@sendevia/pi-ask-author 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{getSelectListTheme as an}from"@earendil-works/pi-coding-agent";import{Editor as un,Key as y,matchesKey as b}from"@earendil-works/pi-tui";import{stripTerminalSequences as rt,truncateToWidth as ie,visibleWidth as be,wrapTextWithAnsi as st}from"@earendil-works/pi-tui";var T={dividerChar:" │ ",dividerThick:"═",dividerThin:"─",dividerWidth:3,leftColMax:46,leftColMin:30,leftColRatio:.42,splitViewMinWidth:72,tabLabelMaxWidth:14,previewScrollStep:3,singlePreviewHeight:7,splitPreviewHeight:14,summaryPageSize:16,summaryScrollStep:3,visibleOptionCount:7,statusDurationMs:3e3},O={cancel:"󰜺",check:"󰄬",checked:"󰐾",unchecked:"󰄰",error:"󰅚",note:"󰷬",cursor:"",scrollUp:"",scrollDown:"",checkedMulti:"[󰄬] ",uncheckedMulti:"[ ] ",checkedSingle:"(•) ",uncheckedSingle:"( ) "},M=30,R=20;function I(e,t,i){return Math.max(t,Math.min(e,i))}function Q(e,t,i){return I(e,0,Math.max(0,t-i))}function G(e,t,i){return e.slice(t,t+i)}function N(e){return e?e.replace(/\t/g," ").replace(/\r/g,""):""}function lt(e){return rt(e).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function w(e){let t=e?.trim();return t&&lt(N(t))||void 0}function D(e){if("string"==typeof e){if(e.length>1e6)return;try{return JSON.parse(e)}catch{return}}return e}function at(e,t,i){let o=be(e);o>=i&&i>0&&(e=ie(e,i-1),o=be(e));let n=Math.max(1,i-o),r=" ".repeat(o),s=st(t,n);return 0===s.length?e?[e]:[]:s.map((t,i)=>0===i?e+t:r+t)}function C(e,t,i,o=""){e.push(...at(o,t,i))}function L(e,t){return t<=0?"":ie(N(e),t)}function j(e,t){return t<=0?"":ie(N(e),t,"...",!0)}function re(e,t=T.dividerThin){return e>0?t.repeat(e):""}var ut={" ":" ","【":"[","】":"]"};function se(e){if(1!==e.length)return e;let t=ut[e];if(void 0!==t)return t;let i=e.charCodeAt(0);return i>=65281&&i<=65374?String.fromCharCode(i-65248):e}function ge(e){return e.replace(/\s+/g," ").trim()}var le={tool:{label:"Consult Author"},command:{name:"ask-author",description:"Show the ask_author consultation tool reference",notify:"Ask the AI to call ask_author in your prompt to consult you on creative decisions"},common:{optionSeparator:", ",bulletPrefix:"• ",helpSeparator:" • "},tabs:{questionTab:{template:"Q{index}",params:["index"]},submitTab:{template:"{icon.check} Submit"}},view:{modeSingle:"[Single]",conditionalBadge:"[Conditional]",modeMultiAtLeast:{template:"[Multi, at least {min}{maxPart}]",params:["min","maxPart"]},modeMultiOptional:{template:"[Multi, optional{maxPart}]",params:["maxPart"]},modeMultiUnconstrained:{template:"[Multi{maxPart}]",params:["maxPart"]},modeMultiMaxPart:{template:", up to {max}",params:["max"]},attachedNoteBanner:{template:"{icon.note} Question note: {text}",params:["text"]},optionAttachedNoteBanner:{template:"{icon.note} [{label}] option note: {text}",params:["label","text"]},listTopMore:{template:" {icon.scrollUp} {count} more above",params:["count"]},listBottomMore:{template:" {icon.scrollDown} {count} more below",params:["count"]},optionNotePanelTitle:"Option Note",storyDescriptionPanelTitle:"Plot Deduction",storyDraftPanelTitle:"Draft / Storyboard Preview",customNotePanelTitle:"Question Note",confirmPanelTitle:"Controls",customNotePanelCurrent:"Current content:",previewScrollInfo:{template:"(lines {start}-{end}/{total}, use [ ] to scroll)",params:["start","end","total"]},previewNoDraft:"(nothing to preview)",customNotePanelTips:['• Press "N", or select this item and press "Enter", to write or edit the question note','• Press "x" to clear the question note',"• The note is submitted together with the selected options and their option notes"],confirmPanelTips:["• Press `Enter` to confirm this question and move on to the next one","• Confirming the last question opens the summary and submit page"],sectionTitle:{template:"### {title}",params:["title"]},fieldLabel:{template:"**{label}**",params:["label"]},italicLine:{template:"_{text}_",params:["text"]}},menu:{customNoteLabel:{template:"{icon.note} Question note"},customNoteLabelFilled:{template:"{icon.note} Question note (filled)"},confirmDetailMulti:{template:"{selectedCount} selected",params:["selectedCount","minSelect"]},confirmDetailMultiBelowMin:{template:"{selectedCount}/{minSelect} selected",params:["selectedCount","minSelect"]},confirmLabel:{template:"{icon.check} Confirm question ({detail}{noteSuffix})",params:["detail","noteSuffix"]},confirmNoteSuffix:" + note",confirmDesc:"Confirm and continue to the next question or the summary"},editor:{title:{template:" {icon.note} Question note ({questionTitle})",params:["questionTitle"]},optionTitle:{template:" {icon.note} Option note ({optionLabel} - {questionTitle})",params:["questionTitle","optionLabel"]},footerHelp:" [Enter] save and return • [Esc/Ctrl+C] cancel"},status:{questionNoteSaved:"Question note saved",noteCleared:"Question note cleared",optionNoteSaved:{template:"Saved note for {label}",params:["label"]},optionNoteSavedUnselected:{template:"Saved note for {label} (option not selected; submitted as a note only)",params:["label"]},optionNoteSavedAtLimit:{template:"Limit reached (up to {max} options): note saved, option left unselected",params:["max"]},optionNoteCleared:{template:"Cleared note for {label}",params:["label"]},selectedUpToLimit:{template:"Selection limit reached (up to {limit} items)",params:["limit"]},maxSelectExceeded:{template:'Limit reached (up to {max} items): press "Space" to deselect an item first',params:["max"]},minSelectRequired:{template:'Below minimum (at least {min} required): press "Space" to select more, or press "n/N" to write a note',params:["min"]},pleaseAnswerBeforeSubmit:'Question not answered: press "Space/Enter" to pick an option, or press "n/N" to write a note',editorDiscardConfirm:"Press Esc/Ctrl+C again to discard changes (unsaved content will be lost); keep typing to cancel",errorNonTui:"The current environment is not an interactive terminal, so the interface cannot start; retry in an interactive TUI session",errorNoQuestions:"No valid question or option was provided; provide at least one question with options",errorInvalidCondition:{template:"Invalid adaptive condition: {details} (make showIf reference an earlier question and an existing option label, or use answered)",params:["details"]},errorExecutionFailed:{template:"Component failure: {reason} (fix the arguments and retry)",params:["reason"]}},help:{cancel:"Esc/Ctrl+C cancel",clearNote:"x clear note",confirmQuestion:"Enter confirm",confirmSubmit:"Enter submit",editNote:"n question note",editOptionNote:"n option note",editQuestionNote:"N question note",jumpQuestion:"1-9 jump to question",moveCursor:"↑↓/jk move",scrollDraft:"[ ] scroll draft",scrollSummary:"↑↓/[ ] scroll",selectOptionSingle:"Space/Enter select",switchQuestion:"Tab/←→/hl switch question",toggleAll:"a select/clear all",toggleCheckMulti:"Space toggle"},summary:{title:"[Answer Summary]",statusDone:"[Done]",statusPending:"[Pending]",questionPrefix:{template:"Q{index}: {title}",params:["index","title"]},selectedLabel:"Selected:",optionNoteBadge:{template:"({icon.note} note)"},optionNotePrefix:{template:"{icon.note} Option note ({optLabel}):",params:["optLabel"]},customNoteLabel:{template:"{icon.note} Question note:"},allDonePrompt:{template:" {icon.check} All questions answered; press Enter/Ctrl+S to submit, Tab/hl/1-9 to revise"},pendingWarning:{template:" {icon.unchecked} Some questions are unanswered; press Enter to answer, Tab/hl/1-9 to switch"},topMore:{template:" {icon.scrollUp} {count} more lines above",params:["count"]},bottomMore:{template:" {icon.scrollDown} {count} more lines below",params:["count"]}},card:{callQuestionAndOptionCount:{template:"{qCount} questions • {optCount} options",params:["qCount","optCount"]},callOptionCountOnly:{template:"{optCount} options",params:["optCount"]},resultCancelled:{template:"{icon.cancel} Cancelled"},resultErrorShort:{template:"{icon.error} Failed"},resultCompleted:{template:"{icon.check} Completed"},resultCount:{template:"{n} items",params:["n"]},optionBullet:{template:"• {title}: {content}",params:["title","content"]},optionWithNote:{template:"{label} [{icon.note} {note}]",params:["label","note"]},questionNoteTag:{template:" ({icon.note} question note: {text})",params:["text"]},errorBullet:{template:"• Error: {err}",params:["err"]}},fallbacks:{defaultFormTitle:"Creative Decision",defaultQuestionTitle:"Choose the next creative option",defaultCustomPlaceholder:"Enter overall requirements, foreshadowing details, or revision notes for this question...",defaultOptionCustomPlaceholder:"Enter specific requirements or revision details for this option...",defaultCustomChoiceName:"Custom option",defaultOptionLabel:"Default option",unnamedOptionLabel:"Unnamed option",unselectedOption:"Not selected",autoQuestionId:{template:"q_{n}",params:["n"]},autoQuestionTitle:{template:"Question {n}",params:["n"]},autoOptionLabel:{template:"Option {n}",params:["n"]}}},we={tool:{label:"向作者请示"},command:{name:"ask-author",description:"查看 ask_author 创作请示工具说明",notify:"在提示词中指示 AI 调用 ask_author,即可向您请示创作决策"},common:{optionSeparator:"、",bulletPrefix:"• ",helpSeparator:" • "},tabs:{questionTab:{template:"第{index}题",params:["index"]},submitTab:{template:"{icon.check} 提交答卷"}},view:{modeSingle:"[单选]",conditionalBadge:"[条件显示]",modeMultiAtLeast:{template:"[多选 至少{min}项{maxPart}]",params:["min","maxPart"]},modeMultiOptional:{template:"[多选 可不选{maxPart}]",params:["maxPart"]},modeMultiUnconstrained:{template:"[多选{maxPart}]",params:["maxPart"]},modeMultiMaxPart:{template:" 至多{max}项",params:["max"]},attachedNoteBanner:{template:"{icon.note} 题目补充说明:{text}",params:["text"]},optionAttachedNoteBanner:{template:"{icon.note} [{label}] 选项补充说明:{text}",params:["label","text"]},listTopMore:{template:" {icon.scrollUp} 向上还有 {count} 项",params:["count"]},listBottomMore:{template:" {icon.scrollDown} 向下还有 {count} 项",params:["count"]},optionNotePanelTitle:"选项补充说明",storyDescriptionPanelTitle:"情节设定推演",storyDraftPanelTitle:"正文草稿/分镜头试撰写",customNotePanelTitle:"题目补充说明",confirmPanelTitle:"操作说明",customNotePanelCurrent:"当前填写内容:",previewScrollInfo:{template:"(行 {start}-{end}/{total},用 [ ] 滚动)",params:["start","end","total"]},previewNoDraft:"(无内容预览)",customNotePanelTips:["• 随时按「N」或选择此项按「Enter」填写/修改本题补充说明","• 按「x」清空本题补充说明","• 补充说明将随所选选项及选项专属补充说明一并提交给 AI 助手"],confirmPanelTips:["• 按 `Enter` 确认本题并前往下一题","• 最后一题确认后自动进入总览提交页"],sectionTitle:{template:"### {title}",params:["title"]},fieldLabel:{template:"**{label}**",params:["label"]},italicLine:{template:"_{text}_",params:["text"]}},menu:{customNoteLabel:{template:"{icon.note} 题目补充说明"},customNoteLabelFilled:{template:"{icon.note} 题目补充说明 (已填写)"},confirmDetailMulti:{template:"已选 {selectedCount} 项",params:["selectedCount","minSelect"]},confirmDetailMultiBelowMin:{template:"已选 {selectedCount}/{minSelect} 项",params:["selectedCount","minSelect"]},confirmLabel:{template:"{icon.check} 确认本题 ({detail}{noteSuffix})",params:["detail","noteSuffix"]},confirmNoteSuffix:" + 补充说明",confirmDesc:"确认并前往下一题或总览页"},editor:{title:{template:" {icon.note} 填写题目补充说明({questionTitle})",params:["questionTitle"]},optionTitle:{template:" {icon.note} 填写选项补充说明({optionLabel} - {questionTitle})",params:["questionTitle","optionLabel"]},footerHelp:" [Enter] 保存并返回 • [Esc/Ctrl+C] 取消"},status:{questionNoteSaved:"已保存本题补充说明",noteCleared:"已清空本题补充说明",optionNoteSaved:{template:"已保存「{label}」补充说明",params:["label"]},optionNoteSavedUnselected:{template:"已保存「{label}」批注(该选项未勾选,仅作批注提交)",params:["label"]},optionNoteSavedAtLimit:{template:"已达上限(至多 {max} 项):批注已保存,但该选项未勾选",params:["max"]},optionNoteCleared:{template:"已清空「{label}」补充说明",params:["label"]},selectedUpToLimit:{template:"已达选择上限(至多 {limit} 项)",params:["limit"]},maxSelectExceeded:{template:"已达上限(至多 {max} 项):请按「空格」取消已选项后重选",params:["max"]},minSelectRequired:{template:"未达下限(至少需 {min} 项):请按「空格」继续勾选,或按「n/N」填写说明",params:["min"]},pleaseAnswerBeforeSubmit:"本题未完成:请按「空格/Enter」选定选项,或按「n/N」填写补充说明",editorDiscardConfirm:"再次按 Esc/Ctrl+C 放弃修改(未保存内容将丢失),继续输入可撤销",errorNonTui:"当前为非交互式终端环境,无法启动交互界面,请在交互式 TUI 会话中重试",errorNoQuestions:"未提供有效的问题或选项,请提供至少一个带选项的问题",errorInvalidCondition:{template:"自适应条件无效:{details}(请让 showIf 指向更早的题目,并引用该题已有选项的标签,或改用 answered)",params:["details"]},errorExecutionFailed:{template:"组件执行异常:{reason}(可修正参数后重试)",params:["reason"]}},help:{cancel:"Esc/Ctrl+C 取消",clearNote:"x 清空补充说明",confirmQuestion:"Enter 确认",confirmSubmit:"Enter 提交",editNote:"n 补充说明",editOptionNote:"n 选项补充说明",editQuestionNote:"N 题目补充说明",jumpQuestion:"1~9 跳转题目",moveCursor:"↑↓/jk 移动",scrollDraft:"[ ] 滚动草稿",scrollSummary:"↑↓/[ ] 滚动",selectOptionSingle:"空格/Enter 选定",switchQuestion:"Tab/←→/hl 切换题目",toggleAll:"a 全选/清空",toggleCheckMulti:"空格 勾选"},summary:{title:"【答卷总览与确认】",statusDone:"[已完成]",statusPending:"[未完成]",questionPrefix:{template:"第{index}题:{title}",params:["index","title"]},selectedLabel:"已选:",optionNoteBadge:{template:"({icon.note} 批注)"},optionNotePrefix:{template:"{icon.note} 选项补充说明({optLabel}):",params:["optLabel"]},customNoteLabel:{template:"{icon.note} 题目补充说明:"},allDonePrompt:{template:" {icon.check} 全部完成,按 Enter/Ctrl+S 提交答卷,Tab/hl/1-9 返回修改"},pendingWarning:{template:" {icon.unchecked} 尚有题目未完成,按 Enter 前往作答,Tab/hl/1-9 切换修改"},topMore:{template:" {icon.scrollUp} 向上还有 {count} 行",params:["count"]},bottomMore:{template:" {icon.scrollDown} 向下还有 {count} 行",params:["count"]}},card:{callQuestionAndOptionCount:{template:"{qCount} 题 • {optCount} 选项",params:["qCount","optCount"]},callOptionCountOnly:{template:"{optCount} 选项",params:["optCount"]},resultCancelled:{template:"{icon.cancel} 已取消"},resultErrorShort:{template:"{icon.error} 执行失败"},resultCompleted:{template:"{icon.check} 已完成"},resultCount:{template:"{n} 项",params:["n"]},optionBullet:{template:"• {title}:{content}",params:["title","content"]},optionWithNote:{template:"{label} [{icon.note} {note}]",params:["label","note"]},questionNoteTag:{template:" ({icon.note} 题目补充说明: {text})",params:["text"]},errorBullet:{template:"• 错误原因:{err}",params:["err"]}},fallbacks:{defaultFormTitle:"创作决策",defaultQuestionTitle:"请选择接下来的创作方案",defaultCustomPlaceholder:"输入本题整体补充要求、伏笔细节或修改意见...",defaultOptionCustomPlaceholder:"输入针对该选项的具体补充要求或修改细节...",defaultCustomChoiceName:"自定义方案",defaultOptionLabel:"默认方案",unnamedOptionLabel:"未命名方案",unselectedOption:"未选",autoQuestionId:{template:"q_{n}",params:["n"]},autoQuestionTitle:{template:"问题 {n}",params:["n"]},autoOptionLabel:{template:"选项 {n}",params:["n"]}}},ye={en_US:le,zh_CN:we},Te="en_US",pt=["LANGUAGE","LC_ALL","LC_MESSAGES","LANG"];function mt(e){let t=e.trim().split(/[.@]/)[0]??"";if(!t||/^(c|posix)$/i.test(t))return;let i=t.replace(/-/g,"_").split("_"),o=i[0];if(!o)return;let n=i[1];return n?`${o.toLowerCase()}_${n.toUpperCase()}`:o.toLowerCase()}function xe(e,t){let i=[];for(let t of pt){let o=e[t];o&&("LANGUAGE"===t?i.push(...o.split(":")):i.push(o))}t&&i.push(t);let o=Object.keys(ye);for(let e of i){let t=mt(e);if(!t)continue;let i=o.find(e=>e.toLowerCase()===t);if(i)return i;let n=t.split("_")[0],r=o.find(e=>e.toLowerCase().split("_")[0]===n);if(r)return r}return Te}var ve=xe(process.env,Intl.DateTimeFormat().resolvedOptions().locale);function ft(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&"string"==typeof e.template}function Se(e){return"string"==typeof e?"text":ft(e)?"template":Array.isArray(e)?"list":"group"}function ht(e,t,i){let o=[],n=0;for(let r of e.template.matchAll(/\{([^{}]+)\}/g)){let s=r.index,l=(r[1]??"").trim();o.push(e.template.slice(n,s));let a=t.indexOf(l);if(a>=0)o.push(a);else{let t=i(l);if(void 0===t)throw new Error(`语言资源模板存在未声明的占位符 {${l}}:${e.template}`);o.push(t)}n=s+r[0].length}return o.push(e.template.slice(n)),(...i)=>{if(i.length!==t.length)throw new Error(`语言资源模板形参数量不匹配(声明 ${t.length},实际 ${i.length}):${e.template}`);return o.map(e=>"string"==typeof e?e:String(i[e])).join("")}}function Ce(e,t,i,o){let n=Se(e);if(void 0!==t&&Se(t)!==n)throw new Error(`语言资源键 ${o} 的取值种类与 ${Te} 不一致`);let r=t??e;if("template"===n){let t=e.params??[],o=ht(r,t,i);return 0===t.length?o():o}if("text"===n)return r;if("list"===n)return[...r];let s=r,l={};for(let[t,n]of Object.entries(e))l[t]=Ce(n,s[t],i,o?`${o}.${t}`:t);return l}function Ae(e){return Ce(le,ye[ve],e,"")}var K={tool:{name:"ask_author",description:"Ask the author to choose between concrete narrative directions. Supports one question or a batch of related questions, with options, optional Markdown draft previews, author notes, and conditional follow-ups based on earlier answers.",promptSnippet:"Ask the author to choose narrative directions with options, draft previews, and conditional follow-ups",promptGuidelines:["ask_author: Call it directly when the author must choose a plot branch, character action, scene direction, or setting; do not ask the same question in chat first.","ask_author: Use flat mode (formTitle + question + options) for one decision, or the questions array for related decisions. Batch related choices into one call instead of consecutive calls, always give a concise formTitle, and add tabLabel when a long question title needs a short tab name.","ask_author: Label options with concrete actions and put consequences in description. Add preview only when a Markdown draft or storyboard helps the author judge.","ask_author: Omit optional fields that use defaults. Add a question id only when a later showIf references it, and point showIf at an earlier question id plus one of its option labels, or answered.","ask_author: The author may choose multiple options, add notes, and edit drafts. Confirmed drafts return as [Draft directive: ...] lines.","ask_author: [Author Decision Cancelled] means drop the decision. [Author Consultation Error] means fix the arguments and retry once, then continue without the confirmation."]},schema:{optionLabel:"Concrete action or choice label",optionDesc:"Consequences or rationale (optional)",optionPreview:"Markdown draft or storyboard excerpt (optional)",optionCustomPlaceholder:"Placeholder for the option note (optional)",optionShowIf:"Show only when an earlier answer matches (condition or array; all must hold)",questionId:"Stable id for showIf references (optional)",questionTitle:"Question text",questionTabLabel:"Short label for the tab bar (default: Q<index>)",questionDesc:"Context for the question (optional)",questionMultiSelect:"Allow multiple selections (default false)",questionMinSelect:"Minimum selections (default 1)",questionMaxSelect:"Maximum selections (default: all options)",questionAllowEmpty:"Allow submitting with no selection (default false)",questionOptions:`Candidate options (1-${M}, 2-10 recommended)`,questionAllowCustom:"Allow author notes (default true)",questionCustomPlaceholder:"Placeholder for the author note (optional)",questionShowIf:"Show only when an earlier answer matches (condition or array; all must hold)",conditionQuestionId:"Id of an earlier question",conditionOption:"Option label that activates the condition",conditionAnswered:"Match any answer (default true) or no answer (false); ignored with option",formTitle:"Short title for the consultation",formDesc:"Overall context (optional)",formQuestions:`Related questions (1-${R}); batch related decisions into one call`,formSingleQuestion:"Question for flat mode",flatPrefix:"(Flat single-question mode only) ",flatQuestionOptions:`Options for flat mode (1-${M}, 2-10 recommended)`},markdown:{envelopePrefix:"[Author Decision Finalized]",envelopeSuffix:"Proceed with the author decisions and draft directives above without conversational acknowledgment.",envelopeCancelled:"[Author Decision Cancelled]\nThe author cancelled. Do not proceed with the discarded decision; propose next steps or ask for clarification.",envelopeError:(e,t)=>`[Author Consultation Error]\nFailed to consult author: ${e}\nGuidance: ${t}`,errorReasons:{nonTui:"Interactive TUI is unavailable in the current mode.",noQuestions:"No questions or options were provided.",runtimeError:e=>`Consultation UI failed: ${e}`,invalidCondition:e=>`Invalid showIf condition: ${e}`},errorGuidances:{nonTui:"Use defaults, or ask the user in chat if the decision is crucial.",noQuestions:"Provide at least one question with concrete options.",runtimeError:"Check the arguments and retry with valid questions and options.",invalidCondition:"Reference an earlier question id plus one of its option labels, or use answered."},adaptiveErrors:{unknownQuestion:e=>`showIf references unknown question id "${e}"`,forwardQuestion:e=>`showIf may only reference an earlier question, got "${e}"`,unknownOption:(e,t)=>`showIf option "${t}" does not exist in question "${e}"`},envelopeEmpty:"The author submitted no answers. Use your defaults, or ask a follow-up if the decision is crucial.",noSelection:"(No selection; the author skipped this question)",notePrefix:"[Author note: ",noteSuffix:"]",draftDirectivePrefix:"[Draft directive: ",draftDirectiveSuffix:"]",answerLine:(e,t,i)=>`${e}. [${t}]: ${i}`,partSeparator:"; ",draftSegmentSeparator:" / ",optionWithDesc:(e,t,i,o)=>`【${e}】${t}${o?` ${o}`:""}${i?` ${i}`:""}`,optionWithoutDesc:(e,t,i)=>`【${e}】${i?` ${i}`:""}${t?` ${t}`:""}`,unselectedOptionNote:(e,t)=>`[Author note on unselected option 【${e}】] ${t}`,fallbackQuestionTitle:e=>`Question ${e}`,fallbackOptionLabel:e=>`Option ${e}`}},bt=e=>e.startsWith("icon.")?O[e.slice(5)]:void 0,v=Ae(bt),gt=(e,t,i,o)=>{let n=t<i?v.view.modeMultiMaxPart(t):"";return e>1?v.view.modeMultiAtLeast(e,n):0===e||o?v.view.modeMultiOptional(n):v.view.modeMultiUnconstrained(n)},wt=(e,t)=>e<t?v.menu.confirmDetailMultiBelowMin(e,t):v.menu.confirmDetailMulti(e,t),St=(e,t)=>v.menu.confirmLabel(e,t?v.menu.confirmNoteSuffix:""),r={tool:{...K.tool,label:v.tool.label},schema:K.schema,markdown:K.markdown,command:v.command,common:v.common,tabs:v.tabs,view:{...v.view,modeMulti:gt},menu:{...v.menu,confirmDetailMulti:wt,confirmLabel:St},editor:v.editor,status:v.status,help:v.help,summary:v.summary,card:v.card,fallbacks:v.fallbacks};import{truncateToWidth as Ot,visibleWidth as ae,wrapTextWithAnsi as Nt}from"@earendil-works/pi-tui";var P=class extends Error{constructor(e){super(e),this.name="AdaptiveConditionError"}};function F(e){return!!e.customText?.trim()}function yt(e){for(let t of e.optionNotes.values())if(t?.trim())return!0;return!1}function Tt(e){return F(e)||yt(e)}function xt(e,t,i){let o=void 0!==e,n=I(e??1,0,i);return{minSelect:n,minSelectExplicit:o,maxSelect:I(t??i,n,i)}}function Ie(e){return e?(Array.isArray(e)?e:[e]).map(e=>({questionId:e.questionId,option:e.option,answered:e.answered})):[]}function vt(e,t){return{question:{id:w(e.id)??r.fallbacks.autoQuestionId(t+1),title:w(e.title)??r.fallbacks.autoQuestionTitle(t+1),tabLabel:w(e.tabLabel),description:w(e.description),multiSelect:!!e.multiSelect,...xt(e.minSelect,e.maxSelect,e.options.length),options:e.options.map(e=>({label:w(e.label)??r.fallbacks.unnamedOptionLabel,description:w(e.description),preview:w(e.preview),customPlaceholder:w(e.customPlaceholder),showIf:[]})),allowEmpty:!!e.allowEmpty,allowCustom:!1!==e.allowCustom,customPlaceholder:w(e.customPlaceholder)??r.fallbacks.defaultCustomPlaceholder,showIf:[]},questionConditions:Ie(e.showIf),optionConditions:e.options.map(e=>Ie(e.showIf))}}function Oe(e,t,i,o){return e.map(e=>{let n=w(e.questionId)??"",s=i.get(n);if(void 0===s)throw new P(r.markdown.adaptiveErrors.unknownQuestion(n));if(s>=t)throw new P(r.markdown.adaptiveErrors.forwardQuestion(n));let l=w(e.option);if(void 0===l)return{kind:"answered",questionIndex:s,answered:!1!==e.answered};let a=o[s]?.options.findIndex(e=>e.label===l)??-1;if(a<0)throw new P(r.markdown.adaptiveErrors.unknownOption(n,l));return{kind:"option",questionIndex:s,optionIndex:a}})}function Ne(e){let t=e.map((e,t)=>vt(e,t)),i=Ct(t.map(e=>e.question)),o=new Map(i.map((e,t)=>[e.id,t]));return i.map((e,n)=>{let r=t[n];return{...e,showIf:Oe(r?.questionConditions??[],n,o,i),options:e.options.map((e,t)=>({...e,showIf:Oe(r?.optionConditions[t]??[],n,o,i)}))}})}function ke(e,t){let i={label:e.label,description:e.description,preview:e.preview,customPlaceholder:e.customPlaceholder};return t&&(i.customText=t),i}function Ct(e){let t=new Set;return e.map((e,i)=>{if(!t.has(e.id))return t.add(e.id),e;let o=r.fallbacks.autoQuestionId(i+1);for(let e=2;t.has(o);e++)o=`${o}_${e}`;return t.add(o),{...e,id:o}})}function V(e){return ge(e).replace(/[“”„‟«»]/g,"'").replace(/[\[\]]/g,e=>"["===e?"[":"]").replace(/[【】]/g,"").replace(/;/g,";")}function At(e){if(!e)return;let t=N(e);if(!t.trim())return;let i=t.split("\n").map(e=>{let t=e.trim();return t?(t=t.replace(/^(?:[>#]+\s*)+/,""),t=t.replace(/\s+/g," "),t):""}).filter(Boolean);return 0!==i.length?i.join(r.markdown.draftSegmentSeparator):void 0}function It(e,t){return void 0===t?e:e===r.fallbacks.defaultQuestionTitle||e===r.fallbacks.autoQuestionTitle(t+1)?r.markdown.fallbackQuestionTitle(t+1):e}function Le(e,t){return void 0===t?e:e===r.fallbacks.unnamedOptionLabel||e===r.fallbacks.defaultOptionLabel||e===r.fallbacks.autoOptionLabel(t)?r.markdown.fallbackOptionLabel(t):e}var z=class{formTitle;formDescription;questions;revisionValue=0;states=new Map;visibilityCache;constructor(e){let t=e.questions??[],i=t.length>0;this.formTitle=w(e.formTitle)??r.fallbacks.defaultFormTitle,this.formDescription=w(e.description),this.questions=i?Ne(t):e.options?.length?Ne([{title:w(e.question)??r.fallbacks.defaultQuestionTitle,description:w(e.description),multiSelect:e.multiSelect,minSelect:e.minSelect,maxSelect:e.maxSelect,allowEmpty:e.allowEmpty,options:e.options,allowCustom:e.allowCustom,customPlaceholder:e.customPlaceholder}]):[]}get revision(){return this.revisionValue}get questionCount(){return this.questions.length}getQuestion(e){return this.questions[e]}getState(e){let t=this.states.get(e);return t||(t={selectedIndices:new Set,optionNotes:new Map},this.states.set(e,t)),t}snapshot(){let e=this.visibilityCache;if(e&&e.revision===this.revisionValue)return e;let t=[],i=[],o=[];for(let[e,n]of this.questions.entries()){let r=n.showIf.every(e=>this.conditionHolds(e,t,o)),s=n.options.map(e=>e.showIf.every(e=>this.conditionHolds(e,t,o))),l=this.states.get(e),a=[];if(l)if(n.multiSelect)for(let e of l.selectedIndices)s[e]&&a.push(e);else void 0!==l.selectedIndex&&s[l.selectedIndex]&&a.push(l.selectedIndex);a.sort((e,t)=>e-t),t.push(r),i.push(s),o.push(a)}return this.visibilityCache={revision:this.revisionValue,questions:t,options:i,selected:o},this.visibilityCache}conditionHolds(e,t,i){return!!t[e.questionIndex]&&("answered"===e.kind?this.hasAnyResponse(e.questionIndex)===e.answered:(i[e.questionIndex]??[]).includes(e.optionIndex))}hasAnyResponse(e){let t=this.states.get(e);return!!t&&(void 0!==t.selectedIndex||t.selectedIndices.size>0||Tt(t))}isQuestionVisible(e){return this.snapshot().questions[e]??!1}isOptionVisible(e,t){return this.snapshot().options[e]?.[t]??!1}getVisibleQuestionIndices(){let{questions:e}=this.snapshot(),t=[];for(let[i,o]of e.entries())o&&t.push(i);return t}getSelectedIndices(e){return[...this.snapshot().selected[e]??[]]}getSelectedIndex(e){return this.snapshot().selected[e]?.[0]}bumpRevision(){this.revisionValue++}getMenuItems(e){let t=this.getQuestion(e);if(!t)return[];let i=this.getState(e),o=this.hasSubmittableNote(e),n=[];for(let[i,o]of t.options.entries())this.isOptionVisible(e,i)&&n.push({type:"option",optionIndex:i,label:o.label,description:o.description,preview:o.preview});t.allowCustom&&n.push({type:"custom_note",label:F(i)?r.menu.customNoteLabelFilled:r.menu.customNoteLabel});let s=this.getSelectedIndex(e),l=t.multiSelect?r.menu.confirmDetailMulti(this.getSelectedIndices(e).length,t.minSelect):void 0!==s?t.options[s]?.label??r.fallbacks.unselectedOption:o?r.fallbacks.defaultCustomChoiceName:r.fallbacks.unselectedOption;return n.push({type:"confirm_btn",label:r.menu.confirmLabel(l,o),description:r.menu.confirmDesc}),n}hasSubmittableNote(e){let t=this.states.get(e);if(!t)return!1;if(t.customText?.trim())return!0;for(let[i,o]of t.optionNotes)if(o?.trim()&&this.isOptionVisible(e,i))return!0;return!1}isQuestionAnswered(e){let t=this.questions[e];if(!t||!this.isQuestionVisible(e))return!1;if(!t.multiSelect)return void 0!==this.getSelectedIndex(e)||t.allowEmpty||t.allowCustom&&this.hasSubmittableNote(e);let i=this.getSelectedIndices(e).length;return!!(i>=t.minSelect||0===i&&t.allowEmpty||!t.minSelectExplicit&&0===i&&t.allowCustom&&this.hasSubmittableNote(e))}areAllQuestionsAnswered(){return this.getVisibleQuestionIndices().every(e=>this.isQuestionAnswered(e))}toggleOption(e,t){let i=this.getQuestion(e);if(!i||!i.options[t])return"limit";let o=this.getState(e);return i.multiSelect?o.selectedIndices.has(t)?(o.selectedIndices.delete(t),this.bumpRevision(),"deselected"):this.getSelectedIndices(e).length>=i.maxSelect?"limit":(o.selectedIndices.add(t),this.bumpRevision(),"selected"):(o.selectedIndex=o.selectedIndex===t?void 0:t,this.bumpRevision(),void 0===o.selectedIndex?"deselected":"selected")}commitOption(e,t){let i=this.getQuestion(e);if(!i||!i.options[t])return;let o=this.getState(e);i.multiSelect?o.selectedIndices.has(t)||this.getSelectedIndices(e).length>=i.maxSelect||(o.selectedIndices.add(t),this.bumpRevision()):o.selectedIndex!==t&&(o.selectedIndex=t,this.bumpRevision())}selectAllOrClear(e){let t=this.getQuestion(e);if(!t||!t.multiSelect)return"cleared";let i=this.getState(e);if(this.getSelectedIndices(e).length>=t.maxSelect)return i.selectedIndices.clear(),this.bumpRevision(),"cleared";let o=this.getSelectedIndices(e).length;for(let[n]of t.options.entries()){if(o>=t.maxSelect)break;!this.isOptionVisible(e,n)||i.selectedIndices.has(n)||(i.selectedIndices.add(n),o++)}return this.bumpRevision(),"filled"}setOptionNote(e,t,i){let o=this.getQuestion(e);if(!o||!o.options[t])return"cleared";let n=this.getState(e),r=w(i);return this.bumpRevision(),r?(n.optionNotes.set(t,r),o.multiSelect?this.getSelectedIndices(e).includes(t)?"saved":this.getSelectedIndices(e).length>=o.maxSelect?"savedAtLimit":(n.selectedIndices.add(t),"saved"):void 0===n.selectedIndex?(n.selectedIndex=t,"saved"):n.selectedIndex===t?"saved":"savedUnselected"):(n.optionNotes.delete(t),"cleared")}setQuestionNote(e,t){let i=this.getState(e),o=w(t);return i.customText=o,this.bumpRevision(),o?"saved":"cleared"}clearOptionNote(e,t){let i=this.states.get(e);return!!i?.optionNotes.has(t)&&(i.optionNotes.delete(t),this.bumpRevision(),!0)}clearQuestionNote(e){let t=this.states.get(e);return!!t?.customText?.trim()&&(t.customText=void 0,this.bumpRevision(),!0)}collectOptionNotes(e,t,i){let o={};if(!i)return o;for(let[n,r]of i.optionNotes){let i=w(r);i&&t.options[n]&&this.isOptionVisible(e,n)&&(o[n+1]=i)}return o}compileAnswers(){let e=[];for(let[t,i]of this.questions.entries()){if(!this.isQuestionVisible(t))continue;let o=this.states.get(t),n=o?.customText?.trim()?N(o.customText.trim()):void 0,r={questionId:i.id,questionTitle:i.title,customText:n};if(i.multiSelect){let n=this.getSelectedIndices(t),s=this.collectOptionNotes(t,i,o),l=[];for(let e of n){let t=i.options[e];t&&l.push(ke(t,s[e+1]))}let a=Object.keys(s).length>0;e.push({...r,multiSelect:!0,selectedOptions:l,selectedIndices:n.map(e=>e+1),optionNotes:a?s:void 0})}else{let n=this.getSelectedIndex(t);if(void 0!==n){let s=i.options[n],l=this.collectOptionNotes(t,i,o);e.push({...r,multiSelect:!1,selectedOption:s?ke(s,l[n+1]):void 0,selectedOptionIndex:n+1,optionNotes:Object.keys(l).length>0?l:void 0})}else if(this.isQuestionAnswered(t)){let n=this.collectOptionNotes(t,i,o),s=Object.keys(n).length>0;e.push({...r,multiSelect:!1,optionNotes:s?n:void 0})}}}return e}formatAnswers(e){if(0===e.length)return`${r.markdown.envelopePrefix}\n${r.markdown.envelopeEmpty}\n${r.markdown.envelopeSuffix}`;let t=e=>e?`${r.markdown.notePrefix}${V(e)}${r.markdown.noteSuffix}`:"",i=e=>e?`${r.markdown.draftDirectivePrefix}${V(e)}${r.markdown.draftDirectiveSuffix}`:"",o=new Map(this.questions.map((e,t)=>[e.id,t])),n=e.map((e,n)=>{let s=o.get(e.questionId),l=(e.multiSelect?e.selectedOptions??[]:e.selectedOption?[e.selectedOption]:[]).map((o,n)=>{let s=At(o.preview),l=t(w(o.customText)??""),a=V(Le(o.label,e.multiSelect?e.selectedIndices?.[n]:e.selectedOptionIndex)),u=V(o.description??"");return u?r.markdown.optionWithDesc(a,u,i(s),l):r.markdown.optionWithoutDesc(a,i(s),l)}),a=void 0===s?void 0:this.questions[s];if(a&&e.optionNotes){let i=new Set(e.multiSelect?e.selectedIndices??[]:void 0!==e.selectedOptionIndex?[e.selectedOptionIndex]:[]);for(let[o,n]of Object.entries(e.optionNotes)){let e=Number(o);if(i.has(e))continue;let s=a.options[e-1]?.label;s&&n&&l.push(r.markdown.unselectedOptionNote(V(Le(s,e)),t(n)))}}e.customText&&l.push(t(e.customText));let u=l.join(r.markdown.partSeparator)||r.markdown.noSelection;return r.markdown.answerLine(n+1,V(It(e.questionTitle,s)),u)});return`${r.markdown.envelopePrefix}\n${n.join("\n")}\n${r.markdown.envelopeSuffix}`}};function $(e,t){return e.options[t]?.label??r.fallbacks.autoOptionLabel(t+1)}function kt(e,t,i){return"option"===e.type&&void 0!==e.optionIndex?t.multiSelect?i.selectedIndices.has(e.optionIndex):i.selectedIndex===e.optionIndex:"custom_note"===e.type&&F(i)}function Lt(e,t,i,o){return"option"!==o.type||void 0===o.optionIndex?"":t.multiSelect?i.selectedIndices.has(o.optionIndex)?e.fg("success",O.checkedMulti):e.fg("dim",O.uncheckedMulti):i.selectedIndex===o.optionIndex?e.fg("accent",O.checkedSingle):e.fg("dim",O.uncheckedSingle)}function Ee(e,t,i,o,n,r){let s=kt(t,o,n),l=`${i?e.fg("accent",e.bold(`${O.cursor} `)):" "}${Lt(e,o,n,t)}`,a=ae(l),u=" ".repeat(a),c=Math.max(8,r-a),d=t.label;return"option"===t.type&&void 0!==t.optionIndex&&n.optionNotes.get(t.optionIndex)&&(d=`${t.label} ${O.note}`),(ae(d)<=c?[d]:Nt(d,c)).map((o,n)=>{if(i)return e.bg("selectedBg",e.fg("text",e.bold(j(0===n?`${l}${o}`:`${u}${o}`,r))));let a=e.fg("option"!==t.type&&"custom_note"!==t.type||s?"text":"dim",o);return L(0===n?`${l}${a}`:`${u}${a}`,r)})}function Et(e,t,i){let o=e.getQuestion(t)?.tabLabel;return o?Ot(o,T.tabLabelMaxWidth):r.tabs.questionTab(i)}function Me(e,t,i,o){let n=i===t.questionCount,s=[],l=[];for(let[o,n]of t.getVisibleQuestionIndices().entries()){let r=n===i,s=t.isQuestionAnswered(n),a=s?"success":"muted",u=` ${s?O.checked:O.unchecked} ${Et(t,n,o+1)} `;l.push(r?e.bg("selectedBg",e.fg("accent",e.bold(u))):e.fg(a,u))}let a=` ${r.tabs.submitTab} `;l.push(n?e.bg("selectedBg",e.fg("success",e.bold(a))):e.fg(t.areAllQuestionsAnswered()?"success":"dim",a));let u="",c=0;for(let e of l){let t=ae(e);c>0&&c+1+t>o?(s.push(L(u,o)),u="",c=0):c>0&&(u+=" ",c+=1),u+=e,c+=t}return s.push(L(u,o)),s.push(e.fg("dim",re(o))),s}function Y(e,t,i){i&&(e.push(""),e.push(` ${t.fg("warning",i)}`))}function Mt(e){return e.join(r.common.helpSeparator)}function J(e,t,i,o){C(e,i.fg("dim",Mt(t)),o," ")}function q(e,t,i){e.push(t.fg("accent",re(i,T.dividerThick)))}function Qe(e,t,i,o,n,s){let l=t.getQuestion(i);if(!l)return[];let a=[];if("option"===o?.type){let t=o.optionIndex,i=l.options[t],n=$(l,t),u=i?.customPlaceholder??r.fallbacks.defaultOptionCustomPlaceholder;a.push(e.fg("accent",e.bold(r.editor.optionTitle(l.title,n)))),i?.description&&C(a,e.fg("muted",i.description),s," "),a.push(""),a.push(e.fg("accent",` ${u}`))}else a.push(e.fg("accent",e.bold(r.editor.title(l.title)))),l.description&&C(a,e.fg("muted",l.description),s," "),a.push(""),a.push(e.fg("accent",` ${l.customPlaceholder}`));a.push("");for(let e of n.render(Math.max(10,s-4)))a.push(` ${e}`);return a.push(""),a.push(e.fg("dim",r.editor.footerHelp)),q(a,e,s),a}import{visibleWidth as nn}from"@earendil-works/pi-tui";import{getMarkdownTheme as Qt}from"@earendil-works/pi-coding-agent";import{Markdown as Pt}from"@earendil-works/pi-tui";var Pe=[{opener:"「",closer:"」",marker:"d",maxSpanLength:400,paint:(e,t)=>e.fg("accent",t)},{opener:"(",closer:")",marker:"m",maxSpanLength:400,paint:(e,t)=>e.fg("muted",e.italic(t))}],qe=new Map(Pe.map(e=>[e.opener,e])),Re=new Map(Pe.map(e=>[e.marker,e]));function qt(e){let t=Qt();return{...t,heading:t=>e.fg("accent",e.bold(t)),quote:t=>e.fg("muted",t),quoteBorder:t=>e.fg("dim",t),listBullet:t=>e.fg("accent",t),code:i=>Rt(e,i)??t.code(i),codeBlockBorder:t=>e.fg("dim",t),link:t=>e.fg("accent",t),linkUrl:t=>e.fg("dim",t)}}function Rt(e,t){if(!t.startsWith("\0"))return;let i=[],o=0;for(;o<t.length;){if("\0"!==t.charAt(o))return;let n=Re.get(t.charAt(o+1));if(!n)return;let r=t.indexOf("\0",o+2),s=r<0?t.length:r;i.push(n.paint(e,t.slice(o+2,s))),o=s}return i.length>0?i.join(""):void 0}var $t=/^ {0,3}(`{3,}|~{3,})/,_t=/^ {4,}\S/,Dt=/^ {0,3}(?:<(?=[/!?a-zA-Z])|\|)/,$e=/^ {0,3}(?:\$\$|\\\[)/;function _e(e){for(let t=0;t<e.length;t++){let i=e.charAt(t);if("\\"===i){if("("===e.charAt(t+1)||"["===e.charAt(t+1))return!0;t++;continue}if("$"!==i)continue;let o=e.charAt(t+1);if(""!==o&&!/\s/.test(o))return!0}return!1}var Vt=/^(?: {0,3}>[ \t]?)+/,Ft=/^ {0,3}\[[^\]\n]*\]:/;function Fe(e){return e.replace(Vt,"")}function Bt(e){return!!e.includes("|")&&/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/.test(Fe(e))}var jt=/^ {0,3}(?:#{1,6}[ \t]|[-+*][ \t]|\d{1,9}[.)][ \t]|>|\||`{3,}|~{3,})/,zt=/[`*_\[\]<>$\\|]|~~|&(?:[A-Za-z][A-Za-z0-9]*|#\d+|#[xX][0-9a-fA-F]+);/;function Ut(e){let t=[],i=0;for(let o of e)t.push(i),i+=o.length+1;return t}function Wt(e,t,i){let o=new Uint8Array(e.length),n=(e,t)=>{for(let i=e;i<t;i++)o[i]=1},r=e=>{let o=i[e]??0;n(o,o+(t[e]?.length??0))},s=null,l=!1,a=null;for(let e=0;e<t.length;e++){let i=t[e]??"";if(""===i.trim()){l=!1,null!==s&&r(e),null!==a&&r(e);continue}if(null!==a){r(e);let t=i.indexOf(a);if(t>=0){let e=i.slice(t+a.length);a=null,_e(e)&&(l=!0)}continue}if(null!==s){r(e),s.test(i)&&(s=null);continue}if(l){r(e);continue}if(Bt(i)){r(e),l=!0;let i=t[e-1];void 0!==i&&i.includes("|")&&r(e-1);continue}let o=$t.exec(i),n=o?.[1],u=i.slice(o?.[0].length??0);if(void 0===n||"~"!==n[0]&&u.includes("`"))if(_t.test(i))r(e);else if(Dt.test(Fe(i)))r(e),l=!0;else if(Ft.test(i))r(e);else{if($e.test(i)){let t=i.replace($e,"");r(e),t.includes(t.startsWith("$$")?"$$":"\\]")||(a=t.startsWith("$$")?"$$":"\\]");continue}_e(i)&&(r(e),l=!0)}else r(e),s=new RegExp(`^ {0,3}${n[0]??"`"}{${n.length},}[ \\t]*$`)}let u=0;for(;u<e.length;){if("`"!==e[u]||1===o[u]){u++;continue}let t=0;for(;"`"===e[u+t]&&0===o[u+t];)t++;let i=Xt(e,o,u+t,t);if(i<0)return null;n(u,i+t),u=i+t}return o}function Xt(e,t,i,o){for(let n=i;n<e.length;n++){if("`"!==e[n]||1===t[n])continue;let i=0;for(;"`"===e[n+i]&&0===t[n+i];)i++;if(i===o&&"`"!==e[n+o])return n;n+=i-1}return-1}function Ht(e,t,i,o){let n=[],r=[];for(let s=0;s<e.length;s++){if(1===t[s])continue;let l=e[s]??"",a=qe.get(l);if(void 0!==a){n.push({template:a,start:s});continue}let u=Gt(n,l);if(u<0)continue;let c=n[u];if(n.length=u,!c)continue;let d=s+1;if(d-c.start>c.template.maxSpanLength||zt.test(e.slice(c.start,d)))continue;let m=De(o,c.start),h=De(o,d-1);if(!Kt(i,m,h))continue;let p=r[r.length-1];for(;void 0!==p&&p.startFlat>=c.start;)r.pop(),p=r[r.length-1];r.push({template:c.template,startFlat:c.start,startLine:m,startCol:c.start-(o[m]??0),endLine:h,endCol:d-(o[h]??0)})}return r}function Gt(e,t){for(let i=e.length-1;i>=0;i--)if(e[i]?.template.closer===t)return i;return-1}function De(e,t){let i=0,o=Math.max(0,e.length-1);for(;i<o;){let n=i+o+1>>1;(e[n]??0)<=t?i=n:o=n-1}return i}function Kt(e,t,i){if(t===i)return!0;for(let o=t+1;o<=i;o++){let t=e[o]??"";if(""===t.trim()||jt.test(t))return!1}return!0}function Yt(e,t){let i=[];for(let o of t)i.push(`\0${o.template.marker}${e.slice(o.start,o.end)}`);return`\`${i.join("")}\``}function Jt(e,t){let i=[],o=0,n=0;for(;n<t.length;){let r=t[n];if(!r)break;let s=[r],l=r;for(;n+1<t.length;){let e=t[n+1];if(!e||e.start!==l.end)break;n++,l=e,s.push(e)}let a=r.start,u=l.end,c=e.slice(o,a),d=e.slice(a,u),m="`"===e.charAt(a-1)||"`"===e.charAt(u);i.push(c,m?d:Yt(e,s)),o=u,n++}return i.push(e.slice(o)),i.join("")}function Zt(e,t,i){for(let o=t;o<i;o++)if(1===e[o])return!0;return!1}function en(e,t,i,o){let n=new Map;for(let r of o){let o=(t[r.startLine]??0)+r.startCol,s=(t[r.endLine]??0)+r.endCol;for(let l=r.startLine;l<=r.endLine;l++){let a=t[l]??0,u=a+(e[l]?.length??0),c=Math.max(o,a),d=Math.min(s,u);if(d<=c||Zt(i,c,d))continue;let m={start:c-a,end:d-a,template:r.template},h=n.get(l);h?h.push(m):n.set(l,[m])}}return e.map((e,t)=>{let i=n.get(t);return i?(i.sort((e,t)=>e.start-t.start),Jt(e,i)):e}).join("\n")}function tn(e){if(0===e.length)return e;let t=e.split("\n"),i=Ut(t),o=Wt(e,t,i);if(null===o)return e;let n=Ht(e,o,t,i);return 0===n.length?e:en(t,i,o,n)}function Ve(e,t){return`${r.view.sectionTitle(e)}\n\n${t.map(e=>`${e}\n`).join("")}`}function Be(e,t,i,o,n){if(!e)return[];let s="";"option"===e.type?(i&&(s+=`${r.view.sectionTitle(r.view.optionNotePanelTitle)}\n\n${r.view.fieldLabel(r.view.customNotePanelCurrent)}\n\n${N(i)}\n\n`),e.description&&(s+=`${r.view.sectionTitle(r.view.storyDescriptionPanelTitle)}\n\n${N(e.description)}\n\n`),e.preview?s+=`${r.view.sectionTitle(r.view.storyDraftPanelTitle)}\n\n${N(e.preview)}\n\n`:!e.description&&!i&&(s+=`${r.view.italicLine(r.view.previewNoDraft.trim())}\n\n`)):"custom_note"===e.type?(s+=Ve(r.view.customNotePanelTitle,r.view.customNotePanelTips),t&&(s+=`\n${r.view.fieldLabel(r.view.customNotePanelCurrent)}\n\n${N(t)}\n\n`)):s+=Ve(r.view.confirmPanelTitle,r.view.confirmPanelTips);let l=qt(n);return new Pt(s.trim(),1,0,l,void 0,{transform:tn}).render(o)}var on=32;function je(e){return I(e-14,6,T.splitPreviewHeight)}function ue(e){return I(e-18,3,T.singlePreviewHeight)}function rn(e,t,i,o){return i.options.some((i,n)=>e.isOptionVisible(t,n)&&(!!i.preview||nn(i.description??"")>30||!!o.optionNotes.get(n)))}var ee=class{constructor(e,t){this.theme=e,this.model=t}theme;model;previewCache=new Map;leftColCache;clear(){this.previewCache.clear(),this.leftColCache=void 0}clearColumnCache(){this.leftColCache=void 0}render(e,t,i){let o=this.model.getQuestion(e.tab);if(!o)return{lines:[]};let n=this.model.getState(e.tab),s=[],l=o.options.filter((t,i)=>this.model.isOptionVisible(e.tab,i)).length;C(s,` ${o.multiSelect?this.theme.fg("warning",r.view.modeMulti(o.minSelect,o.maxSelect,l,o.allowEmpty)):this.theme.fg("accent",r.view.modeSingle)}${o.showIf.length>0?` ${this.theme.fg("muted",r.view.conditionalBadge)}`:""} ${this.theme.bold(o.title)}`,t),o.description&&C(s,this.theme.fg("muted",o.description),t," "),n.customText?.trim()&&C(s,this.theme.fg("success",r.view.attachedNoteBanner(n.customText)),t," ");let a=e.menuItems[e.optionIndex];if("option"===a?.type&&void 0!==a.optionIndex){let e=n.optionNotes.get(a.optionIndex)?.trim();if(e){let i=$(o,a.optionIndex);C(s,this.theme.fg("success",r.view.optionAttachedNoteBanner(i,e)),t," ")}}s.push("");let u,c=rn(this.model,e.tab,o,n);u=t>=T.splitViewMinWidth&&c?this.renderSplitView(s,o,n,e,t,i):this.pushListItems(s,o,n,e,t-2,c,i),Y(s,this.theme,e.statusMessage),s.push("");let d=[r.help.switchQuestion];return this.model.getVisibleQuestionIndices().length>1&&d.push(r.help.jumpQuestion),d.push(r.help.moveCursor),"option"===a?.type?(d.push(r.help.editOptionNote),d.push(r.help.editQuestionNote)):d.push(r.help.editNote),("option"===a?.type&&void 0!==a.optionIndex&&n.optionNotes.has(a.optionIndex)||F(n))&&d.push(r.help.clearNote),d.push(o.multiSelect?r.help.toggleCheckMulti:r.help.selectOptionSingle),o.multiSelect&&(d.push(r.help.toggleAll),d.push(r.help.confirmQuestion)),c&&d.push(r.help.scrollDraft),d.push(r.help.cancel),J(s,d,this.theme,t),q(s,this.theme,t),{lines:s,previewViewport:u}}previewContentLines(e,t,i,o,n){let r=[e,t.type,t.optionIndex??-1,n,i??"",o??""].join(""),s=this.previewCache.get(r);if(s)return s;let l=Be(t,i,o,n,this.theme);if(this.previewCache.size>=on){let e=this.previewCache.keys().next();e.done||this.previewCache.delete(e.value)}return this.previewCache.set(r,l),l}buildPreviewBox(e,t,i,o,n,s,l){let a=this.previewContentLines(e,t,i,o,n),u=a.length,c=Q(l,u,s),d=G(a,c,s).map(e=>L(e,n));if(u>s){let e=r.view.previewScrollInfo(c+1,Math.min(u,c+s),u);d.push(L(` ${this.theme.fg("dim",e)}`,n))}return{lines:d,viewport:{total:u,viewHeight:s}}}renderSplitView(e,t,i,o,n,r){let s,l=I(Math.floor(n*T.leftColRatio),T.leftColMin,T.leftColMax),a=Math.max(20,n-l-T.dividerWidth),u=`${o.tab}_${o.optionIndex}_${o.listScrollOffset}_${this.model.revision}_${l}`;this.leftColCache&&this.leftColCache.key===u?s=this.leftColCache.lines:(s=[],this.pushListItems(s,t,i,o,l,!1,r),this.leftColCache={key:u,lines:s});let c=o.menuItems[o.optionIndex],d="option"===c?.type&&void 0!==c.optionIndex?i.optionNotes.get(c.optionIndex):void 0,m=void 0===c?{lines:[],viewport:{total:0,viewHeight:je(r)}}:this.buildPreviewBox(o.tab,c,i.customText,d,a,je(r),o.previewScrollOffset),h=Math.max(s.length,m.lines.length);for(let t=0;t<h;t++){let i=s[t]??"",o=m.lines[t]??"",n=this.theme.fg("dim",T.dividerChar);e.push(`${j(i,l)}${n}${L(o,a)}`)}return m.viewport}pushListItems(e,t,i,o,n,s,l){o.listScrollOffset>0&&e.push(this.theme.fg("dim",r.view.listTopMore(o.listScrollOffset)));let a,u=o.menuItems.slice(o.listScrollOffset,o.listScrollOffset+T.visibleOptionCount);for(let[r,c]of u.entries()){if(!c)continue;let u=o.listScrollOffset+r,d=u===o.optionIndex,m=o.menuItems[u-1];if(m&&"option"===m.type&&"option"!==c.type&&e.push(""),e.push(...Ee(this.theme,c,d,t,i,n)),d&&s&&("option"!==c.type||c.description||c.preview||i.optionNotes.has(c.optionIndex??-1))){e.push("");let t="option"===c.type&&void 0!==c.optionIndex?i.optionNotes.get(c.optionIndex):void 0,r=this.buildPreviewBox(o.tab,c,i.customText,t,Math.max(10,n-2),ue(l),o.previewScrollOffset);a=r.viewport;for(let t of r.lines)e.push(t);e.push("")}}let c=o.menuItems.length-(o.listScrollOffset+T.visibleOptionCount);return c>0&&e.push(this.theme.fg("dim",r.view.listBottomMore(c))),a}};function sn(e){return[r.help.switchQuestion,...e.getVisibleQuestionIndices().length>1?[r.help.jumpQuestion]:[],r.help.scrollSummary,r.help.confirmSubmit,r.help.cancel]}function ce(e){return I(e-10,4,T.summaryPageSize)}var te=class{constructor(e,t){this.theme=e,this.model=t}theme;model;cache;clear(){this.cache=void 0}get contentLineCount(){return this.cache?.lines.length??0}render(e,t,i,o){let n=[this.theme.fg("accent",this.theme.bold(r.summary.title)),""],s=o-2;(!this.cache||this.cache.width!==s||this.cache.revision!==this.model.revision)&&(this.cache={width:s,revision:this.model.revision,lines:ln(this.model,this.theme,s)});let l=this.cache.lines,a=l.length,u=Q(e,a,t);u>0&&n.push(this.theme.fg("dim",r.summary.topMore(u)));for(let e of G(l,u,t))n.push(e);let c=a-(u+t);return c>0&&n.push(this.theme.fg("dim",r.summary.bottomMore(c))),n.push(""),C(n,this.model.areAllQuestionsAnswered()?this.theme.fg("success",this.theme.bold(r.summary.allDonePrompt)):this.theme.fg("warning",r.summary.pendingWarning),s),Y(n,this.theme,i),n.push(""),J(n,sn(this.model),this.theme,o),q(n,this.theme,o),n}};function ln(e,t,i){let o=[];for(let[n,s]of e.getVisibleQuestionIndices().entries()){let l=e.getQuestion(s);if(!l)continue;let a=e.isQuestionAnswered(s),u=e.getState(s);C(o,`${a?t.fg("success",r.summary.statusDone):t.fg("warning",r.summary.statusPending)} ${t.bold(r.summary.questionPrefix(n+1,l.title))}`,i," ");let c=[];if(l.multiSelect)for(let t of e.getSelectedIndices(s)){let e=l.options[t];if(!e)continue;let i=u.optionNotes.get(t);c.push(i?`${e.label} ${r.summary.optionNoteBadge}`:e.label)}else{let t=e.getSelectedIndex(s),i=void 0===t?void 0:l.options[t];if(i&&void 0!==t){let e=u.optionNotes.get(t);c.push(e?`${i.label} ${r.summary.optionNoteBadge}`:i.label)}}let d=c.length?t.fg("accent",c.join(r.common.optionSeparator)):t.fg("dim",r.fallbacks.unselectedOption);C(o,`${t.fg("muted",r.summary.selectedLabel)} ${d}`,i," ");for(let[n,a]of u.optionNotes.entries()){let u=l.options[n];u&&a?.trim()&&e.isOptionVisible(s,n)&&C(o,`${t.fg("muted",r.summary.optionNotePrefix(u.label))} ${t.fg("accent",a)}`,i," ")}u.customText&&C(o,`${t.fg("muted",r.summary.customNoteLabel)} ${t.fg("accent",u.customText)}`,i," "),o.push("")}return o}var ne=class{_focused=!1;get focused(){return this._focused}set focused(e){this._focused!==e&&(this._focused=e,this.editor.focused=this.inputMode&&e,this.touch(),this.tabCache=void 0,this.questionView.clearColumnCache())}tui;theme;model;done;currentTab=0;cursorByTab=new Map;currentOptionIndex=0;listScrollOffset=0;previewScrollOffset=0;summaryScrollOffset=0;inputMode=!1;editorEscArmed=!1;statusMessage=null;statusTimer=null;isFinished=!1;disposed=!1;abortBinding;cachedWidth;cachedLayoutWidth;cachedHeight;cachedLines;tabCache;menuCache;previewViewportObservation;editTarget;editor;questionView;summaryView;constructor(e,t,i,o){this.tui=e,this.theme=t,this.model=i,this.done=o,this.questionView=new ee(t,i),this.summaryView=new te(t,i);let n={borderColor:e=>this.theme.fg("accent",e),selectList:an()};this.editor=new un(this.tui,n),this.editor.focused=!1,this.editor.onSubmit=e=>{let t=this.editTarget;if(t){if("option"===t.type){let i=this.model.getQuestion(this.currentTab),o=t.optionIndex,n=i?$(i,o):r.fallbacks.autoOptionLabel(o+1),s=this.model.setOptionNote(this.currentTab,o,e);this.setStatus("cleared"===s?r.status.optionNoteCleared(n):"savedAtLimit"===s&&i?r.status.optionNoteSavedAtLimit(i.maxSelect):"savedUnselected"===s?r.status.optionNoteSavedUnselected(n):r.status.optionNoteSaved(n))}else{let t=this.model.setQuestionNote(this.currentTab,e);this.setStatus("saved"===t?r.status.questionNoteSaved:r.status.noteCleared)}this.touchDerived(),this.closeEditor()}else this.closeEditor()}}bindAbortSignal(e){if(!e||this.abortBinding||this.disposed)return;if(e.aborted)return void queueMicrotask(()=>this.finish(!0));let t=()=>this.finish(!0);e.addEventListener("abort",t,{once:!0}),this.abortBinding={signal:e,onAbort:t}}dispose(){this.disposed||(this.disposed=!0,this.clearStatusTimer(),this.abortBinding&&(this.abortBinding.signal.removeEventListener("abort",this.abortBinding.onAbort),this.abortBinding=void 0),this.clearDerivedCaches(),this.previewViewportObservation=void 0,this.clearFrameCaches())}clearFrameCaches(){this.cachedWidth=void 0,this.cachedLayoutWidth=void 0,this.cachedHeight=void 0,this.cachedLines=void 0}clearDerivedCaches(){this.questionView.clear(),this.summaryView.clear(),this.tabCache=void 0,this.menuCache=void 0}touch(){this.clearFrameCaches(),this.tui.requestRender()}touchDerived(){this.clearDerivedCaches(),this.touch()}invalidate(){this.touchDerived(),this.editor.invalidate()}clearStatusTimer(){this.statusTimer&&(clearTimeout(this.statusTimer),this.statusTimer=null)}setStatus(e){this.statusMessage=e,this.clearStatusTimer(),this.statusTimer=setTimeout(()=>{this.statusMessage=null,this.statusTimer=null,this.touch()},T.statusDurationMs),this.touch()}finish(e){this.isFinished||(this.isFinished=!0,this.dispose(),this.done({formTitle:this.model.formTitle,formDescription:this.model.formDescription,questions:this.model.questions,answers:e?[]:this.model.compileAnswers(),cancelled:e}))}get tabOrder(){return[...this.model.getVisibleQuestionIndices(),this.model.questionCount]}get isSubmitTab(){return this.currentTab===this.model.questionCount}get terminalRows(){let e=this.tui.terminal?.rows;return"number"==typeof e&&e>0?e:24}get summaryViewportHeight(){return ce(this.terminalRows)}getMenuItems(){let e=this.menuCache;if(e&&e.tab===this.currentTab&&e.revision===this.model.revision)return e.items;let t=this.model.getMenuItems(this.currentTab);return this.menuCache={tab:this.currentTab,revision:this.model.revision,items:t},t}currentMenuItem(){return this.getMenuItems()[this.currentOptionIndex]}switchTab(e){e!==this.currentTab&&(this.currentTab=e,this.previewScrollOffset=0,this.summaryScrollOffset=0,this.listScrollOffset=0,this.menuCache=void 0,this.isSubmitTab?this.currentOptionIndex=0:(this.currentOptionIndex=this.cursorByTab.get(this.currentTab)??this.model.getSelectedIndex(this.currentTab)??0,this.adjustScrollForCurrentOption()),this.touch())}switchRelativeTab(e){let t=this.tabOrder,i=t.indexOf(this.currentTab);this.switchTab(-1!==i?t[(i+e+t.length)%t.length]??this.currentTab:t[0]??this.model.questionCount)}adjustScrollForCurrentOption(){let e=this.getMenuItems().length;0!==e&&(this.currentOptionIndex=I(this.currentOptionIndex,0,e-1),this.currentOptionIndex<this.listScrollOffset?this.listScrollOffset=this.currentOptionIndex:this.currentOptionIndex>=this.listScrollOffset+T.visibleOptionCount&&(this.listScrollOffset=this.currentOptionIndex-T.visibleOptionCount+1))}moveCursor(e){let t=this.getMenuItems().length;if(0===t)return;let i=I("number"==typeof e?e:this.currentOptionIndex+e.delta,0,t-1);i!==this.currentOptionIndex&&(this.currentOptionIndex=i,this.cursorByTab.set(this.currentTab,i),this.previewScrollOffset=0,this.adjustScrollForCurrentOption(),this.touch())}getEditTargetForCurrentSelection(){let e=this.currentMenuItem();return"option"===e?.type&&void 0!==e.optionIndex?{type:"option",optionIndex:e.optionIndex}:{type:"question"}}openCustomEditor(e){let t=this.model.getQuestion(this.currentTab);if(!t||!t.allowCustom)return;let i=this.model.getState(this.currentTab),o=e??this.getEditTargetForCurrentSelection();this.editTarget=o,this.inputMode=!0,this.editorEscArmed=!1;let n="option"===o.type?i.optionNotes.get(o.optionIndex)??"":i.customText??"";this.editor.setText(n),this.editor.focused=this._focused,this.touch()}closeEditor(){this.inputMode=!1,this.editorEscArmed=!1,this.editTarget=void 0,this.editor.focused=!1,this.editor.setText(""),this.touch()}confirmAndAdvance(e,t){if("option"===e.type&&void 0!==e.optionIndex&&this.model.commitOption(this.currentTab,e.optionIndex),this.model.isQuestionAnswered(this.currentTab)){let e=this.tabOrder,t=e.indexOf(this.currentTab);return void this.switchTab(-1===t?this.model.questionCount:e[t+1]??this.model.questionCount)}this.setStatus(t.multiSelect?r.status.minSelectRequired(t.minSelect):r.status.pleaseAnswerBeforeSubmit)}handleInput(e){if(this.isFinished||this.disposed)return;let t=b(e,y.escape)||b(e,y.ctrl("c"));if(this.inputMode)return t?""===this.editor.getText()||this.editorEscArmed?void this.closeEditor():(this.editorEscArmed=!0,void this.setStatus(r.status.editorDiscardConfirm)):(this.editorEscArmed&&(this.editorEscArmed=!1,this.statusMessage=null),this.editor.handleInput(e),void this.touch());if(t)this.finish(!0);else{if(e=se(e),/^[1-9]$/.test(e)){let t=parseInt(e,10)-1,i=this.tabOrder[t];if(void 0!==i&&i<this.model.questionCount)return void this.switchTab(i)}b(e,y.tab)||b(e,y.right)||b(e,"l")?this.switchRelativeTab(1):b(e,y.shift("tab"))||b(e,y.left)||b(e,"h")?this.switchRelativeTab(-1):this.isSubmitTab?this.handleSummaryInput(e):this.handleQuestionInput(e)}}handleQuestionInput(e){let t=this.model.getQuestion(this.currentTab);if(!t||this.handleNoteShortcut(t,e)||this.handlePreviewScroll(e)||this.handleCursorNavigation(e)||this.handleSelectAllShortcut(t,e))return;let i=this.currentMenuItem();if(i){if(b(e,y.ctrl("s")))return void this.confirmAndAdvance(i,t);if(b(e,y.space))return void this.activateMenuItem(i,t);b(e,y.enter)&&("custom_note"===i.type?this.openCustomEditor({type:"question"}):this.confirmAndAdvance(i,t))}}handleNoteShortcut(e,t){if(!e.allowCustom)return!1;if(b(t,y.shift("n")))return this.openCustomEditor({type:"question"}),!0;if(b(t,"n")||b(t,"e"))return this.openCustomEditor(),!0;if(b(t,"x")||b(t,y.delete)){let t=this.currentMenuItem();if("option"===t?.type&&void 0!==t.optionIndex){let i=t.optionIndex;if(this.model.clearOptionNote(this.currentTab,i))return this.setStatus(r.status.optionNoteCleared($(e,i))),!0}if(this.model.clearQuestionNote(this.currentTab))return this.setStatus(r.status.noteCleared),!0}return!1}handlePreviewScroll(e){let t=0;if(b(e,y.leftbracket)||b(e,y.alt("up"))?t=-T.previewScrollStep:(b(e,y.rightbracket)||b(e,y.alt("down")))&&(t=T.previewScrollStep),0===t)return!1;let i=this.previewViewportObservation,o=i?.viewHeight??ue(this.terminalRows);return this.previewScrollOffset=Q(this.previewScrollOffset+t,i?.total??0,o),this.touch(),!0}handleCursorNavigation(e){return b(e,y.up)||b(e,"k")?(this.moveCursor({delta:-1}),!0):b(e,y.down)||b(e,"j")?(this.moveCursor({delta:1}),!0):b(e,y.home)?(this.moveCursor(0),!0):!!b(e,y.end)&&(this.moveCursor(Number.MAX_SAFE_INTEGER),!0)}handleSelectAllShortcut(e,t){if(!e.multiSelect||!b(t,"a"))return!1;let i=this.model.selectAllOrClear(this.currentTab),o=e.options.filter((e,t)=>this.model.isOptionVisible(this.currentTab,t)).length;return"filled"===i&&e.maxSelect<o?this.setStatus(r.status.selectedUpToLimit(e.maxSelect)):this.touch(),!0}activateMenuItem(e,t){"option"!==e.type||void 0===e.optionIndex?"custom_note"!==e.type?this.confirmAndAdvance(e,t):this.openCustomEditor({type:"question"}):"limit"===this.model.toggleOption(this.currentTab,e.optionIndex)?this.setStatus(r.status.maxSelectExceeded(t.maxSelect)):this.touch()}handleSummaryInput(e){if(b(e,y.enter)||b(e,y.ctrl("s"))){if(this.model.areAllQuestionsAnswered())this.finish(!1);else{let e=this.model.getVisibleQuestionIndices().find(e=>!this.model.isQuestionAnswered(e));if(void 0!==e){this.switchTab(e);let t=this.model.getQuestion(e);t&&this.setStatus(t.multiSelect?r.status.minSelectRequired(t.minSelect):r.status.pleaseAnswerBeforeSubmit)}}return}if(b(e,y.home))return this.summaryScrollOffset=0,void this.touch();if(b(e,y.end))return this.summaryScrollOffset=Number.MAX_SAFE_INTEGER,void this.touch();let t=this.summaryScrollStep(e);if(0===t&&b(e,y.space)&&(t=T.summaryScrollStep),0===t)return;let i=this.summaryView.contentLineCount,o=this.summaryViewportHeight,n=Q(this.summaryScrollOffset,i,o);this.summaryScrollOffset=Q(n+t,i,o),this.touch()}summaryScrollStep(e){return b(e,y.leftbracket)||b(e,y.alt("up"))?-T.summaryScrollStep:b(e,y.rightbracket)||b(e,y.alt("down"))?T.summaryScrollStep:b(e,y.up)||b(e,"k")?-1:b(e,y.down)||b(e,"j")?1:0}render(e){let t=Math.max(20,e),i=this.terminalRows;if(this.cachedLines&&this.cachedWidth===e&&this.cachedLayoutWidth===t&&this.cachedHeight===i)return this.cachedLines;let o=[];q(o,this.theme,t);let n=`${this.currentTab}_${this.model.revision}_${t}`;if((!this.tabCache||this.tabCache.key!==n)&&(this.tabCache={key:n,lines:Me(this.theme,this.model,this.currentTab,t)}),o.push(...this.tabCache.lines),this.isSubmitTab)o.push(...this.summaryView.render(this.summaryScrollOffset,ce(i),this.statusMessage,t));else if(this.inputMode)o.push(...Qe(this.theme,this.model,this.currentTab,this.editTarget,this.editor,t));else{let e=this.questionView.render({tab:this.currentTab,optionIndex:this.currentOptionIndex,listScrollOffset:this.listScrollOffset,previewScrollOffset:this.previewScrollOffset,statusMessage:this.statusMessage,menuItems:this.getMenuItems()},t,i);o.push(...e.lines),e.previewViewport&&(this.previewViewportObservation=e.previewViewport)}return this.cachedWidth=e,this.cachedLayoutWidth=t,this.cachedHeight=i,this.cachedLines=o.map(t=>L(t,e)),this.cachedLines}};import{Type as h}from"typebox";var de=h.Object({questionId:h.String({description:r.schema.conditionQuestionId}),option:h.Optional(h.String({description:r.schema.conditionOption})),answered:h.Optional(h.Boolean({description:r.schema.conditionAnswered}))});function ze(e){return h.Optional(h.Union([de,h.Array(de)],{description:e}))}var pe=h.Object({label:h.String({description:r.schema.optionLabel}),description:h.Optional(h.String({description:r.schema.optionDesc})),preview:h.Optional(h.String({description:r.schema.optionPreview})),customPlaceholder:h.Optional(h.String({description:r.schema.optionCustomPlaceholder})),showIf:ze(r.schema.optionShowIf)}),Ue=h.Object({id:h.Optional(h.String({description:r.schema.questionId})),title:h.String({description:r.schema.questionTitle}),tabLabel:h.Optional(h.String({description:r.schema.questionTabLabel})),description:h.Optional(h.String({description:r.schema.questionDesc})),multiSelect:h.Optional(h.Boolean({description:r.schema.questionMultiSelect})),minSelect:h.Optional(h.Integer({description:r.schema.questionMinSelect,minimum:0})),maxSelect:h.Optional(h.Integer({description:r.schema.questionMaxSelect,minimum:1})),allowEmpty:h.Optional(h.Boolean({description:r.schema.questionAllowEmpty})),options:h.Array(pe,{description:r.schema.questionOptions,minItems:1,maxItems:M}),allowCustom:h.Optional(h.Boolean({description:r.schema.questionAllowCustom})),customPlaceholder:h.Optional(h.String({description:r.schema.questionCustomPlaceholder})),showIf:ze(r.schema.questionShowIf)}),me=h.Object({formTitle:h.String({description:r.schema.formTitle}),description:h.Optional(h.String({description:r.schema.formDesc})),questions:h.Optional(h.Array(Ue,{description:r.schema.formQuestions,minItems:1,maxItems:R})),question:h.Optional(h.String({description:r.schema.formSingleQuestion})),multiSelect:h.Optional(h.Boolean({description:`${r.schema.flatPrefix}${r.schema.questionMultiSelect}`})),minSelect:h.Optional(h.Integer({description:`${r.schema.flatPrefix}${r.schema.questionMinSelect}`,minimum:0})),maxSelect:h.Optional(h.Integer({description:`${r.schema.flatPrefix}${r.schema.questionMaxSelect}`,minimum:1})),allowEmpty:h.Optional(h.Boolean({description:`${r.schema.flatPrefix}${r.schema.questionAllowEmpty}`})),options:h.Optional(h.Array(pe,{description:r.schema.flatQuestionOptions,minItems:1,maxItems:M})),allowCustom:h.Optional(h.Boolean({description:`${r.schema.flatPrefix}${r.schema.questionAllowCustom}`})),customPlaceholder:h.Optional(h.String({description:`${r.schema.flatPrefix}${r.schema.questionCustomPlaceholder}`}))});function U(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cn(e){let t=D(e.raw);return U(t)?t:(delete e.raw,e)}function A(e,t){for(let i of t){let t=e[i];if("string"==typeof t)return t}}function _(e,t){if("boolean"==typeof e)return e;if(1===e)return!0;if(0===e)return!1;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}return t}function We(e){if("number"==typeof e&&Number.isFinite(e))return Math.floor(e);if("string"==typeof e){let t=parseInt(e.trim(),10);return Number.isFinite(t)?t:void 0}}function Xe(e){let t=We(e);return void 0===t?void 0:Math.max(0,t)}function He(e){let t=We(e);return void 0!==t&&t>=1?t:void 0}function dn(e){if(!U(e))return;let t=w(A(e,["questionId","question"]));if(!t)return;let i={questionId:t},o=w(A(e,["option","optionLabel","label"]));return o&&(i.option=o),void 0!==e.answered&&(i.answered=_(e.answered,!0)),i}function Ge(e){let t=D(e),i=(Array.isArray(t)?t:[t]).map(dn).filter(e=>void 0!==e);return Array.isArray(t)?i.length>0?i:void 0:i[0]}function Ke(e){let t=D(e);return Array.isArray(t)?t.slice(0,M).map((e,t)=>{if("string"==typeof e)return{label:e.trim()||r.fallbacks.autoOptionLabel(t+1)};if(!U(e))return{label:r.fallbacks.autoOptionLabel(t+1)};let i=e;return{label:w(A(i,["label","name","title","text","value","choice"]))??r.fallbacks.autoOptionLabel(t+1),description:w(A(i,["description","desc","reason","rationale","deduction"])),preview:w(A(i,["preview","draft","scene","content"])),customPlaceholder:w(A(i,["customPlaceholder","placeholder"])),showIf:Ge(i.showIf??i.when??i.visibleIf)}}):[]}function pn(e){return"object"==typeof e&&null!==e&&!("questions"in e)&&("options"in e||"choices"in e||"items"in e||"question"in e||"prompt"in e)}function mn(e,t){if("string"==typeof e)return{title:e,options:oe([])};if(!U(e))return{title:r.fallbacks.autoQuestionTitle(t+1),options:oe([])};let i=e;return{id:A(i,["id"]),title:w(A(i,["title","question","prompt","query","heading"]))??r.fallbacks.autoQuestionTitle(t+1),tabLabel:w(A(i,["tabLabel","tabTitle","tab"])),description:w(A(i,["description","desc","rationale"])),multiSelect:_(i.multiSelect,!1),minSelect:Xe(i.minSelect),maxSelect:He(i.maxSelect),allowEmpty:_(i.allowEmpty,!1),options:oe(Ke(i.options??i.choices??i.items)),allowCustom:_(i.allowCustom,!0),customPlaceholder:A(i,["customPlaceholder","placeholder"]),showIf:Ge(i.showIf??i.when??i.visibleIf)}}function fn(e){if(void 0===e)return;let t=D(e),i=Array.isArray(t)?t:pn(t)?[t]:[];return 0!==i.length?i.slice(0,R).map((e,t)=>mn(e,t)):void 0}function oe(e){return e.length>0?e:[{label:r.fallbacks.defaultOptionLabel}]}function hn(e,t,i,o){return"string"==typeof e?e:"string"==typeof t?t:o?i:void 0}function W(e){let t=e&&"object"==typeof e?e:D(e);if(!U(t))return{formTitle:r.fallbacks.defaultFormTitle};let i=cn({...t}),o=w(A(i,["title","taskTitle"])),n=w(A(i,["formTitle"]))??o??r.fallbacks.defaultFormTitle,s=fn(i.questions??i.form??i.survey),l=void 0!==i.options||void 0!==i.choices||void 0!==i.items,a=l?oe(Ke(i.options??i.choices??i.items)):void 0,u=hn(i.question,i.prompt,o,l);return{formTitle:n,description:A(i,["description"]),questions:s,question:u,multiSelect:void 0===i.multiSelect?void 0:_(i.multiSelect,!1),minSelect:void 0===i.minSelect?void 0:Xe(i.minSelect),maxSelect:void 0===i.maxSelect?void 0:He(i.maxSelect),allowEmpty:void 0===i.allowEmpty?void 0:_(i.allowEmpty,!1),options:a,allowCustom:void 0===i.allowCustom?void 0:_(i.allowCustom,!0),customPlaceholder:A(i,["customPlaceholder"])}}import{Text as tt}from"@earendil-works/pi-tui";function bn(e){return e instanceof Error?e.message:String(e)}function Ye(e={}){return{formTitle:e.formTitle??r.fallbacks.defaultFormTitle,formDescription:e.formDescription,questions:e.questions??[]}}function fe(e={}){let{formTitle:t,formDescription:i,questions:o}=Ye(e);return{content:[{type:"text",text:r.markdown.envelopeCancelled}],details:{formTitle:t,formDescription:i,questions:o,answers:[],cancelled:!0}}}function X(e,t,i,o={}){let{formTitle:n,formDescription:s,questions:l}=Ye(o);return{content:[{type:"text",text:r.markdown.envelopeError(e,t)}],details:{formTitle:n,formDescription:s,questions:l,answers:[],cancelled:!1,error:i},isError:!0}}function he(e,t={}){let i=bn(e);return X(r.markdown.errorReasons.runtimeError(i),r.markdown.errorGuidances.runtimeError,r.status.errorExecutionFailed(i),t)}function Je(e,t){return{content:[{type:"text",text:e.formatAnswers(t)}],details:{formTitle:e.formTitle,formDescription:e.formDescription,questions:e.questions,answers:t,cancelled:!1}}}function Ze(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`ask_author 结果详情应为普通对象,实际收到 ${JSON.stringify(e)}`);if(!("cancelled"in e&&"answers"in e&&"questions"in e&&"formTitle"in e))throw new Error("ask_author 结果详情缺少 cancelled/answers/questions/formTitle 字段");if("boolean"!=typeof e.cancelled)throw new Error("ask_author 结果详情的 cancelled 字段应为布尔值");if(!Array.isArray(e.answers)||!Array.isArray(e.questions))throw new Error("ask_author 结果详情的 answers/questions 字段应为数组");if("string"!=typeof e.formTitle)throw new Error("ask_author 结果详情的 formTitle 字段应为字符串");return e}function et(e){let t=e.customText?r.card.questionNoteTag(e.customText):"",i=(e,t)=>t?r.card.optionWithNote(e,t):e;return e.multiSelect?((e.selectedOptions??[]).map(e=>i(e.label,e.customText)).join(r.common.optionSeparator)||r.fallbacks.unselectedOption)+t:e.selectedOption?i(e.selectedOption.label,e.selectedOption.customText)+t:e.customText||r.fallbacks.unselectedOption}function gn(e,t){if(t.cachedArgs===e&&t.cachedCard)return t.cachedCard;let i=W(e),o=i.questions??[],n=i.options??[],s=o.length>0?o.length:n.length>0?1:0,l=o.length>0?o.reduce((e,t)=>e+t.options.length,0):n.length,a={title:i.formTitle,countLabel:s>1?r.card.callQuestionAndOptionCount(s,l):r.card.callOptionCountOnly(l)};return t.cachedArgs=e,t.cachedCard=a,a}function B(e,t){let i=t instanceof tt?t:new tt("",0,0);return i.setText(e),i}function nt(e,t,i){let o=gn(e,i.state);return B(`${t.fg("accent",r.tool.label)} ${t.bold(o.title)} ${t.fg("muted",`(${o.countLabel})`)}`,i.lastComponent)}function ot(e,t,i,o){let n=Ze(e.details),{expanded:s}=t;if(n.error){let e=`${i.fg("error",i.bold(r.card.resultErrorShort))} ${i.fg("muted",`${r.common.bulletPrefix}${n.error}`)}`;return B(s?`${e}\n${r.card.errorBullet(i.fg("error",n.error))}`:e,o.lastComponent)}if(n.cancelled)return B(i.fg("warning",r.card.resultCancelled),o.lastComponent);let l=`${i.fg("success",i.bold(r.card.resultCompleted))} ${i.fg("muted",`${r.common.bulletPrefix}${r.card.resultCount(n.answers.length)}`)}`;return B(s?[l,...n.answers.map(e=>r.card.optionBullet(i.bold(e.questionTitle),i.fg("accent",et(e))))].join("\n"):l,o.lastComponent)}function wn(e){e.registerTool({name:r.tool.name,label:r.tool.label,description:r.tool.description,promptSnippet:r.tool.promptSnippet,promptGuidelines:[...r.tool.promptGuidelines],parameters:me,executionMode:"sequential",exposure:"model-only",annotations:{readOnlyHint:!0,openWorldHint:!1},prepareArguments:W,async execute(e,t,i,o,n){let s,l,a=w(t?.formTitle)??r.fallbacks.defaultFormTitle;if(i?.aborted)return fe({formTitle:a});if("tui"!==n.mode)return X(r.markdown.errorReasons.nonTui,r.markdown.errorGuidances.nonTui,r.status.errorNonTui,{formTitle:a});try{s=new z(t)}catch(e){return e instanceof P?X(r.markdown.errorReasons.invalidCondition(e.message),r.markdown.errorGuidances.invalidCondition,r.status.errorInvalidCondition(e.message),{formTitle:a}):he(e,{formTitle:a})}if(0===s.questions.length)return X(r.markdown.errorReasons.noQuestions,r.markdown.errorGuidances.noQuestions,r.status.errorNoQuestions,{questions:[],formTitle:s.formTitle,formDescription:s.formDescription});try{let e=await n.ui.custom((e,t,o,n)=>(l=new ne(e,t,s,n),l.bindAbortSignal(i),l));return!e||e.cancelled?fe({questions:e?.questions??s.questions,formTitle:e?.formTitle??s.formTitle,formDescription:e?.formDescription??s.formDescription}):Je(s,e.answers)}catch(e){return he(e,{questions:s.questions,formTitle:s.formTitle,formDescription:s.formDescription})}finally{l?.dispose()}},renderCall:nt,renderResult:ot}),e.registerCommand(r.command.name,{description:r.command.description,handler:async(e,t)=>{t.ui.notify(r.command.notify,"info")}})}export{ve as ACTIVE_LOCALE,P as AdaptiveConditionError,z as AskAuthorFormModel,me as AskAuthorParams,O as ICONS,T as LAYOUT_CONFIG,M as MAX_OPTIONS,R as MAX_QUESTIONS,pe as OptionSchema,Ue as QuestionSchema,de as ShowIfConditionSchema,r as TEXTS,wn as askAuthorExtension,w as cleanOptional,N as cleanText,wn as default,xe as detectLocale,se as normalizeImeKey,j as padToVisibleWidth,L as safeLine,W as sanitizeAskAuthorArgs};
1
+ import{getSelectListTheme as Sn}from"@earendil-works/pi-coding-agent";import{Editor as yn,Key as S,matchesKey as w}from"@earendil-works/pi-tui";import{stripTerminalSequences as gt,truncateToWidth as se,visibleWidth as Ae,wrapTextWithAnsi as xt}from"@earendil-works/pi-tui";var y={dividerChar:" │ ",dividerThick:"═",dividerThin:"─",dividerWidth:3,leftColMax:46,leftColMin:30,leftColRatio:.42,splitViewMinWidth:72,tabLabelMaxWidth:14,previewScrollStep:3,singlePreviewHeight:7,splitPreviewHeight:14,summaryPageSize:16,summaryScrollStep:3,visibleOptionCount:7,statusDurationMs:3e3},E={cancel:"󰜺",check:"󰄬",checked:"󰐾",unchecked:"󰄰",error:"󰅚",note:"󰷬",cursor:"󰁔",scrollUp:"󰁝",scrollDown:"󰁅",checkedMulti:"[󰄬] ",uncheckedMulti:"[ ] ",checkedSingle:"(•) ",uncheckedSingle:"( ) "},M=30,k=20;function O(e,t,i){return Math.max(t,Math.min(e,i))}function $(e,t,i){return O(e,0,Math.max(0,t-i))}function Y(e,t,i){return e.slice(t,t+i)}function q(e){return e?e.replace(/\t/g," ").replace(/\r/g,""):""}function wt(e){return gt(e).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function g(e){let t=e?.trim();return t&&wt(q(t))||void 0}function L(e){if("string"==typeof e){if(e.length>1e6)return;try{return JSON.parse(e)}catch{return}}return e}function St(e,t,i){let n=Ae(e);n>=i&&i>0&&(e=se(e,i-1),n=Ae(e));let o=Math.max(1,i-n),s=" ".repeat(n),r=xt(t,o);return 0===r.length?e?[e]:[]:r.map((t,i)=>0===i?e+t:s+t)}function A(e,t,i,n=""){e.push(...St(n,t,i))}function P(e,t){return t<=0?"":se(q(e),t)}function W(e,t){return t<=0?"":se(q(e),t,"...",!0)}function re(e,t=y.dividerThin){return e>0?t.repeat(e):""}var yt={" ":" ","【":"[","】":"]"};function ae(e){if(1!==e.length)return e;let t=yt[e];if(void 0!==t)return t;let i=e.charCodeAt(0);return i>=65281&&i<=65374?String.fromCharCode(i-65248):e}function Ne(e){return e.replace(/\s+/g," ").trim()}var le={tool:{label:"Consult Author"},command:{name:"ask-author",description:"Show the ask_author consultation tool reference",notify:"Ask the AI to call ask_author in your prompt to consult you on creative decisions"},common:{optionSeparator:", ",bulletPrefix:"• ",helpSeparator:" • "},tabs:{questionTab:{template:"Q{index}",params:["index"]},expansionPlaceholder:"expanding…",submitTab:{template:"{icon.check} Submit"}},view:{modeSingle:"[Single]",conditionalBadge:"[Conditional]",expansionBadge:"[Expand]",expansionPendingHint:"Question switching and answering are paused while the follow-up is generated; new questions and options appear in place when it finishes",modeMultiAtLeast:{template:"[Multi, at least {min}{maxPart}]",params:["min","maxPart"]},modeMultiOptional:{template:"[Multi, optional{maxPart}]",params:["maxPart"]},modeMultiUnconstrained:{template:"[Multi{maxPart}]",params:["maxPart"]},modeMultiMaxPart:{template:", up to {max}",params:["max"]},attachedNoteBanner:{template:"{icon.note} Question note: {text}",params:["text"]},optionAttachedNoteBanner:{template:"{icon.note} [{label}] option note: {text}",params:["label","text"]},listTopMore:{template:" {icon.scrollUp} {count} more above",params:["count"]},listBottomMore:{template:" {icon.scrollDown} {count} more below",params:["count"]},optionNotePanelTitle:"Option Note",storyDescriptionPanelTitle:"Plot Deduction",storyDraftPanelTitle:"Draft / Storyboard Preview",customNotePanelTitle:"Question Note",confirmPanelTitle:"Controls",previewScrollInfo:{template:"(lines {start}-{end}/{total}, use [ ] to scroll)",params:["start","end","total"]},previewNoDraft:"(nothing to preview)",customNotePanelTips:['• Press "N", or select this item and press "Enter", to write or edit the question note','• Press "x" to clear the question note',"• The note is submitted together with the selected options and their option notes"],confirmPanelTips:["• Press `Enter` to confirm this question and move on to the next one","• Confirming the last question opens the summary and submit page"],sectionTitle:{template:"### {title}",params:["title"]},italicLine:{template:"_{text}_",params:["text"]}},menu:{customNoteLabel:{template:"{icon.note} Question note"},customNoteLabelFilled:{template:"{icon.note} Question note (filled)"},confirmDetailMulti:{template:"{selectedCount} selected",params:["selectedCount","minSelect"]},confirmDetailMultiBelowMin:{template:"{selectedCount}/{minSelect} selected",params:["selectedCount","minSelect"]},confirmLabel:{template:"{icon.check} Confirm question ({detail}{noteSuffix})",params:["detail","noteSuffix"]},confirmNoteSuffix:" + note",confirmDesc:"Confirm and continue to the next question or the summary"},editor:{title:{template:" {icon.note} Question note ({questionTitle})",params:["questionTitle"]},optionTitle:{template:" {icon.note} Option note ({optionLabel} - {questionTitle})",params:["questionTitle","optionLabel"]},footerHelp:" [Enter] save and return • [Esc/Ctrl+C] cancel"},status:{questionNoteSaved:"Question note saved",noteCleared:"Question note cleared",optionNoteSaved:{template:"Saved note for {label}",params:["label"]},optionNoteSavedUnselected:{template:"Saved note for {label} (option not selected; submitted as a note only)",params:["label"]},optionNoteSavedAtLimit:{template:"Limit reached (up to {max} options): note saved, option left unselected",params:["max"]},optionNoteCleared:{template:"Cleared note for {label}",params:["label"]},selectedUpToLimit:{template:"Selection limit reached (up to {limit} items)",params:["limit"]},maxSelectExceeded:{template:'Limit reached (up to {max} items): press "Space" to deselect an item first',params:["max"]},minSelectRequired:{template:'Below minimum (at least {min} required): press "Space" to select more, or press "n/N" to write a note',params:["min"]},pleaseAnswerBeforeSubmit:'Question not answered: press "Space/Enter" to pick an option, or press "n/N" to write a note',editorDiscardConfirm:"Press Esc/Ctrl+C again to discard changes (unsaved content will be lost); keep typing to cancel",errorNonTui:"The current environment is not an interactive terminal, so the interface cannot start; retry in an interactive TUI session",errorNoQuestions:"No valid question or option was provided; provide at least one question with options",errorInvalidCondition:{template:"Invalid adaptive condition: {details} (make showIf reference an earlier question and an existing option label, or use answered)",params:["details"]},errorExecutionFailed:{template:"Component failure: {reason} (fix the arguments and retry)",params:["reason"]},expansionRunning:"Expanding follow-up questions from your answers…",expansionAdded:{template:"Expansion finished: {qCount} new questions, {optCount} new options",params:["qCount","optCount"]},expansionRetracted:"Answer changed, the previous expansion was withdrawn",expansionStopped:"The answers already determine the next step; no further questions added",expansionFailed:{template:"Expansion failed: {reason} (answer on or submit as is)",params:["reason"]}},help:{cancel:"Esc/Ctrl+C cancel",clearNote:"x clear note",confirmQuestion:"Enter confirm",confirmSubmit:"Enter submit",editNote:"n question note",editOptionNote:"n option note",editQuestionNote:"N question note",jumpQuestion:"1-9 jump to question",moveCursor:"↑↓/jk move",scrollDraft:"[ ] scroll draft",scrollSummary:"↑↓/[ ] scroll",selectOptionSingle:"Space/Enter select",switchQuestion:"Tab/←→/hl switch question",toggleAll:"a select/clear all",toggleCheckMulti:"Space toggle"},summary:{title:"[Answer Summary]",statusDone:"[Done]",statusPending:"[Pending]",questionPrefix:{template:"Q{index}: {title}",params:["index","title"]},selectedLabel:"Selected:",optionNoteBadge:{template:"({icon.note} note)"},optionNotePrefix:{template:"{icon.note} Option note ({optLabel}):",params:["optLabel"]},customNoteLabel:{template:"{icon.note} Question note:"},allDonePrompt:{template:" {icon.check} All questions answered; press Enter/Ctrl+S to submit, Tab/hl/1-9 to revise"},pendingWarning:{template:" {icon.unchecked} Some questions are unanswered; press Enter to answer, Tab/hl/1-9 to switch"},topMore:{template:" {icon.scrollUp} {count} more lines above",params:["count"]},bottomMore:{template:" {icon.scrollDown} {count} more lines below",params:["count"]}},card:{callQuestionAndOptionCount:{template:"{qCount} questions • {optCount} options",params:["qCount","optCount"]},callOptionCountOnly:{template:"{optCount} options",params:["optCount"]},resultCancelled:{template:"{icon.cancel} Cancelled"},resultErrorShort:{template:"{icon.error} Failed"},resultCompleted:{template:"{icon.check} Completed"},resultCount:{template:"{n} items",params:["n"]},optionBullet:{template:"• {title}: {content}",params:["title","content"]},optionWithNote:{template:"{label} [{icon.note} {note}]",params:["label","note"]},questionNoteTag:{template:" ({icon.note} question note: {text})",params:["text"]},errorBullet:{template:"• Error: {err}",params:["err"]}},fallbacks:{defaultFormTitle:"Creative Decision",defaultQuestionTitle:"Choose the next creative option",defaultCustomPlaceholder:"Enter overall requirements, foreshadowing details, or revision notes for this question...",defaultOptionCustomPlaceholder:"Enter specific requirements or revision details for this option...",defaultCustomChoiceName:"Custom option",defaultOptionLabel:"Default option",unnamedOptionLabel:"Unnamed option",unselectedOption:"Not selected",autoQuestionId:{template:"q_{n}",params:["n"]},autoQuestionTitle:{template:"Question {n}",params:["n"]},autoOptionLabel:{template:"Option {n}",params:["n"]}}},Oe={tool:{label:"作者に確認"},command:{name:"ask-author",description:"ask_author 創作確認ツールの説明を表示",notify:"プロンプトで AI に ask_author の呼び出しを指示すると、創作方針の確認が行われます"},common:{optionSeparator:"、",bulletPrefix:"• ",helpSeparator:" • "},tabs:{questionTab:{template:"第{index}問",params:["index"]},expansionPlaceholder:"展開中…",submitTab:{template:"{icon.check} 回答を提出"}},view:{modeSingle:"[単一選択]",conditionalBadge:"[条件付き]",expansionBadge:"[展開]",expansionPendingHint:"展開中は質問の切り替えと回答を停止します。完了すると新しい質問と選択肢がその場で展開されます",modeMultiAtLeast:{template:"[複数選択 {min}項目以上{maxPart}]",params:["min","maxPart"]},modeMultiOptional:{template:"[複数選択 選択任意{maxPart}]",params:["maxPart"]},modeMultiUnconstrained:{template:"[複数選択{maxPart}]",params:["maxPart"]},modeMultiMaxPart:{template:"、最大{max}項目",params:["max"]},attachedNoteBanner:{template:"{icon.note} 質問の補足説明:{text}",params:["text"]},optionAttachedNoteBanner:{template:"{icon.note} [{label}] 選択肢の補足説明:{text}",params:["label","text"]},listTopMore:{template:" {icon.scrollUp} 上にあと {count} 項目",params:["count"]},listBottomMore:{template:" {icon.scrollDown} 下にあと {count} 項目",params:["count"]},optionNotePanelTitle:"選択肢の補足説明",storyDescriptionPanelTitle:"ストーリー設定の展開",storyDraftPanelTitle:"本文下書き/シーン試筆",customNotePanelTitle:"質問の補足説明",confirmPanelTitle:"操作案内",previewScrollInfo:{template:"({start}-{end}/{total} 行、[ ] でスクロール)",params:["start","end","total"]},previewNoDraft:"(プレビュー内容なし)",customNotePanelTips:["• 「N」キーを押すか、本項目を選択して「Enter」を押すと質問の補足説明を入力・編集できます","• 「x」キーを押すと質問の補足説明を消去できます","• 補足説明は選択された選択肢および選択肢ごとの補足説明と共に AI アシスタントへ送信されます"],confirmPanelTips:["• `Enter` を押してこの質問を確定し、次の質問へ進みます","• 最後の質問を確定すると、自動的に概要確認・提出画面へ遷移します"],sectionTitle:{template:"### {title}",params:["title"]},italicLine:{template:"_{text}_",params:["text"]}},menu:{customNoteLabel:{template:"{icon.note} 質問の補足説明"},customNoteLabelFilled:{template:"{icon.note} 質問の補足説明 (入力済み)"},confirmDetailMulti:{template:"{selectedCount} 項目選択済み",params:["selectedCount","minSelect"]},confirmDetailMultiBelowMin:{template:"{selectedCount}/{minSelect} 項目選択済み",params:["selectedCount","minSelect"]},confirmLabel:{template:"{icon.check} この質問を確定 ({detail}{noteSuffix})",params:["detail","noteSuffix"]},confirmNoteSuffix:" + 補足説明",confirmDesc:"確定して次の質問または概要画面へ進む"},editor:{title:{template:" {icon.note} 質問の補足説明を入力({questionTitle})",params:["questionTitle"]},optionTitle:{template:" {icon.note} 選択肢の補足説明を入力({optionLabel} - {questionTitle})",params:["questionTitle","optionLabel"]},footerHelp:" [Enter] 保存して戻る • [Esc/Ctrl+C] 取り消し"},status:{questionNoteSaved:"質問の補足説明を保存しました",noteCleared:"質問の補足説明を消去しました",optionNoteSaved:{template:"「{label}」の補足説明を保存しました",params:["label"]},optionNoteSavedUnselected:{template:"「{label}」のメモを保存しました(この選択肢は未選択のため、メモとしてのみ送信されます)",params:["label"]},optionNoteSavedAtLimit:{template:"上限(最大 {max} 項目)に達しました:メモは保存されましたが、選択肢は未選択のままです",params:["max"]},optionNoteCleared:{template:"「{label}」の補足説明を消去しました",params:["label"]},selectedUpToLimit:{template:"選択上限に達しました(最大 {limit} 項目)",params:["limit"]},maxSelectExceeded:{template:"上限(最大 {max} 項目)に達しました:「Space」キーで選択を解除してから再選択してください",params:["max"]},minSelectRequired:{template:"下限(少なくとも {min} 項目)を満たしていません:「Space」キーで選択を続けるか、「n/N」で説明を入力してください",params:["min"]},pleaseAnswerBeforeSubmit:"この質問は未回答です:「Space/Enter」で選択肢を選択するか、「n/N」で補足説明を入力してください",editorDiscardConfirm:"もう一度 Esc/Ctrl+C を押すと変更を破棄します(未保存の内容は失われます)。入力を続けると取り消しを中止します",errorNonTui:"対話型ターミナル環境ではないため、インターフェースを起動できません。対話型 TUI セッションで再試行してください",errorNoQuestions:"有効な質問または選択肢が指定されていません。選択肢を含む質問を少なくとも1つ指定してください",errorInvalidCondition:{template:"適応条件が無効です:{details}(showIf はより前の質問と既存の選択肢ラベルを参照するか、answered を使用してください)",params:["details"]},errorExecutionFailed:{template:"コンポーネント実行エラー:{reason}(引数を修正して再試行してください)",params:["reason"]},expansionRunning:"回答に基づき後続の質問を展開中…",expansionAdded:{template:"展開完了:{qCount} 問、{optCount} 個の選択肢を追加しました",params:["qCount","optCount"]},expansionRetracted:"回答が変更されたため、前回の展開結果を取り消しました",expansionStopped:"推論に必要な情報は十分揃っているため、質問の追加を終了しました",expansionFailed:{template:"展開に失敗しました:{reason}(回答を続けるか、そのまま提出できます)",params:["reason"]}},help:{cancel:"Esc/Ctrl+C 取消",clearNote:"x 補足説明を消去",confirmQuestion:"Enter 確定",confirmSubmit:"Enter 提出",editNote:"n 補足説明",editOptionNote:"n 選択肢の補足説明",editQuestionNote:"N 質問の補足説明",jumpQuestion:"1〜9 質問へ移動",moveCursor:"↑↓/jk 移動",scrollDraft:"[ ] 下書きをスクロール",scrollSummary:"↑↓/[ ] スクロール",selectOptionSingle:"Space/Enter 選択",switchQuestion:"Tab/←→/hl 質問切り替え",toggleAll:"a 全選択/クリア",toggleCheckMulti:"Space 選択/解除"},summary:{title:"【回答概要と確認】",statusDone:"[完了]",statusPending:"[未完了]",questionPrefix:{template:"第{index}問:{title}",params:["index","title"]},selectedLabel:"選択済み:",optionNoteBadge:{template:"({icon.note} メモ)"},optionNotePrefix:{template:"{icon.note} 選択肢の補足説明({optLabel}):",params:["optLabel"]},customNoteLabel:{template:"{icon.note} 質問の補足説明:"},allDonePrompt:{template:" {icon.check} すべて完了しました。Enter/Ctrl+S で提出、Tab/hl/1〜9 で戻って修正"},pendingWarning:{template:" {icon.unchecked} 未完了の質問があります。Enter で回答、Tab/hl/1〜9 で切り替えて修正"},topMore:{template:" {icon.scrollUp} 上にあと {count} 行",params:["count"]},bottomMore:{template:" {icon.scrollDown} 下にあと {count} 行",params:["count"]}},card:{callQuestionAndOptionCount:{template:"{qCount} 問 • {optCount} 選択肢",params:["qCount","optCount"]},callOptionCountOnly:{template:"{optCount} 選択肢",params:["optCount"]},resultCancelled:{template:"{icon.cancel} 取り消しました"},resultErrorShort:{template:"{icon.error} 実行失敗"},resultCompleted:{template:"{icon.check} 完了"},resultCount:{template:"{n} 項目",params:["n"]},optionBullet:{template:"• {title}:{content}",params:["title","content"]},optionWithNote:{template:"{label} [{icon.note} {note}]",params:["label","note"]},questionNoteTag:{template:" ({icon.note} 質問の補足説明: {text})",params:["text"]},errorBullet:{template:"• エラー原因:{err}",params:["err"]}},fallbacks:{defaultFormTitle:"創作の決定",defaultQuestionTitle:"今後の創作方針を選択してください",defaultCustomPlaceholder:"この質問に対する全体的な要望、伏線などの詳細、または修正意見を入力...",defaultOptionCustomPlaceholder:"この選択肢に対する具体的な追加要望や修正の詳細を入力...",defaultCustomChoiceName:"カスタム案",defaultOptionLabel:"デフォルト案",unnamedOptionLabel:"名称未設定の案",unselectedOption:"未選択",autoQuestionId:{template:"q_{n}",params:["n"]},autoQuestionTitle:{template:"質問 {n}",params:["n"]},autoOptionLabel:{template:"選択肢 {n}",params:["n"]}}},ke={tool:{label:"작가에게 문의"},command:{name:"ask-author",description:"ask_author 창작 문의 도구 설명 보기",notify:"프롬프트에서 AI에게 ask_author 호출을 지시하면 창작 결정에 대해 문의합니다"},common:{optionSeparator:", ",bulletPrefix:"• ",helpSeparator:" • "},tabs:{questionTab:{template:"질문 {index}",params:["index"]},expansionPlaceholder:"전개 중…",submitTab:{template:"{icon.check} 답변 제출"}},view:{modeSingle:"[단일 선택]",conditionalBadge:"[조건부]",expansionBadge:"[전개]",expansionPendingHint:"전개 중에는 질문 전환과 답변이 일시 중지되며, 완료되면 새 질문과 선택지가 원래 자리에 나타납니다",modeMultiAtLeast:{template:"[다중 선택 최소 {min}개{maxPart}]",params:["min","maxPart"]},modeMultiOptional:{template:"[다중 선택 선택 안 함 가능{maxPart}]",params:["maxPart"]},modeMultiUnconstrained:{template:"[다중 선택{maxPart}]",params:["maxPart"]},modeMultiMaxPart:{template:" 최대 {max}개",params:["max"]},attachedNoteBanner:{template:"{icon.note} 질문 추가 설명: {text}",params:["text"]},optionAttachedNoteBanner:{template:"{icon.note} [{label}] 선택지 추가 설명: {text}",params:["label","text"]},listTopMore:{template:" {icon.scrollUp} 위에 {count}개 더 있음",params:["count"]},listBottomMore:{template:" {icon.scrollDown} 아래에 {count}개 더 있음",params:["count"]},optionNotePanelTitle:"선택지 추가 설명",storyDescriptionPanelTitle:"플롯 설정 전개",storyDraftPanelTitle:"본문 초안 / 콘티 시안",customNotePanelTitle:"질문 추가 설명",confirmPanelTitle:"조작 안내",previewScrollInfo:{template:"({start}-{end}/{total}행, [ ]로 스크롤)",params:["start","end","total"]},previewNoDraft:"(미리보기 내용 없음)",customNotePanelTips:["• 언제든지 'N'을 누르거나 이 항목을 선택 후 'Enter'를 눌러 질문 추가 설명을 입력/수정합니다","• 'x'를 눌러 질문 추가 설명을 지웁니다","• 추가 설명은 선택된 선택지 및 선택지별 추가 설명과 함께 AI 어시스턴트에게 제출됩니다"],confirmPanelTips:["• `Enter`를 눌러 이 질문을 확정하고 다음 질문으로 이동합니다","• 마지막 질문을 확정하면 개요 및 제출 화면으로 자동 이동합니다"],sectionTitle:{template:"### {title}",params:["title"]},italicLine:{template:"_{text}_",params:["text"]}},menu:{customNoteLabel:{template:"{icon.note} 질문 추가 설명"},customNoteLabelFilled:{template:"{icon.note} 질문 추가 설명 (작성됨)"},confirmDetailMulti:{template:"{selectedCount}개 선택됨",params:["selectedCount","minSelect"]},confirmDetailMultiBelowMin:{template:"{selectedCount}/{minSelect}개 선택됨",params:["selectedCount","minSelect"]},confirmLabel:{template:"{icon.check} 이 질문 확정 ({detail}{noteSuffix})",params:["detail","noteSuffix"]},confirmNoteSuffix:" + 추가 설명",confirmDesc:"확정 후 다음 질문 또는 개요 화면으로 이동"},editor:{title:{template:" {icon.note} 질문 추가 설명 작성({questionTitle})",params:["questionTitle"]},optionTitle:{template:" {icon.note} 선택지 추가 설명 작성({optionLabel} - {questionTitle})",params:["questionTitle","optionLabel"]},footerHelp:" [Enter] 저장 후 돌아가기 • [Esc/Ctrl+C] 취소"},status:{questionNoteSaved:"질문 추가 설명을 저장했습니다",noteCleared:"질문 추가 설명을 지웠습니다",optionNoteSaved:{template:"'{label}' 추가 설명을 저장했습니다",params:["label"]},optionNoteSavedUnselected:{template:"'{label}' 메모를 저장했습니다 (해당 선택지는 선택되지 않았으며 메모로만 제출됩니다)",params:["label"]},optionNoteSavedAtLimit:{template:"최대 한도(최대 {max}개)에 도달했습니다: 메모는 저장되었으나 선택지는 선택되지 않았습니다",params:["max"]},optionNoteCleared:{template:"'{label}' 추가 설명을 지웠습니다",params:["label"]},selectedUpToLimit:{template:"선택 한도에 도달했습니다 (최대 {limit}개)",params:["limit"]},maxSelectExceeded:{template:"최대 한도(최대 {max}개)에 도달했습니다: '스페이스바'로 선택을 해제한 후 다시 선택해 주세요",params:["max"]},minSelectRequired:{template:"최소 조건(최소 {min}개)을 충족하지 않았습니다: '스페이스바'로 계속 선택하거나 'n/N'으로 설명을 입력해 주세요",params:["min"]},pleaseAnswerBeforeSubmit:"이 질문에 답변하지 않았습니다: '스페이스바/Enter'로 선택지를 선택하거나 'n/N'으로 추가 설명을 입력해 주세요",editorDiscardConfirm:"다시 Esc/Ctrl+C를 누르면 변경사항을 취소합니다 (저장되지 않은 내용은 삭제됩니다). 입력을 계속하면 취소가 중단됩니다",errorNonTui:"대화형 터미널 환경이 아니므로 인터페이스를 시작할 수 없습니다. 대화형 TUI 세션에서 다시 시도해 주세요",errorNoQuestions:"유효한 질문이나 선택지가 제공되지 않았습니다. 선택지가 포함된 질문을 최소 하나 이상 제공해 주세요",errorInvalidCondition:{template:"적응형 조건이 유효하지 않습니다: {details} (showIf는 더 이전의 질문 및 기존 선택지 라벨을 참조하거나 answered를 사용해 주세요)",params:["details"]},errorExecutionFailed:{template:"컴포넌트 실행 오류: {reason} (매개변수를 수정한 후 다시 시도해 주세요)",params:["reason"]},expansionRunning:"답변에 따라 후속 질문을 전개하는 중…",expansionAdded:{template:"전개 완료: 질문 {qCount}개, 선택지 {optCount}개 추가됨",params:["qCount","optCount"]},expansionRetracted:"답변이 변경되어 이전 전개 결과를 회수했습니다",expansionStopped:"판단에 필요한 정보가 충분하여 질문을 더 이상 추가하지 않습니다",expansionFailed:{template:"전개 실패: {reason} (계속 답변하거나 그대로 제출할 수 있습니다)",params:["reason"]}},help:{cancel:"Esc/Ctrl+C 취소",clearNote:"x 추가 설명 삭제",confirmQuestion:"Enter 확정",confirmSubmit:"Enter 제출",editNote:"n 추가 설명",editOptionNote:"n 선택지 추가 설명",editQuestionNote:"N 질문 추가 설명",jumpQuestion:"1~9 질문으로 이동",moveCursor:"↑↓/jk 이동",scrollDraft:"[ ] 초안 스크롤",scrollSummary:"↑↓/[ ] 스크롤",selectOptionSingle:"스페이스바/Enter 선택",switchQuestion:"Tab/←→/hl 질문 전환",toggleAll:"a 전체 선택/해제",toggleCheckMulti:"스페이스바 선택/해제"},summary:{title:"【답변 개요 및 확인】",statusDone:"[완료]",statusPending:"[미완료]",questionPrefix:{template:"질문 {index}: {title}",params:["index","title"]},selectedLabel:"선택됨: ",optionNoteBadge:{template:"({icon.note} 메모)"},optionNotePrefix:{template:"{icon.note} 선택지 추가 설명({optLabel}): ",params:["optLabel"]},customNoteLabel:{template:"{icon.note} 질문 추가 설명: "},allDonePrompt:{template:" {icon.check} 모두 완료되었습니다. Enter/Ctrl+S로 제출, Tab/hl/1~9로 돌아가서 수정"},pendingWarning:{template:" {icon.unchecked} 미완료된 질문이 있습니다. Enter로 답변, Tab/hl/1~9로 전환하여 수정"},topMore:{template:" {icon.scrollUp} 위에 {count}줄 더 있음",params:["count"]},bottomMore:{template:" {icon.scrollDown} 아래에 {count}줄 더 있음",params:["count"]}},card:{callQuestionAndOptionCount:{template:"{qCount}개 질문 • {optCount}개 선택지",params:["qCount","optCount"]},callOptionCountOnly:{template:"{optCount}개 선택지",params:["optCount"]},resultCancelled:{template:"{icon.cancel} 취소됨"},resultErrorShort:{template:"{icon.error} 실행 실패"},resultCompleted:{template:"{icon.check} 완료"},resultCount:{template:"{n}개",params:["n"]},optionBullet:{template:"• {title}: {content}",params:["title","content"]},optionWithNote:{template:"{label} [{icon.note} {note}]",params:["label","note"]},questionNoteTag:{template:" ({icon.note} 질문 추가 설명: {text})",params:["text"]},errorBullet:{template:"• 오류 원인: {err}",params:["err"]}},fallbacks:{defaultFormTitle:"창작 결정",defaultQuestionTitle:"향후 창작 방향을 선택해 주세요",defaultCustomPlaceholder:"이 질문에 대한 전반적인 추가 요구사항, 복선 디테일 또는 수정 의견을 입력하세요...",defaultOptionCustomPlaceholder:"해당 선택지에 대한 구체적인 추가 요구사항 또는 수정 세부 내용을 입력하세요...",defaultCustomChoiceName:"사용자 지정 방안",defaultOptionLabel:"기본 방안",unnamedOptionLabel:"이름 없는 방안",unselectedOption:"선택 안 함",autoQuestionId:{template:"q_{n}",params:["n"]},autoQuestionTitle:{template:"질문 {n}",params:["n"]},autoOptionLabel:{template:"선택지 {n}",params:["n"]}}},Ee={tool:{label:"向作者请示"},command:{name:"ask-author",description:"查看 ask_author 创作请示工具说明",notify:"在提示词中指示 AI 调用 ask_author,即可向您请示创作决策"},common:{optionSeparator:"、",bulletPrefix:"• ",helpSeparator:" • "},tabs:{questionTab:{template:"第{index}题",params:["index"]},expansionPlaceholder:"推演中…",submitTab:{template:"{icon.check} 提交答卷"}},view:{modeSingle:"[单选]",conditionalBadge:"[条件]",expansionBadge:"[推演]",expansionPendingHint:"推演期间题目切换与作答暂停,完成后新题目与选项在原位展开",modeMultiAtLeast:{template:"[多选 至少{min}项{maxPart}]",params:["min","maxPart"]},modeMultiOptional:{template:"[多选 可不选{maxPart}]",params:["maxPart"]},modeMultiUnconstrained:{template:"[多选{maxPart}]",params:["maxPart"]},modeMultiMaxPart:{template:" 至多{max}项",params:["max"]},attachedNoteBanner:{template:"{icon.note} 题目补充说明:{text}",params:["text"]},optionAttachedNoteBanner:{template:"{icon.note} [{label}] 选项补充说明:{text}",params:["label","text"]},listTopMore:{template:" {icon.scrollUp} 向上还有 {count} 项",params:["count"]},listBottomMore:{template:" {icon.scrollDown} 向下还有 {count} 项",params:["count"]},optionNotePanelTitle:"选项补充说明",storyDescriptionPanelTitle:"情节设定推演",storyDraftPanelTitle:"正文草稿/分镜头试撰写",customNotePanelTitle:"题目补充说明",confirmPanelTitle:"操作说明",previewScrollInfo:{template:"(行 {start}-{end}/{total},用 [ ] 滚动)",params:["start","end","total"]},previewNoDraft:"(无内容预览)",customNotePanelTips:["• 随时按「N」或选择此项按「Enter」填写/修改本题补充说明","• 按「x」清空本题补充说明","• 补充说明将随所选选项及选项专属补充说明一并提交给 AI 助手"],confirmPanelTips:["• 按 `Enter` 确认本题并前往下一题","• 最后一题确认后自动进入总览提交页"],sectionTitle:{template:"### {title}",params:["title"]},italicLine:{template:"_{text}_",params:["text"]}},menu:{customNoteLabel:{template:"{icon.note} 题目补充说明"},customNoteLabelFilled:{template:"{icon.note} 题目补充说明 (已填写)"},confirmDetailMulti:{template:"已选 {selectedCount} 项",params:["selectedCount","minSelect"]},confirmDetailMultiBelowMin:{template:"已选 {selectedCount}/{minSelect} 项",params:["selectedCount","minSelect"]},confirmLabel:{template:"{icon.check} 确认本题 ({detail}{noteSuffix})",params:["detail","noteSuffix"]},confirmNoteSuffix:" + 补充说明",confirmDesc:"确认并前往下一题或总览页"},editor:{title:{template:" {icon.note} 填写题目补充说明({questionTitle})",params:["questionTitle"]},optionTitle:{template:" {icon.note} 填写选项补充说明({optionLabel} - {questionTitle})",params:["questionTitle","optionLabel"]},footerHelp:" [Enter] 保存并返回 • [Esc/Ctrl+C] 取消"},status:{questionNoteSaved:"已保存本题补充说明",noteCleared:"已清空本题补充说明",optionNoteSaved:{template:"已保存「{label}」补充说明",params:["label"]},optionNoteSavedUnselected:{template:"已保存「{label}」批注(该选项未勾选,仅作批注提交)",params:["label"]},optionNoteSavedAtLimit:{template:"已达上限(至多 {max} 项):批注已保存,但该选项未勾选",params:["max"]},optionNoteCleared:{template:"已清空「{label}」补充说明",params:["label"]},selectedUpToLimit:{template:"已达选择上限(至多 {limit} 项)",params:["limit"]},maxSelectExceeded:{template:"已达上限(至多 {max} 项):请按「空格」取消已选项后重选",params:["max"]},minSelectRequired:{template:"未达下限(至少需 {min} 项):请按「空格」继续勾选,或按「n/N」填写说明",params:["min"]},pleaseAnswerBeforeSubmit:"本题未完成:请按「空格/Enter」选定选项,或按「n/N」填写补充说明",editorDiscardConfirm:"再次按 Esc/Ctrl+C 放弃修改(未保存内容将丢失),继续输入可撤销",errorNonTui:"当前为非交互式终端环境,无法启动交互界面,请在交互式 TUI 会话中重试",errorNoQuestions:"未提供有效的问题或选项,请提供至少一个带选项的问题",errorInvalidCondition:{template:"自适应条件无效:{details}(请让 showIf 指向更早的题目,并引用该题已有选项的标签,或改用 answered)",params:["details"]},errorExecutionFailed:{template:"组件执行异常:{reason}(可修正参数后重试)",params:["reason"]},expansionRunning:"正在根据作答推演后续题目…",expansionAdded:{template:"推演完成:新增 {qCount} 题、{optCount} 个选项",params:["qCount","optCount"]},expansionRetracted:"答案已改动,撤回上一轮推演结果",expansionStopped:"推演判断信息已足够,不再新增题目",expansionFailed:{template:"推演失败:{reason}(可继续作答或直接提交)",params:["reason"]}},help:{cancel:"Esc/Ctrl+C 取消",clearNote:"x 清空补充说明",confirmQuestion:"Enter 确认",confirmSubmit:"Enter 提交",editNote:"n 补充说明",editOptionNote:"n 选项补充说明",editQuestionNote:"N 题目补充说明",jumpQuestion:"1~9 跳转题目",moveCursor:"↑↓/jk 移动",scrollDraft:"[ ] 滚动草稿",scrollSummary:"↑↓/[ ] 滚动",selectOptionSingle:"空格/Enter 选定",switchQuestion:"Tab/←→/hl 切换题目",toggleAll:"a 全选/清空",toggleCheckMulti:"空格 勾选"},summary:{title:"【答卷总览与确认】",statusDone:"[已完成]",statusPending:"[未完成]",questionPrefix:{template:"第{index}题:{title}",params:["index","title"]},selectedLabel:"已选:",optionNoteBadge:{template:"({icon.note} 批注)"},optionNotePrefix:{template:"{icon.note} 选项补充说明({optLabel}):",params:["optLabel"]},customNoteLabel:{template:"{icon.note} 题目补充说明:"},allDonePrompt:{template:" {icon.check} 全部完成,按 Enter/Ctrl+S 提交答卷,Tab/hl/1-9 返回修改"},pendingWarning:{template:" {icon.unchecked} 尚有题目未完成,按 Enter 前往作答,Tab/hl/1-9 切换修改"},topMore:{template:" {icon.scrollUp} 向上还有 {count} 行",params:["count"]},bottomMore:{template:" {icon.scrollDown} 向下还有 {count} 行",params:["count"]}},card:{callQuestionAndOptionCount:{template:"{qCount} 题 • {optCount} 选项",params:["qCount","optCount"]},callOptionCountOnly:{template:"{optCount} 选项",params:["optCount"]},resultCancelled:{template:"{icon.cancel} 已取消"},resultErrorShort:{template:"{icon.error} 执行失败"},resultCompleted:{template:"{icon.check} 已完成"},resultCount:{template:"{n} 项",params:["n"]},optionBullet:{template:"• {title}:{content}",params:["title","content"]},optionWithNote:{template:"{label} [{icon.note} {note}]",params:["label","note"]},questionNoteTag:{template:" ({icon.note} 题目补充说明: {text})",params:["text"]},errorBullet:{template:"• 错误原因:{err}",params:["err"]}},fallbacks:{defaultFormTitle:"创作决策",defaultQuestionTitle:"请选择接下来的创作方案",defaultCustomPlaceholder:"输入本题整体补充要求、伏笔细节或修改意见...",defaultOptionCustomPlaceholder:"输入针对该选项的具体补充要求或修改细节...",defaultCustomChoiceName:"自定义方案",defaultOptionLabel:"默认方案",unnamedOptionLabel:"未命名方案",unselectedOption:"未选",autoQuestionId:{template:"q_{n}",params:["n"]},autoQuestionTitle:{template:"问题 {n}",params:["n"]},autoOptionLabel:{template:"选项 {n}",params:["n"]}}},Le={en_US:le,ja_JP:Oe,ko_KR:ke,zh_CN:Ee},Pe="en_US",At=["LANGUAGE","LC_ALL","LC_MESSAGES","LANG"];function Nt(e){let t=e.trim().split(/[.@]/)[0]??"";if(!t||/^(c|posix)$/i.test(t))return;let i=t.replace(/-/g,"_").split("_"),n=i[0];if(!n)return;let o=i[1];return o?`${n.toLowerCase()}_${o.toUpperCase()}`:n.toLowerCase()}function Qe(e,t){let i=[];for(let t of At){let n=e[t];n&&("LANGUAGE"===t?i.push(...n.split(":")):i.push(n))}t&&i.push(t);let n=Object.keys(Le);for(let e of i){let t=Nt(e);if(!t)continue;let i=n.find(e=>e.toLowerCase()===t);if(i)return i;let o=t.split("_")[0],s=n.find(e=>e.toLowerCase().split("_")[0]===o);if(s)return s}return Pe}var Me=Qe(process.env,Intl.DateTimeFormat().resolvedOptions().locale);function Ot(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&"string"==typeof e.template}function qe(e){return"string"==typeof e?"text":Ot(e)?"template":Array.isArray(e)?"list":"group"}function kt(e,t,i){let n=[],o=0;for(let s of e.template.matchAll(/\{([^{}]+)\}/g)){let r=s.index,a=(s[1]??"").trim();n.push(e.template.slice(o,r));let l=t.indexOf(a);if(l>=0)n.push(l);else{let t=i(a);if(void 0===t)throw new Error(`语言资源模板存在未声明的占位符 {${a}}:${e.template}`);n.push(t)}o=r+s[0].length}return n.push(e.template.slice(o)),(...i)=>{if(i.length!==t.length)throw new Error(`语言资源模板形参数量不匹配(声明 ${t.length},实际 ${i.length}):${e.template}`);return n.map(e=>"string"==typeof e?e:String(i[e])).join("")}}function Re(e,t,i,n){let o=qe(e);if(void 0!==t&&qe(t)!==o)throw new Error(`语言资源键 ${n} 的取值种类与 ${Pe} 不一致`);let s=t??e;if("template"===o){let t=e.params??[],n=kt(s,t,i);return 0===t.length?n():n}if("text"===o)return s;if("list"===o)return[...s];let r=s,a={};for(let[t,o]of Object.entries(e))a[t]=Re(o,r[t],i,n?`${n}.${t}`:t);return a}function $e(e){return Re(le,Le[Me],e,"")}var H={tool:{name:"ask_author",description:"Ask the author to decide between concrete narrative options in an interactive terminal form. Handles a single question or a batch, optional draft previews, author notes, conditional questions, and live follow-up questions generated while the author answers.",promptSnippet:"Ask the author to pick narrative directions in a terminal form",promptGuidelines:["ask_author: Use it when the author must choose a plot branch, character action, scene direction, or setting; do not ask the same question in chat first.","ask_author: Prefer one call over several: flat mode (formTitle + question + options) for a single decision, the questions array for related decisions.","ask_author: Write option labels as concrete actions, put consequences in description, and add preview only when a Markdown draft or storyboard helps the choice.","ask_author: Give a short formTitle and a tabLabel for every long question title; omit fields that use defaults.","ask_author: Add a question id only when a showIf or expansion.insert.after refers to it; showIf may only point at an earlier question's option label or answered.",'ask_author: Pass expansion when follow-up decisions depend on the answers: declare only the first question and let the same model add questions and options on each confirmation; expansion.insert picks "follow" (default), "tail", or {"after":"question_id"}.',"ask_author: The author can multi-select, add notes, and edit drafts; confirmed drafts return as [Draft directive: ...] lines. Treat [Author Decision Cancelled] as no decision, and [Author Consultation Error] as a request to fix the arguments once."]},schema:{optionLabel:"Concrete action or choice label",optionDesc:"Consequences or rationale (optional)",optionPreview:"Markdown draft or storyboard for this option (optional)",optionCustomPlaceholder:"Placeholder for the author's note on this option (optional)",optionShowIf:"Show only if an earlier answer matches; array means all must hold (optional)",questionId:"Id referenced by showIf and expansion.insert.after (optional)",questionTitle:"Question text",questionTabLabel:"Short tab label (default: Q<index>)",questionDesc:"Context shown under the question (optional)",questionMultiSelect:"Allow multiple selections (default false)",questionMinSelect:"Minimum selections, multi-select only (default 1)",questionMaxSelect:"Maximum selections, multi-select only (default: all options)",questionAllowEmpty:"Allow submitting without a selection (default false)",questionOptions:`Options (1-${M}, 2-10 recommended)`,questionAllowCustom:"Allow author notes (default true)",questionCustomPlaceholder:"Placeholder for the author's note (optional)",questionShowIf:"Show only if an earlier answer matches; array means all must hold (optional)",conditionQuestionId:"Earlier question id",conditionOption:"Option label of that question that activates the condition",conditionAnswered:"Any answer (default true) or no answer (false); ignored when option is set",formTitle:"Short title for the consultation",formDesc:"Overall context (optional)",formQuestions:`Questions (1-${k}); batch related decisions in one call`,formSingleQuestion:"Question for flat mode",flatPrefix:"(Flat single-question mode only) ",flatQuestionOptions:`Options for flat mode (1-${M}, 2-10 recommended)`,expansion:"Generate follow-up questions and options while the author answers; insert controls where they land (optional)",expansionMaxQuestions:`Question cap including declared ones (default ${k})`,expansionGuidance:"Standing hint for what the expansion should probe (optional)",expansionInsert:'"follow" (default, after the answered question), "tail" (end of the form), or {"after":"question_id"} (optional)',expansionInsertAfter:"Declared question id to insert after"},expansion:{systemPrompt:'You extend an interactive author decision form while the author answers it.\n\nInput JSON: formTitle, formDescription, guidance, insert, maxAdditionalQuestions, questions (with ids), answers (selected labels and notes).\n\nReturn JSON only:\n{"questions":[{"id":"unique_id","title":"...","description":"...","options":[{"label":"...","description":"..."}]}],"options":[{"questionId":"existing_id","options":[{"label":"..."}]}]}\n\nRules:\n- Add at most maxAdditionalQuestions questions; fewer is better.\n- New questions may also set multiSelect, minSelect, maxSelect, allowEmpty; every option needs a label.\n- Add options to a declared question only when the answers reveal a choice it cannot express; use its id and unused labels.\n- Give new questions unique ids and 2-6 concrete options; put consequences in description.\n- Never repeat a declared question or a declared label.\n- showIf takes {"questionId":"id","option":"label"} or {"questionId":"id","answered":true} and may only reference a question above the insertion point or one of your earlier new questions.\n- Reply {"questions":[],"options":[]} when the answers already determine the next step.\n- No prose, no code fences, no trailing commas.',userPreamble:"Extend this author decision form. Input JSON:",errors:{noModel:"no model is available for live expansion",aborted:"live expansion was aborted",providerFailed:"the expansion request failed",invalidReply:"the expansion reply was not a JSON object"}},markdown:{envelopePrefix:"[Author Decision Finalized]",envelopeSuffix:"Proceed with the author decisions and draft directives above without conversational acknowledgment.",envelopeCancelled:"[Author Decision Cancelled]\nThe author cancelled. Do not proceed with the discarded decision; propose next steps or ask for clarification.",envelopeError:(e,t)=>`[Author Consultation Error]\nFailed to consult author: ${e}\nGuidance: ${t}`,errorReasons:{nonTui:"Interactive TUI is unavailable in the current mode.",noQuestions:"No questions or options were provided.",runtimeError:e=>`Consultation UI failed: ${e}`,invalidCondition:e=>`Invalid condition or insertion anchor: ${e}`,expansionUnavailable:"Live expansion was requested but no model is available in this session."},errorGuidances:{nonTui:"Use defaults, or ask the user in chat if the decision is crucial.",noQuestions:"Provide at least one question with concrete options.",runtimeError:"Check the arguments and retry with valid questions and options.",invalidCondition:"Reference an earlier question id plus one of its option labels, use answered, or point expansion.insert.after at a declared question id.",expansionUnavailable:"Drop the expansion field and declare the questions directly, or retry in a session with a model selected."},adaptiveErrors:{unknownQuestion:e=>`showIf references unknown question id "${e}"`,forwardQuestion:e=>`showIf may only reference an earlier question, got "${e}"`,unknownOption:(e,t)=>`showIf option "${t}" does not exist in question "${e}"`,unknownInsertAnchor:e=>`expansion.insert.after references unknown question id "${e}"`},envelopeEmpty:"The author submitted no answers. Use your defaults, or ask a follow-up if the decision is crucial.",noSelection:"(No selection; the author skipped this question)",notePrefix:"[Author note: ",noteSuffix:"]",draftDirectivePrefix:"[Draft directive: ",draftDirectiveSuffix:"]",answerLine:(e,t,i)=>`${e}. [${t}]: ${i}`,partSeparator:"; ",draftSegmentSeparator:" / ",optionWithDesc:(e,t,i,n)=>`【${e}】${t}${n?` ${n}`:""}${i?` ${i}`:""}`,optionWithoutDesc:(e,t,i)=>`【${e}】${i?` ${i}`:""}${t?` ${t}`:""}`,unselectedOptionNote:(e,t)=>`[Author note on unselected option 【${e}】] ${t}`,fallbackQuestionTitle:e=>`Question ${e}`,fallbackOptionLabel:e=>`Option ${e}`}},Et=e=>e.startsWith("icon.")?E[e.slice(5)]:void 0,v=$e(Et),qt=(e,t,i,n)=>{let o=t<i?v.view.modeMultiMaxPart(t):"";return e>1?v.view.modeMultiAtLeast(e,o):0===e||n?v.view.modeMultiOptional(o):v.view.modeMultiUnconstrained(o)},Lt=(e,t)=>e<t?v.menu.confirmDetailMultiBelowMin(e,t):v.menu.confirmDetailMulti(e,t),Pt=(e,t)=>v.menu.confirmLabel(e,t?v.menu.confirmNoteSuffix:""),r={tool:{...H.tool,label:v.tool.label},schema:H.schema,expansion:H.expansion,markdown:H.markdown,command:v.command,common:v.common,tabs:v.tabs,view:{...v.view,modeMulti:qt},menu:{...v.menu,confirmDetailMulti:Lt,confirmLabel:Pt},editor:v.editor,status:v.status,help:v.help,summary:v.summary,card:v.card,fallbacks:v.fallbacks};import{truncateToWidth as Dt,visibleWidth as de,wrapTextWithAnsi as Ft}from"@earendil-works/pi-tui";var R=class extends Error{constructor(e){super(e),this.name="AdaptiveConditionError"}};function U(e){return!!e.customText?.trim()}function Qt(e){for(let t of e.optionNotes.values())if(t?.trim())return!0;return!1}function Mt(e){return U(e)||Qt(e)}function ue(e,t,i){let n=void 0!==e,o=O(e??1,0,i);return{minSelect:o,minSelectExplicit:n,maxSelect:O(t??i,o,i)}}function ce(e){return e?(Array.isArray(e)?e:[e]).map(e=>({questionId:e.questionId,option:e.option,answered:e.answered})):[]}function Be(e,t){return{question:{id:g(e.id)??r.fallbacks.autoQuestionId(t+1),title:g(e.title)??r.fallbacks.autoQuestionTitle(t+1),tabLabel:g(e.tabLabel),description:g(e.description),multiSelect:!!e.multiSelect,...ue(e.minSelect,e.maxSelect,e.options.length),options:e.options.map(e=>({label:g(e.label)??r.fallbacks.unnamedOptionLabel,description:g(e.description),preview:g(e.preview),customPlaceholder:g(e.customPlaceholder),showIf:[]})),allowEmpty:!!e.allowEmpty,allowCustom:!1!==e.allowCustom,customPlaceholder:g(e.customPlaceholder)??r.fallbacks.defaultCustomPlaceholder,showIf:[]},questionConditions:ce(e.showIf),optionConditions:e.options.map(e=>ce(e.showIf))}}function X(e,t,i,n){return e.map(e=>{let o=g(e.questionId)??"",s=i.get(o);if(void 0===s)throw new R(r.markdown.adaptiveErrors.unknownQuestion(o));if(s>=t)throw new R(r.markdown.adaptiveErrors.forwardQuestion(o));let a=g(e.option);if(void 0===a)return{kind:"answered",questionIndex:s,answered:!1!==e.answered};let l=n[s]?.options.findIndex(e=>e.label===a)??-1;if(l<0)throw new R(r.markdown.adaptiveErrors.unknownOption(o,a));return{kind:"option",questionIndex:s,optionIndex:l}})}function _e(e){let t=e.map((e,t)=>Be(e,t)),i=Rt(t.map(e=>e.question)),n=new Map(i.map((e,t)=>[e.id,t]));return i.map((e,o)=>{let s=t[o];return{...e,showIf:X(s?.questionConditions??[],o,n,i),options:e.options.map((e,t)=>({...e,showIf:X(s?.optionConditions[t]??[],o,n,i)}))}})}function De(e,t){let i={label:e.label,description:e.description,preview:e.preview,customPlaceholder:e.customPlaceholder};return t&&(i.customText=t),i}function Rt(e){let t=new Set;return e.map((e,i)=>{if(!t.has(e.id))return t.add(e.id),e;let n=r.fallbacks.autoQuestionId(i+1);for(let e=2;t.has(n);e++)n=`${n}_${e}`;return t.add(n),{...e,id:n}})}function V(e){return Ne(e).replace(/[“”„‟«»]/g,"'").replace(/[\[\]]/g,e=>"["===e?"[":"]").replace(/[【】]/g,"").replace(/;/g,";")}function $t(e){if(!e)return;let t=q(e);if(!t.trim())return;let i=t.split("\n").map(e=>{let t=e.trim();return t?(t=t.replace(/^(?:[>#]+\s*)+/,""),t=t.replace(/\s+/g," "),t):""}).filter(Boolean);return 0!==i.length?i.join(r.markdown.draftSegmentSeparator):void 0}function _t(e,t){return void 0===t?e:e===r.fallbacks.defaultQuestionTitle||e===r.fallbacks.autoQuestionTitle(t+1)?r.markdown.fallbackQuestionTitle(t+1):e}function Fe(e,t){return void 0===t?e:e===r.fallbacks.unnamedOptionLabel||e===r.fallbacks.defaultOptionLabel||e===r.fallbacks.autoOptionLabel(t)?r.markdown.fallbackOptionLabel(t):e}var G=class{formTitle;formDescription;expansionMaxQuestions;expansionInsert;questionList;expansions=[];revisionValue=0;states=new Map;visibilityCache;constructor(e){let t=e.questions??[],i=t.length>0;this.formTitle=g(e.formTitle)??r.fallbacks.defaultFormTitle,this.formDescription=g(e.description),this.expansionMaxQuestions=O(e.expansion?.maxQuestions??k,1,k),this.expansionInsert=e.expansion?.insert??"follow",this.questionList=i?_e(t):e.options?.length?_e([{title:g(e.question)??r.fallbacks.defaultQuestionTitle,description:g(e.description),multiSelect:e.multiSelect,minSelect:e.minSelect,maxSelect:e.maxSelect,allowEmpty:e.allowEmpty,options:e.options,allowCustom:e.allowCustom,customPlaceholder:e.customPlaceholder}]):[],this.resolveInsertIndex(this.expansionInsert)}get questions(){return this.questionList}get expansionInsertLabel(){return"follow"===this.expansionInsert?"right after the question the author just confirmed":"tail"===this.expansionInsert?"at the end of the form":`right after question "${this.expansionInsert.after}"`}get revision(){return this.revisionValue}get questionCount(){return this.questions.length}getQuestion(e){return this.questions[e]}getState(e){let t=this.states.get(e);return t||(t={selectedIndices:new Set,optionNotes:new Map},this.states.set(e,t)),t}snapshot(){let e=this.visibilityCache;if(e&&e.revision===this.revisionValue)return e;let t=[],i=[],n=[];for(let[e,o]of this.questions.entries()){let s=o.showIf.every(e=>this.conditionHolds(e,t,n)),r=o.options.map(e=>e.showIf.every(e=>this.conditionHolds(e,t,n))),a=this.states.get(e),l=[];if(a)if(o.multiSelect)for(let e of a.selectedIndices)r[e]&&l.push(e);else void 0!==a.selectedIndex&&r[a.selectedIndex]&&l.push(a.selectedIndex);l.sort((e,t)=>e-t),t.push(s),i.push(r),n.push(l)}return this.visibilityCache={revision:this.revisionValue,questions:t,options:i,selected:n},this.visibilityCache}conditionHolds(e,t,i){return!!t[e.questionIndex]&&("answered"===e.kind?this.hasAnyResponse(e.questionIndex)===e.answered:(i[e.questionIndex]??[]).includes(e.optionIndex))}hasAnyResponse(e){let t=this.states.get(e);return!!t&&(void 0!==t.selectedIndex||t.selectedIndices.size>0||Mt(t))}isQuestionVisible(e){return this.snapshot().questions[e]??!1}isOptionVisible(e,t){return this.snapshot().options[e]?.[t]??!1}getVisibleQuestionIndices(){let{questions:e}=this.snapshot(),t=[];for(let[i,n]of e.entries())n&&t.push(i);return t}getSelectedIndices(e){return[...this.snapshot().selected[e]??[]]}getSelectedIndex(e){return this.snapshot().selected[e]?.[0]}bumpRevision(){this.revisionValue++}getExpansions(){return[...this.expansions]}answerSignature(e){let t=this.questionList[e];if(!t)return;let i=this.getSelectedIndices(e);return 0!==i.length?i.map(e=>t.options[e]?.label??"").join("|"):void 0}resolveInsertIndex(e,t=0){if("tail"===e)return this.questionList.length;if("follow"===e)return Math.min(t+1,this.questionList.length);let i=g(e.after)??"",n=this.questionList.findIndex(e=>e.id===i);if(n<0)throw new R(r.markdown.adaptiveErrors.unknownInsertAnchor(i));return n+1}pushExpansion(e){let t=Math.max(0,this.expansionMaxQuestions-this.questionList.length),i=this.resolveInsertIndex(this.expansionInsert,e.questionIndex),n=this.insertQuestions(i,e.payload.questions.slice(0,t)),o=this.appendOptions(e.payload.optionAdditions),s={questionIndex:e.questionIndex,signature:e.signature,insertAt:i,addedQuestions:n,addedOptions:o};return this.expansions.push(s),(n>0||o.length>0)&&this.bumpRevision(),s}retractFrom(e){let t=0;for(;this.expansions.length>0;){let i=this.expansions[this.expansions.length-1];if(!i||i.questionIndex<e)break;this.expansions.pop(),this.rollback(i),t++}return t>0&&this.bumpRevision(),t}canExpandOnConfirm(e,t){if(!t||!this.isQuestionVisible(e)||this.questionList.length>=this.expansionMaxQuestions)return!1;let i=this.answerSignature(e);return void 0===i||this.expansions.find(t=>t.questionIndex===e)?.signature!==i}insertQuestions(e,t){if(0===t.length)return 0;let i=new Set(this.questionList.map(e=>e.id)),n=t.map((t,n)=>{let o=e+n,s=Be(t,o),r=this.uniqueQuestionId(s.question.id,o,i);return{...s,question:{...s.question,id:r}}});this.remapQuestionIndices(e,n.length);let o=[...this.questionList.slice(0,e),...n.map(e=>e.question),...this.questionList.slice(e)],s=new Map(o.map((e,t)=>[e.id,t])),r=n.map((t,i)=>{let n=e+i,r=t.question;return{...r,showIf:X(t.questionConditions,n,s,o),options:r.options.map((e,i)=>({...e,showIf:X(t.optionConditions[i]??[],n,s,o)}))}});return this.questionList.splice(e,0,...r),r.length}remapQuestionIndices(e,t){let i=i=>i>=e?i+t:i;for(let[e,t]of this.questionList.entries())this.questionList[e]={...t,showIf:t.showIf.map(e=>({...e,questionIndex:i(e.questionIndex)})),options:t.options.map(e=>({...e,showIf:e.showIf.map(e=>({...e,questionIndex:i(e.questionIndex)}))}))};let n=new Map;for(let[e,t]of this.states)n.set(i(e),t);this.states.clear();for(let[e,t]of n)this.states.set(e,t);for(let[e,t]of this.expansions.entries())this.expansions[e]={...t,questionIndex:i(t.questionIndex),insertAt:i(t.insertAt),addedOptions:t.addedOptions.map(e=>({...e,questionIndex:i(e.questionIndex)}))}}appendOptions(e){if(0===e.length)return[];let t=new Map(this.questionList.map((e,t)=>[e.id,t])),i=[];for(let n of e){let e=t.get(n.questionId);void 0!==e&&i.push({questionIndex:e,options:n.options.map(i=>({label:i.label,description:i.description,preview:i.preview,customPlaceholder:i.customPlaceholder,showIf:X(ce(i.showIf),e,t,this.questionList)}))})}let n=[];for(let e of i){let t=this.questionList[e.questionIndex];if(!t||0===e.options.length)continue;let i=[...t.options,...e.options],o=ue(t.minSelectExplicit?t.minSelect:void 0,t.maxSelect===t.options.length?void 0:t.maxSelect,i.length);this.questionList[e.questionIndex]={...t,options:i,...o},n.push({questionIndex:e.questionIndex,count:e.options.length})}return n}rollback(e){for(let t of[...e.addedOptions].reverse()){let e=this.questionList[t.questionIndex];if(!e)continue;let i=e.options.slice(0,Math.max(0,e.options.length-t.count)),n=ue(e.minSelectExplicit?e.minSelect:void 0,e.maxSelect,i.length);this.questionList[t.questionIndex]={...e,options:i,...n},this.dropOptionsFromState(t.questionIndex,i.length)}if(e.addedQuestions>0){let t=e.insertAt;this.questionList.splice(t,e.addedQuestions);for(let i=t;i<t+e.addedQuestions;i++)this.states.delete(i);this.remapQuestionIndices(t,-e.addedQuestions)}}dropOptionsFromState(e,t){let i=this.states.get(e);if(i){for(let e of[...i.selectedIndices])e>=t&&i.selectedIndices.delete(e);void 0!==i.selectedIndex&&i.selectedIndex>=t&&(i.selectedIndex=void 0);for(let e of[...i.optionNotes.keys()])e>=t&&i.optionNotes.delete(e)}}uniqueQuestionId(e,t,i){if(!i.has(e))return i.add(e),e;let n=r.fallbacks.autoQuestionId(t+1);for(let e=2;i.has(n);e++)n=`${n}_${e}`;return i.add(n),n}getMenuItems(e){let t=this.getQuestion(e);if(!t)return[];let i=this.getState(e),n=this.hasSubmittableNote(e),o=[];for(let[i,n]of t.options.entries())this.isOptionVisible(e,i)&&o.push({type:"option",optionIndex:i,label:n.label,description:n.description,preview:n.preview});t.allowCustom&&o.push({type:"custom_note",label:U(i)?r.menu.customNoteLabelFilled:r.menu.customNoteLabel});let s=this.getSelectedIndex(e),a=t.multiSelect?r.menu.confirmDetailMulti(this.getSelectedIndices(e).length,t.minSelect):void 0!==s?t.options[s]?.label??r.fallbacks.unselectedOption:n?r.fallbacks.defaultCustomChoiceName:r.fallbacks.unselectedOption;return o.push({type:"confirm_btn",label:r.menu.confirmLabel(a,n),description:r.menu.confirmDesc}),o}hasSubmittableNote(e){let t=this.states.get(e);if(!t)return!1;if(t.customText?.trim())return!0;for(let[i,n]of t.optionNotes)if(n?.trim()&&this.isOptionVisible(e,i))return!0;return!1}isQuestionAnswered(e){let t=this.questions[e];if(!t||!this.isQuestionVisible(e))return!1;if(!t.multiSelect)return void 0!==this.getSelectedIndex(e)||t.allowEmpty||t.allowCustom&&this.hasSubmittableNote(e);let i=this.getSelectedIndices(e).length;return!!(i>=t.minSelect||0===i&&t.allowEmpty||!t.minSelectExplicit&&0===i&&t.allowCustom&&this.hasSubmittableNote(e))}areAllQuestionsAnswered(){return this.getVisibleQuestionIndices().every(e=>this.isQuestionAnswered(e))}toggleOption(e,t){let i=this.getQuestion(e);if(!i||!i.options[t])return"limit";let n=this.getState(e);return i.multiSelect?n.selectedIndices.has(t)?(n.selectedIndices.delete(t),this.bumpRevision(),"deselected"):this.getSelectedIndices(e).length>=i.maxSelect?"limit":(n.selectedIndices.add(t),this.bumpRevision(),"selected"):(n.selectedIndex=n.selectedIndex===t?void 0:t,this.bumpRevision(),void 0===n.selectedIndex?"deselected":"selected")}commitOption(e,t){let i=this.getQuestion(e);if(!i||!i.options[t])return;let n=this.getState(e);i.multiSelect?n.selectedIndices.has(t)||this.getSelectedIndices(e).length>=i.maxSelect||(n.selectedIndices.add(t),this.bumpRevision()):n.selectedIndex!==t&&(n.selectedIndex=t,this.bumpRevision())}selectAllOrClear(e){let t=this.getQuestion(e);if(!t||!t.multiSelect)return"cleared";let i=this.getState(e);if(this.getSelectedIndices(e).length>=t.maxSelect)return i.selectedIndices.clear(),this.bumpRevision(),"cleared";let n=this.getSelectedIndices(e).length;for(let[o]of t.options.entries()){if(n>=t.maxSelect)break;!this.isOptionVisible(e,o)||i.selectedIndices.has(o)||(i.selectedIndices.add(o),n++)}return this.bumpRevision(),"filled"}setOptionNote(e,t,i){let n=this.getQuestion(e);if(!n||!n.options[t])return"cleared";let o=this.getState(e),s=g(i);return this.bumpRevision(),s?(o.optionNotes.set(t,s),n.multiSelect?this.getSelectedIndices(e).includes(t)?"saved":this.getSelectedIndices(e).length>=n.maxSelect?"savedAtLimit":(o.selectedIndices.add(t),"saved"):void 0===o.selectedIndex?(o.selectedIndex=t,"saved"):o.selectedIndex===t?"saved":"savedUnselected"):(o.optionNotes.delete(t),"cleared")}setQuestionNote(e,t){let i=this.getState(e),n=g(t);return i.customText=n,this.bumpRevision(),n?"saved":"cleared"}clearOptionNote(e,t){let i=this.states.get(e);return!!i?.optionNotes.has(t)&&(i.optionNotes.delete(t),this.bumpRevision(),!0)}clearQuestionNote(e){let t=this.states.get(e);return!!t?.customText?.trim()&&(t.customText=void 0,this.bumpRevision(),!0)}collectOptionNotes(e,t,i){let n={};if(!i)return n;for(let[o,s]of i.optionNotes){let i=g(s);i&&t.options[o]&&this.isOptionVisible(e,o)&&(n[o+1]=i)}return n}compileAnswers(){let e=[];for(let[t,i]of this.questions.entries()){if(!this.isQuestionVisible(t))continue;let n=this.states.get(t),o=n?.customText?.trim()?q(n.customText.trim()):void 0,s={questionId:i.id,questionTitle:i.title,customText:o};if(i.multiSelect){let o=this.getSelectedIndices(t),r=this.collectOptionNotes(t,i,n),a=[];for(let e of o){let t=i.options[e];t&&a.push(De(t,r[e+1]))}let l=Object.keys(r).length>0;e.push({...s,multiSelect:!0,selectedOptions:a,selectedIndices:o.map(e=>e+1),optionNotes:l?r:void 0})}else{let o=this.getSelectedIndex(t);if(void 0!==o){let r=i.options[o],a=this.collectOptionNotes(t,i,n);e.push({...s,multiSelect:!1,selectedOption:r?De(r,a[o+1]):void 0,selectedOptionIndex:o+1,optionNotes:Object.keys(a).length>0?a:void 0})}else if(this.isQuestionAnswered(t)){let o=this.collectOptionNotes(t,i,n),r=Object.keys(o).length>0;e.push({...s,multiSelect:!1,optionNotes:r?o:void 0})}}}return e}formatAnswers(e){if(0===e.length)return`${r.markdown.envelopePrefix}\n${r.markdown.envelopeEmpty}\n${r.markdown.envelopeSuffix}`;let t=e=>e?`${r.markdown.notePrefix}${V(e)}${r.markdown.noteSuffix}`:"",i=e=>e?`${r.markdown.draftDirectivePrefix}${V(e)}${r.markdown.draftDirectiveSuffix}`:"",n=new Map(this.questions.map((e,t)=>[e.id,t])),o=e.map((e,o)=>{let s=n.get(e.questionId),a=(e.multiSelect?e.selectedOptions??[]:e.selectedOption?[e.selectedOption]:[]).map((n,o)=>{let s=$t(n.preview),a=t(g(n.customText)??""),l=V(Fe(n.label,e.multiSelect?e.selectedIndices?.[o]:e.selectedOptionIndex)),u=V(n.description??"");return u?r.markdown.optionWithDesc(l,u,i(s),a):r.markdown.optionWithoutDesc(l,i(s),a)}),l=void 0===s?void 0:this.questions[s];if(l&&e.optionNotes){let i=new Set(e.multiSelect?e.selectedIndices??[]:void 0!==e.selectedOptionIndex?[e.selectedOptionIndex]:[]);for(let[n,o]of Object.entries(e.optionNotes)){let e=Number(n);if(i.has(e))continue;let s=l.options[e-1]?.label;s&&o&&a.push(r.markdown.unselectedOptionNote(V(Fe(s,e)),t(o)))}}e.customText&&a.push(t(e.customText));let u=a.join(r.markdown.partSeparator)||r.markdown.noSelection;return r.markdown.answerLine(o+1,V(_t(e.questionTitle,s)),u)});return`${r.markdown.envelopePrefix}\n${o.join("\n")}\n${r.markdown.envelopeSuffix}`}};function F(e,t){return e.options[t]?.label??r.fallbacks.autoOptionLabel(t+1)}function Bt(e,t,i){return"option"===e.type&&void 0!==e.optionIndex?t.multiSelect?i.selectedIndices.has(e.optionIndex):i.selectedIndex===e.optionIndex:"custom_note"===e.type&&U(i)}function Vt(e,t,i,n){return"option"!==n.type||void 0===n.optionIndex?"":t.multiSelect?i.selectedIndices.has(n.optionIndex)?e.fg("success",E.checkedMulti):e.fg("dim",E.uncheckedMulti):i.selectedIndex===n.optionIndex?e.fg("accent",E.checkedSingle):e.fg("dim",E.uncheckedSingle)}function Ve(e,t,i,n,o,s){let r=Bt(t,n,o),a=`${i?e.fg("accent",e.bold(`${E.cursor} `)):" "}${Vt(e,n,o,t)}`,l=de(a),u=" ".repeat(l),c=Math.max(8,s-l),p=t.label;return"option"===t.type&&void 0!==t.optionIndex&&o.optionNotes.get(t.optionIndex)&&(p=`${t.label} ${E.note}`),(de(p)<=c?[p]:Ft(p,c)).map((n,o)=>{if(i)return e.bg("selectedBg",e.fg("text",e.bold(W(0===o?`${a}${n}`:`${u}${n}`,s))));let l=e.fg("option"!==t.type&&"custom_note"!==t.type||r?"text":"dim",n);return P(0===o?`${a}${l}`:`${u}${l}`,s)})}function Ut(e,t,i){let n=e.getQuestion(t)?.tabLabel;return n?Dt(n,y.tabLabelMaxWidth):r.tabs.questionTab(i)}function Ue(e,t,i,n,o=!1){let s=i===t.questionCount,a=[],l=[],u=` ${r.tabs.expansionPlaceholder} `;for(let[n,s]of t.getVisibleQuestionIndices().entries()){let r=s===i,a=t.isQuestionAnswered(s),c=r&&o?u:` ${a?E.checked:E.unchecked} ${Ut(t,s,n+1)} `,p=r?o?"warning":"accent":a?"success":"muted";l.push(r?e.bg("selectedBg",e.fg(p,e.bold(c))):e.fg(p,c))}let c=s&&o?u:` ${r.tabs.submitTab} `,p=s?o?"warning":"success":t.areAllQuestionsAnswered()?"success":"dim";l.push(s?e.bg("selectedBg",e.fg(p,e.bold(c))):e.fg(p,c));let d="",m=0;for(let e of l){let t=de(e);m>0&&m+1+t>n?(a.push(P(d,n)),d="",m=0):m>0&&(d+=" ",m+=1),d+=e,m+=t}return a.push(P(d,n)),a.push(e.fg("dim",re(n))),a}function je(e,t,i){e.push(""),e.push(` ${t.fg("warning",t.bold(r.status.expansionRunning))}`),e.push(""),A(e,t.fg("dim",` ${r.view.expansionPendingHint}`),i," "),e.push("")}function J(e,t,i){i&&(e.push(""),e.push(` ${t.fg("warning",i)}`))}function jt(e){return e.join(r.common.helpSeparator)}function Z(e,t,i,n){A(e,i.fg("dim",jt(t)),n," ")}function _(e,t,i){e.push(t.fg("accent",re(i,y.dividerThick)))}function ze(e,t,i,n,o,s){let a=t.getQuestion(i);if(!a)return[];let l=[];if("option"===n?.type){let t=n.optionIndex,i=a.options[t],o=F(a,t),u=i?.customPlaceholder??r.fallbacks.defaultOptionCustomPlaceholder;l.push(e.fg("accent",e.bold(r.editor.optionTitle(a.title,o)))),i?.description&&A(l,e.fg("muted",i.description),s," "),l.push(""),l.push(e.fg("accent",` ${u}`))}else l.push(e.fg("accent",e.bold(r.editor.title(a.title)))),a.description&&A(l,e.fg("muted",a.description),s," "),l.push(""),l.push(e.fg("accent",` ${a.customPlaceholder}`));l.push("");for(let e of o.render(Math.max(10,s-4)))l.push(` ${e}`);return l.push(""),l.push(e.fg("dim",r.editor.footerHelp)),_(l,e,s),l}import{visibleWidth as hn}from"@earendil-works/pi-tui";import{getMarkdownTheme as zt}from"@earendil-works/pi-coding-agent";import{Markdown as Wt}from"@earendil-works/pi-tui";var We=[{opener:"「",closer:"」",marker:"d",maxSpanLength:400,paint:(e,t)=>e.fg("accent",t)},{opener:"(",closer:")",marker:"m",maxSpanLength:400,paint:(e,t)=>e.fg("muted",e.italic(t))}],He=new Map(We.map(e=>[e.opener,e])),Xe=new Map(We.map(e=>[e.marker,e]));function Ht(e){let t=zt();return{...t,heading:t=>e.fg("accent",e.bold(t)),quote:t=>e.fg("muted",t),quoteBorder:t=>e.fg("dim",t),listBullet:t=>e.fg("accent",t),code:i=>Xt(e,i)??t.code(i),codeBlockBorder:t=>e.fg("dim",t),link:t=>e.fg("accent",t),linkUrl:t=>e.fg("dim",t)}}function Xt(e,t){if(!t.startsWith("\0"))return;let i=[],n=0;for(;n<t.length;){if("\0"!==t.charAt(n))return;let o=Xe.get(t.charAt(n+1));if(!o)return;let s=t.indexOf("\0",n+2),r=s<0?t.length:s;i.push(o.paint(e,t.slice(n+2,r))),n=r}return i.length>0?i.join(""):void 0}var Gt=/^ {0,3}(`{3,}|~{3,})/,Kt=/^ {4,}\S/,Yt=/^ {0,3}(?:<(?=[/!?a-zA-Z])|\|)/,Ge=/^ {0,3}(?:\$\$|\\\[)/;function Ke(e){for(let t=0;t<e.length;t++){let i=e.charAt(t);if("\\"===i){if("("===e.charAt(t+1)||"["===e.charAt(t+1))return!0;t++;continue}if("$"!==i)continue;let n=e.charAt(t+1);if(""!==n&&!/\s/.test(n))return!0}return!1}var Jt=/^(?: {0,3}>[ \t]?)+/,Zt=/^ {0,3}\[[^\]\n]*\]:/;function Ze(e){return e.replace(Jt,"")}function en(e){return!!e.includes("|")&&/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/.test(Ze(e))}var tn=/^ {0,3}(?:#{1,6}[ \t]|[-+*][ \t]|\d{1,9}[.)][ \t]|>|\||`{3,}|~{3,})/,nn=/[`*_\[\]<>$\\|]|~~|&(?:[A-Za-z][A-Za-z0-9]*|#\d+|#[xX][0-9a-fA-F]+);/;function on(e){let t=[],i=0;for(let n of e)t.push(i),i+=n.length+1;return t}function sn(e,t,i){let n=new Uint8Array(e.length),o=(e,t)=>{for(let i=e;i<t;i++)n[i]=1},s=e=>{let n=i[e]??0;o(n,n+(t[e]?.length??0))},r=null,a=!1,l=null;for(let e=0;e<t.length;e++){let i=t[e]??"";if(""===i.trim()){a=!1,null!==r&&s(e),null!==l&&s(e);continue}if(null!==l){s(e);let t=i.indexOf(l);if(t>=0){let e=i.slice(t+l.length);l=null,Ke(e)&&(a=!0)}continue}if(null!==r){s(e),r.test(i)&&(r=null);continue}if(a){s(e);continue}if(en(i)){s(e),a=!0;let i=t[e-1];void 0!==i&&i.includes("|")&&s(e-1);continue}let n=Gt.exec(i),o=n?.[1],u=i.slice(n?.[0].length??0);if(void 0===o||"~"!==o[0]&&u.includes("`"))if(Kt.test(i))s(e);else if(Yt.test(Ze(i)))s(e),a=!0;else if(Zt.test(i))s(e);else{if(Ge.test(i)){let t=i.replace(Ge,"");s(e),t.includes(t.startsWith("$$")?"$$":"\\]")||(l=t.startsWith("$$")?"$$":"\\]");continue}Ke(i)&&(s(e),a=!0)}else s(e),r=new RegExp(`^ {0,3}${o[0]??"`"}{${o.length},}[ \\t]*$`)}let u=0;for(;u<e.length;){if("`"!==e[u]||1===n[u]){u++;continue}let t=0;for(;"`"===e[u+t]&&0===n[u+t];)t++;let i=rn(e,n,u+t,t);if(i<0)return null;o(u,i+t),u=i+t}return n}function rn(e,t,i,n){for(let o=i;o<e.length;o++){if("`"!==e[o]||1===t[o])continue;let i=0;for(;"`"===e[o+i]&&0===t[o+i];)i++;if(i===n&&"`"!==e[o+n])return o;o+=i-1}return-1}function an(e,t,i,n){let o=[],s=[];for(let r=0;r<e.length;r++){if(1===t[r])continue;let a=e[r]??"",l=He.get(a);if(void 0!==l){o.push({template:l,start:r});continue}let u=ln(o,a);if(u<0)continue;let c=o[u];if(o.length=u,!c)continue;let p=r+1;if(p-c.start>c.template.maxSpanLength||nn.test(e.slice(c.start,p)))continue;let d=Ye(n,c.start),m=Ye(n,p-1);if(!un(i,d,m))continue;let h=s[s.length-1];for(;void 0!==h&&h.startFlat>=c.start;)s.pop(),h=s[s.length-1];s.push({template:c.template,startFlat:c.start,startLine:d,startCol:c.start-(n[d]??0),endLine:m,endCol:p-(n[m]??0)})}return s}function ln(e,t){for(let i=e.length-1;i>=0;i--)if(e[i]?.template.closer===t)return i;return-1}function Ye(e,t){let i=0,n=Math.max(0,e.length-1);for(;i<n;){let o=i+n+1>>1;(e[o]??0)<=t?i=o:n=o-1}return i}function un(e,t,i){if(t===i)return!0;for(let n=t+1;n<=i;n++){let t=e[n]??"";if(""===t.trim()||tn.test(t))return!1}return!0}function cn(e,t){let i=[];for(let n of t)i.push(`\0${n.template.marker}${e.slice(n.start,n.end)}`);return`\`${i.join("")}\``}function dn(e,t){let i=[],n=0,o=0;for(;o<t.length;){let s=t[o];if(!s)break;let r=[s],a=s;for(;o+1<t.length;){let e=t[o+1];if(!e||e.start!==a.end)break;o++,a=e,r.push(e)}let l=s.start,u=a.end,c=e.slice(n,l),p=e.slice(l,u),d="`"===e.charAt(l-1)||"`"===e.charAt(u);i.push(c,d?p:cn(e,r)),n=u,o++}return i.push(e.slice(n)),i.join("")}function pn(e,t,i){for(let n=t;n<i;n++)if(1===e[n])return!0;return!1}function mn(e,t,i,n){let o=new Map;for(let s of n){let n=(t[s.startLine]??0)+s.startCol,r=(t[s.endLine]??0)+s.endCol;for(let a=s.startLine;a<=s.endLine;a++){let l=t[a]??0,u=l+(e[a]?.length??0),c=Math.max(n,l),p=Math.min(r,u);if(p<=c||pn(i,c,p))continue;let d={start:c-l,end:p-l,template:s.template},m=o.get(a);m?m.push(d):o.set(a,[d])}}return e.map((e,t)=>{let i=o.get(t);return i?(i.sort((e,t)=>e.start-t.start),dn(e,i)):e}).join("\n")}function fn(e){if(0===e.length)return e;let t=e.split("\n"),i=on(t),n=sn(e,t,i);if(null===n)return e;let o=an(e,n,t,i);return 0===o.length?e:mn(t,i,n,o)}function Je(e,t){return`${r.view.sectionTitle(e)}\n\n${t.map(e=>`${e}\n`).join("")}`}function et(e,t,i,n,o){if(!e)return[];let s="";"option"===e.type?(i&&(s+=`${r.view.sectionTitle(r.view.optionNotePanelTitle)}\n\n${q(i)}\n\n`),e.description&&(s+=`${r.view.sectionTitle(r.view.storyDescriptionPanelTitle)}\n\n${q(e.description)}\n\n`),e.preview?s+=`${r.view.sectionTitle(r.view.storyDraftPanelTitle)}\n\n${q(e.preview)}\n\n`:!e.description&&!i&&(s+=`${r.view.italicLine(r.view.previewNoDraft.trim())}\n\n`)):"custom_note"===e.type?(s+=Je(r.view.customNotePanelTitle,r.view.customNotePanelTips),t&&(s+=`\n${q(t)}\n\n`)):s+=Je(r.view.confirmPanelTitle,r.view.confirmPanelTips);let a=Ht(o);return new Wt(s.trim(),1,0,a,void 0,{transform:fn}).render(n)}var bn=32;function tt(e){return O(e-14,6,y.splitPreviewHeight)}function pe(e){return O(e-18,3,y.singlePreviewHeight)}function gn(e,t,i,n){return i.options.some((i,o)=>e.isOptionVisible(t,o)&&(!!i.preview||hn(i.description??"")>30||!!n.optionNotes.get(o)))}var te=class{constructor(e,t){this.theme=e,this.model=t}theme;model;previewCache=new Map;leftColCache;clear(){this.previewCache.clear(),this.leftColCache=void 0}clearColumnCache(){this.leftColCache=void 0}render(e,t,i){let n=this.model.getQuestion(e.tab);if(!n)return{lines:[]};let o=this.model.getState(e.tab),s=[],a=n.options.filter((t,i)=>this.model.isOptionVisible(e.tab,i)).length;A(s,` ${n.multiSelect?this.theme.fg("warning",r.view.modeMulti(n.minSelect,n.maxSelect,a,n.allowEmpty)):this.theme.fg("accent",r.view.modeSingle)}${n.showIf.length>0?` ${this.theme.fg("muted",r.view.conditionalBadge)}`:""}${e.expandable?` ${this.theme.fg("warning",r.view.expansionBadge)}`:""} ${this.theme.bold(n.title)}`,t),n.description&&A(s,this.theme.fg("muted",n.description),t," "),o.customText?.trim()&&A(s,this.theme.fg("success",r.view.attachedNoteBanner(o.customText)),t," ");let l=e.menuItems[e.optionIndex];if("option"===l?.type&&void 0!==l.optionIndex){let e=o.optionNotes.get(l.optionIndex)?.trim();if(e){let i=F(n,l.optionIndex);A(s,this.theme.fg("success",r.view.optionAttachedNoteBanner(i,e)),t," ")}}s.push("");let u,c=gn(this.model,e.tab,n,o);u=t>=y.splitViewMinWidth&&c?this.renderSplitView(s,n,o,e,t,i):this.pushListItems(s,n,o,e,t-2,c,i),J(s,this.theme,e.statusMessage),s.push("");let p=[r.help.switchQuestion];return this.model.getVisibleQuestionIndices().length>1&&p.push(r.help.jumpQuestion),p.push(r.help.moveCursor),"option"===l?.type?(p.push(r.help.editOptionNote),p.push(r.help.editQuestionNote)):p.push(r.help.editNote),("option"===l?.type&&void 0!==l.optionIndex&&o.optionNotes.has(l.optionIndex)||U(o))&&p.push(r.help.clearNote),p.push(n.multiSelect?r.help.toggleCheckMulti:r.help.selectOptionSingle),n.multiSelect&&(p.push(r.help.toggleAll),p.push(r.help.confirmQuestion)),c&&p.push(r.help.scrollDraft),p.push(r.help.cancel),Z(s,p,this.theme,t),_(s,this.theme,t),{lines:s,previewViewport:u}}previewContentLines(e,t,i,n,o){let s=[e,t.type,t.optionIndex??-1,o,i??"",n??""].join(""),r=this.previewCache.get(s);if(r)return r;let a=et(t,i,n,o,this.theme);if(this.previewCache.size>=bn){let e=this.previewCache.keys().next();e.done||this.previewCache.delete(e.value)}return this.previewCache.set(s,a),a}buildPreviewBox(e,t,i,n,o,s,a){let l=this.previewContentLines(e,t,i,n,o),u=l.length,c=$(a,u,s),p=Y(l,c,s).map(e=>P(e,o));if(u>s){let e=r.view.previewScrollInfo(c+1,Math.min(u,c+s),u);p.push(P(` ${this.theme.fg("dim",e)}`,o))}return{lines:p,viewport:{total:u,viewHeight:s}}}renderSplitView(e,t,i,n,o,s){let r,a=O(Math.floor(o*y.leftColRatio),y.leftColMin,y.leftColMax),l=Math.max(20,o-a-y.dividerWidth),u=`${n.tab}_${n.optionIndex}_${n.listScrollOffset}_${this.model.revision}_${a}`;this.leftColCache&&this.leftColCache.key===u?r=this.leftColCache.lines:(r=[],this.pushListItems(r,t,i,n,a,!1,s),this.leftColCache={key:u,lines:r});let c=n.menuItems[n.optionIndex],p="option"===c?.type&&void 0!==c.optionIndex?i.optionNotes.get(c.optionIndex):void 0,d=void 0===c?{lines:[],viewport:{total:0,viewHeight:tt(s)}}:this.buildPreviewBox(n.tab,c,i.customText,p,l,tt(s),n.previewScrollOffset),m=Math.max(r.length,d.lines.length);for(let t=0;t<m;t++){let i=r[t]??"",n=d.lines[t]??"",o=this.theme.fg("dim",y.dividerChar);e.push(`${W(i,a)}${o}${P(n,l)}`)}return d.viewport}pushListItems(e,t,i,n,o,s,a){n.listScrollOffset>0&&e.push(this.theme.fg("dim",r.view.listTopMore(n.listScrollOffset)));let l,u=n.menuItems.slice(n.listScrollOffset,n.listScrollOffset+y.visibleOptionCount);for(let[r,c]of u.entries()){if(!c)continue;let u=n.listScrollOffset+r,p=u===n.optionIndex,d=n.menuItems[u-1];if(d&&"option"===d.type&&"option"!==c.type&&e.push(""),e.push(...Ve(this.theme,c,p,t,i,o)),p&&s&&("option"!==c.type||c.description||c.preview||i.optionNotes.has(c.optionIndex??-1))){e.push("");let t="option"===c.type&&void 0!==c.optionIndex?i.optionNotes.get(c.optionIndex):void 0,s=this.buildPreviewBox(n.tab,c,i.customText,t,Math.max(10,o-2),pe(a),n.previewScrollOffset);l=s.viewport;for(let t of s.lines)e.push(t);e.push("")}}let c=n.menuItems.length-(n.listScrollOffset+y.visibleOptionCount);return c>0&&e.push(this.theme.fg("dim",r.view.listBottomMore(c))),l}};function xn(e){return[r.help.switchQuestion,...e.getVisibleQuestionIndices().length>1?[r.help.jumpQuestion]:[],r.help.scrollSummary,r.help.confirmSubmit,r.help.cancel]}function me(e){return O(e-10,4,y.summaryPageSize)}var ne=class{constructor(e,t){this.theme=e,this.model=t}theme;model;cache;clear(){this.cache=void 0}get contentLineCount(){return this.cache?.lines.length??0}render(e,t,i,n){let o=[this.theme.fg("accent",this.theme.bold(r.summary.title)),""],s=n-2;(!this.cache||this.cache.width!==s||this.cache.revision!==this.model.revision)&&(this.cache={width:s,revision:this.model.revision,lines:wn(this.model,this.theme,s)});let a=this.cache.lines,l=a.length,u=$(e,l,t);u>0&&o.push(this.theme.fg("dim",r.summary.topMore(u)));for(let e of Y(a,u,t))o.push(e);let c=l-(u+t);return c>0&&o.push(this.theme.fg("dim",r.summary.bottomMore(c))),o.push(""),A(o,this.model.areAllQuestionsAnswered()?this.theme.fg("success",this.theme.bold(r.summary.allDonePrompt)):this.theme.fg("warning",r.summary.pendingWarning),s),J(o,this.theme,i),o.push(""),Z(o,xn(this.model),this.theme,n),_(o,this.theme,n),o}};function wn(e,t,i){let n=[];for(let[o,s]of e.getVisibleQuestionIndices().entries()){let a=e.getQuestion(s);if(!a)continue;let l=e.isQuestionAnswered(s),u=e.getState(s);A(n,`${l?t.fg("success",r.summary.statusDone):t.fg("warning",r.summary.statusPending)} ${t.bold(r.summary.questionPrefix(o+1,a.title))}`,i," ");let c=[];if(a.multiSelect)for(let t of e.getSelectedIndices(s)){let e=a.options[t];if(!e)continue;let i=u.optionNotes.get(t);c.push(i?`${e.label} ${r.summary.optionNoteBadge}`:e.label)}else{let t=e.getSelectedIndex(s),i=void 0===t?void 0:a.options[t];if(i&&void 0!==t){let e=u.optionNotes.get(t);c.push(e?`${i.label} ${r.summary.optionNoteBadge}`:i.label)}}let p=c.length?t.fg("accent",c.join(r.common.optionSeparator)):t.fg("dim",r.fallbacks.unselectedOption);A(n,`${t.fg("muted",r.summary.selectedLabel)} ${p}`,i," ");for(let[o,l]of u.optionNotes.entries()){let u=a.options[o];u&&l?.trim()&&e.isOptionVisible(s,o)&&A(n,`${t.fg("muted",r.summary.optionNotePrefix(u.label))} ${t.fg("accent",l)}`,i," ")}u.customText&&A(n,`${t.fg("muted",r.summary.customNoteLabel)} ${t.fg("accent",u.customText)}`,i," "),n.push("")}return n}var oe=class{_focused=!1;get focused(){return this._focused}set focused(e){this._focused!==e&&(this._focused=e,this.editor.focused=this.inputMode&&e,this.touch(),this.tabCache=void 0,this.questionView.clearColumnCache())}tui;theme;model;done;currentTab=0;cursorByTab=new Map;currentOptionIndex=0;listScrollOffset=0;previewScrollOffset=0;summaryScrollOffset=0;inputMode=!1;editorEscArmed=!1;statusMessage=null;statusTimer=null;isFinished=!1;disposed=!1;abortBinding;cachedWidth;cachedLayoutWidth;cachedHeight;cachedLines;tabCache;menuCache;previewViewportObservation;editTarget;editor;expansion;expansionTicket=0;expansionAbort;expansionPending=!1;questionView;summaryView;constructor(e,t,i,n,o){this.tui=e,this.theme=t,this.model=i,this.done=n,this.expansion=o,this.questionView=new te(t,i),this.summaryView=new ne(t,i);let s={borderColor:e=>this.theme.fg("accent",e),selectList:Sn()};this.editor=new yn(this.tui,s),this.editor.focused=!1,this.editor.onSubmit=e=>{let t=this.editTarget;if(t){if("option"===t.type){let i=this.model.getQuestion(this.currentTab),n=t.optionIndex,o=i?F(i,n):r.fallbacks.autoOptionLabel(n+1),s=this.model.setOptionNote(this.currentTab,n,e);this.setStatus("cleared"===s?r.status.optionNoteCleared(o):"savedAtLimit"===s&&i?r.status.optionNoteSavedAtLimit(i.maxSelect):"savedUnselected"===s?r.status.optionNoteSavedUnselected(o):r.status.optionNoteSaved(o))}else{let t=this.model.setQuestionNote(this.currentTab,e);this.setStatus("saved"===t?r.status.questionNoteSaved:r.status.noteCleared)}this.touchDerived(),this.closeEditor()}else this.closeEditor()}}bindAbortSignal(e){if(!e||this.abortBinding||this.disposed)return;if(e.aborted)return void queueMicrotask(()=>this.finish(!0));let t=()=>this.finish(!0);e.addEventListener("abort",t,{once:!0}),this.abortBinding={signal:e,onAbort:t}}dispose(){this.disposed||(this.disposed=!0,this.expansionTicket++,this.expansionAbort?.abort(),this.expansionAbort=void 0,this.expansionPending=!1,this.clearStatusTimer(),this.abortBinding&&(this.abortBinding.signal.removeEventListener("abort",this.abortBinding.onAbort),this.abortBinding=void 0),this.clearDerivedCaches(),this.previewViewportObservation=void 0,this.clearFrameCaches())}clearFrameCaches(){this.cachedWidth=void 0,this.cachedLayoutWidth=void 0,this.cachedHeight=void 0,this.cachedLines=void 0}clearDerivedCaches(){this.questionView.clear(),this.summaryView.clear(),this.tabCache=void 0,this.menuCache=void 0}touch(){this.clearFrameCaches(),this.tui.requestRender()}touchDerived(){this.clearDerivedCaches(),this.touch()}invalidate(){this.touchDerived(),this.editor.invalidate()}clearStatusTimer(){this.statusTimer&&(clearTimeout(this.statusTimer),this.statusTimer=null)}setStatus(e){this.statusMessage=e,this.clearStatusTimer(),this.statusTimer=setTimeout(()=>{this.statusMessage=null,this.statusTimer=null,this.touch()},y.statusDurationMs),this.touch()}get statusLine(){return this.statusMessage}finish(e){this.isFinished||(this.isFinished=!0,this.dispose(),this.done({formTitle:this.model.formTitle,formDescription:this.model.formDescription,questions:this.model.questions,answers:e?[]:this.model.compileAnswers(),cancelled:e}))}get tabOrder(){return[...this.model.getVisibleQuestionIndices(),this.model.questionCount]}get isSubmitTab(){return this.currentTab===this.model.questionCount}get terminalRows(){let e=this.tui.terminal?.rows;return"number"==typeof e&&e>0?e:24}get summaryViewportHeight(){return me(this.terminalRows)}getMenuItems(){let e=this.menuCache;if(e&&e.tab===this.currentTab&&e.revision===this.model.revision)return e.items;let t=this.model.getMenuItems(this.currentTab);return this.menuCache={tab:this.currentTab,revision:this.model.revision,items:t},t}currentMenuItem(){return this.getMenuItems()[this.currentOptionIndex]}switchTab(e){e!==this.currentTab&&(this.currentTab=e,this.previewScrollOffset=0,this.summaryScrollOffset=0,this.listScrollOffset=0,this.menuCache=void 0,this.isSubmitTab?this.currentOptionIndex=0:(this.currentOptionIndex=this.cursorByTab.get(this.currentTab)??this.model.getSelectedIndex(this.currentTab)??0,this.adjustScrollForCurrentOption()),this.touch())}switchRelativeTab(e){let t=this.tabOrder,i=t.indexOf(this.currentTab);this.switchTab(-1!==i?t[(i+e+t.length)%t.length]??this.currentTab:t[0]??this.model.questionCount)}adjustScrollForCurrentOption(){let e=this.getMenuItems().length;0!==e&&(this.currentOptionIndex=O(this.currentOptionIndex,0,e-1),this.currentOptionIndex<this.listScrollOffset?this.listScrollOffset=this.currentOptionIndex:this.currentOptionIndex>=this.listScrollOffset+y.visibleOptionCount&&(this.listScrollOffset=this.currentOptionIndex-y.visibleOptionCount+1))}moveCursor(e){let t=this.getMenuItems().length;if(0===t)return;let i=O("number"==typeof e?e:this.currentOptionIndex+e.delta,0,t-1);i!==this.currentOptionIndex&&(this.currentOptionIndex=i,this.cursorByTab.set(this.currentTab,i),this.previewScrollOffset=0,this.adjustScrollForCurrentOption(),this.touch())}getEditTargetForCurrentSelection(){let e=this.currentMenuItem();return"option"===e?.type&&void 0!==e.optionIndex?{type:"option",optionIndex:e.optionIndex}:{type:"question"}}openCustomEditor(e){let t=this.model.getQuestion(this.currentTab);if(!t||!t.allowCustom)return;let i=this.model.getState(this.currentTab),n=e??this.getEditTargetForCurrentSelection();this.editTarget=n,this.inputMode=!0,this.editorEscArmed=!1;let o="option"===n.type?i.optionNotes.get(n.optionIndex)??"":i.customText??"";this.editor.setText(o),this.editor.focused=this._focused,this.touch()}closeEditor(){this.inputMode=!1,this.editorEscArmed=!1,this.editTarget=void 0,this.editor.focused=!1,this.editor.setText(""),this.touch()}confirmAndAdvance(e,t){if("option"===e.type&&void 0!==e.optionIndex&&this.model.commitOption(this.currentTab,e.optionIndex),this.model.isQuestionAnswered(this.currentTab)){this.expandAfterConfirm(this.currentTab);let e=this.tabOrder,t=e.indexOf(this.currentTab);return void this.switchTab(-1===t?this.model.questionCount:e[t+1]??this.model.questionCount)}this.setStatus(t.multiSelect?r.status.minSelectRequired(t.minSelect):r.status.pleaseAnswerBeforeSubmit)}expandAfterConfirm(e){let t=this.expansion;if(!t)return;let i=this.model.answerSignature(e);if(void 0===i||this.model.getExpansions().find(t=>t.questionIndex===e)?.signature===i)return;if(this.model.retractFrom(e)>0){this.setStatus(r.status.expansionRetracted);for(let t of[...this.cursorByTab.keys()])t>e&&this.cursorByTab.delete(t);this.trimTabs(),this.touchDerived()}let n=this.model.expansionMaxQuestions-this.model.questionCount;if(n<=0)return;let o=++this.expansionTicket,s=new AbortController;this.expansionAbort?.abort(),this.expansionAbort=s,this.expansionPending=!0,this.touch();let a={formTitle:this.model.formTitle,formDescription:this.model.formDescription,guidance:t.guidance,insert:this.model.expansionInsertLabel,maxAdditionalQuestions:n,questions:this.model.questions,answers:this.model.compileAnswers()};t.run(a,s.signal).then(t=>this.applyExpansion(o,e,i,t),e=>this.reportExpansionFailure(o,e))}applyExpansion(e,t,i,n){if(e!==this.expansionTicket||this.isFinished||this.disposed)return;this.expansionPending=!1,this.expansionAbort=void 0;let o,s=this.isSubmitTab,a=this.currentTab,l=s?void 0:this.model.getQuestion(a)?.id;try{o=this.model.pushExpansion({questionIndex:t,signature:i,payload:n})}catch(e){return void this.setStatus(r.status.expansionFailed(this.describeError(e)))}if(o.addedQuestions>0)for(let e of[...this.cursorByTab.keys()])e>=o.insertAt&&this.cursorByTab.delete(e);if(s)this.currentTab=o.addedQuestions>0?o.insertAt:this.model.questionCount;else if(void 0!==l){let e=a===o.insertAt?o.insertAt:this.model.questions.findIndex(e=>e.id===l);e>=0&&e!==this.currentTab&&this.switchTab(e)}this.trimTabs(),this.touchDerived();let u=o.addedOptions.reduce((e,t)=>e+t.count,0);this.setStatus(0===o.addedQuestions&&0===u?r.status.expansionStopped:r.status.expansionAdded(o.addedQuestions,u))}reportExpansionFailure(e,t){e!==this.expansionTicket||this.isFinished||this.disposed||(this.expansionPending=!1,this.expansionAbort=void 0,this.setStatus(r.status.expansionFailed(this.describeError(t))))}describeError(e){return e instanceof Error?e.message:String(e)}trimTabs(){let e=this.model.questionCount;this.currentTab>e&&(this.currentTab=e);for(let t of[...this.cursorByTab.keys()])t>e&&this.cursorByTab.delete(t);let t=this.getMenuItems().length;t>0&&this.currentOptionIndex>=t&&(this.currentOptionIndex=t-1)}handleInput(e){if(this.isFinished||this.disposed)return;let t=w(e,S.escape)||w(e,S.ctrl("c"));if(this.inputMode)return t?""===this.editor.getText()||this.editorEscArmed?void this.closeEditor():(this.editorEscArmed=!0,void this.setStatus(r.status.editorDiscardConfirm)):(this.editorEscArmed&&(this.editorEscArmed=!1,this.statusMessage=null),this.editor.handleInput(e),void this.touch());if(t)this.finish(!0);else if(!this.expansionPending){if(e=ae(e),/^[1-9]$/.test(e)){let t=parseInt(e,10)-1,i=this.tabOrder[t];if(void 0!==i&&i<this.model.questionCount)return void this.switchTab(i)}if(w(e,S.tab)||w(e,S.right)||w(e,"l"))return void this.switchRelativeTab(1);if(w(e,S.shift("tab"))||w(e,S.left)||w(e,"h"))return void this.switchRelativeTab(-1);this.isSubmitTab?this.handleSummaryInput(e):this.handleQuestionInput(e)}}handleQuestionInput(e){let t=this.model.getQuestion(this.currentTab);if(!t||this.handleNoteShortcut(t,e)||this.handlePreviewScroll(e)||this.handleCursorNavigation(e)||this.handleSelectAllShortcut(t,e))return;let i=this.currentMenuItem();if(i){if(w(e,S.ctrl("s")))return void this.confirmAndAdvance(i,t);if(w(e,S.space))return void this.activateMenuItem(i,t);w(e,S.enter)&&("custom_note"===i.type?this.openCustomEditor({type:"question"}):this.confirmAndAdvance(i,t))}}handleNoteShortcut(e,t){if(!e.allowCustom)return!1;if(w(t,S.shift("n")))return this.openCustomEditor({type:"question"}),!0;if(w(t,"n")||w(t,"e"))return this.openCustomEditor(),!0;if(w(t,"x")||w(t,S.delete)){let t=this.currentMenuItem();if("option"===t?.type&&void 0!==t.optionIndex){let i=t.optionIndex;if(this.model.clearOptionNote(this.currentTab,i))return this.setStatus(r.status.optionNoteCleared(F(e,i))),!0}if(this.model.clearQuestionNote(this.currentTab))return this.setStatus(r.status.noteCleared),!0}return!1}handlePreviewScroll(e){let t=0;if(w(e,S.leftbracket)||w(e,S.alt("up"))?t=-y.previewScrollStep:(w(e,S.rightbracket)||w(e,S.alt("down")))&&(t=y.previewScrollStep),0===t)return!1;let i=this.previewViewportObservation,n=i?.viewHeight??pe(this.terminalRows);return this.previewScrollOffset=$(this.previewScrollOffset+t,i?.total??0,n),this.touch(),!0}handleCursorNavigation(e){return w(e,S.up)||w(e,"k")?(this.moveCursor({delta:-1}),!0):w(e,S.down)||w(e,"j")?(this.moveCursor({delta:1}),!0):w(e,S.home)?(this.moveCursor(0),!0):!!w(e,S.end)&&(this.moveCursor(Number.MAX_SAFE_INTEGER),!0)}handleSelectAllShortcut(e,t){if(!e.multiSelect||!w(t,"a"))return!1;let i=this.model.selectAllOrClear(this.currentTab),n=e.options.filter((e,t)=>this.model.isOptionVisible(this.currentTab,t)).length;return"filled"===i&&e.maxSelect<n?this.setStatus(r.status.selectedUpToLimit(e.maxSelect)):this.touch(),!0}activateMenuItem(e,t){"option"!==e.type||void 0===e.optionIndex?"custom_note"!==e.type?this.confirmAndAdvance(e,t):this.openCustomEditor({type:"question"}):"limit"===this.model.toggleOption(this.currentTab,e.optionIndex)?this.setStatus(r.status.maxSelectExceeded(t.maxSelect)):this.touch()}handleSummaryInput(e){if(w(e,S.enter)||w(e,S.ctrl("s"))){if(this.model.areAllQuestionsAnswered())this.finish(!1);else{let e=this.model.getVisibleQuestionIndices().find(e=>!this.model.isQuestionAnswered(e));if(void 0!==e){this.switchTab(e);let t=this.model.getQuestion(e);t&&this.setStatus(t.multiSelect?r.status.minSelectRequired(t.minSelect):r.status.pleaseAnswerBeforeSubmit)}}return}if(w(e,S.home))return this.summaryScrollOffset=0,void this.touch();if(w(e,S.end))return this.summaryScrollOffset=Number.MAX_SAFE_INTEGER,void this.touch();let t=this.summaryScrollStep(e);if(0===t&&w(e,S.space)&&(t=y.summaryScrollStep),0===t)return;let i=this.summaryView.contentLineCount,n=this.summaryViewportHeight,o=$(this.summaryScrollOffset,i,n);this.summaryScrollOffset=$(o+t,i,n),this.touch()}summaryScrollStep(e){return w(e,S.leftbracket)||w(e,S.alt("up"))?-y.summaryScrollStep:w(e,S.rightbracket)||w(e,S.alt("down"))?y.summaryScrollStep:w(e,S.up)||w(e,"k")?-1:w(e,S.down)||w(e,"j")?1:0}render(e){let t=Math.max(20,e),i=this.terminalRows;if(this.cachedLines&&this.cachedWidth===e&&this.cachedLayoutWidth===t&&this.cachedHeight===i)return this.cachedLines;let n=[];_(n,this.theme,t);let o=`${this.currentTab}_${this.expansionPending?"p":"-"}_${this.model.revision}_${t}`;if((!this.tabCache||this.tabCache.key!==o)&&(this.tabCache={key:o,lines:Ue(this.theme,this.model,this.currentTab,t,this.expansionPending)}),n.push(...this.tabCache.lines),this.expansionPending)je(n,this.theme,t);else if(this.isSubmitTab)n.push(...this.summaryView.render(this.summaryScrollOffset,me(i),this.statusLine,t));else if(this.inputMode)n.push(...ze(this.theme,this.model,this.currentTab,this.editTarget,this.editor,t));else{let e=this.questionView.render({tab:this.currentTab,optionIndex:this.currentOptionIndex,listScrollOffset:this.listScrollOffset,previewScrollOffset:this.previewScrollOffset,statusMessage:this.statusLine,menuItems:this.getMenuItems(),expandable:this.model.canExpandOnConfirm(this.currentTab,void 0!==this.expansion)},t,i);n.push(...e.lines),e.previewViewport&&(this.previewViewportObservation=e.previewViewport)}return this.cachedWidth=e,this.cachedLayoutWidth=t,this.cachedHeight=i,this.cachedLines=n.map(t=>P(t,e)),this.cachedLines}};function Q(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Tn(e){let t=L(e.raw);return Q(t)?t:(delete e.raw,e)}function I(e,t){for(let i of t){let t=e[i];if("string"==typeof t)return t}}function B(e,t){if("boolean"==typeof e)return e;if(1===e)return!0;if(0===e)return!1;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}return t}function he(e){if("number"==typeof e&&Number.isFinite(e))return Math.floor(e);if("string"==typeof e){let t=parseInt(e.trim(),10);return Number.isFinite(t)?t:void 0}}function nt(e){let t=he(e);return void 0===t?void 0:Math.max(0,t)}function ot(e){let t=he(e);return void 0!==t&&t>=1?t:void 0}function vn(e){if(!Q(e))return;let t=g(I(e,["questionId","question"]));if(!t)return;let i={questionId:t},n=g(I(e,["option","optionLabel","label"]));return n&&(i.option=n),void 0!==e.answered&&(i.answered=B(e.answered,!0)),i}function it(e){let t=L(e),i=(Array.isArray(t)?t:[t]).map(vn).filter(e=>void 0!==e);return Array.isArray(t)?i.length>0?i:void 0:i[0]}function be(e){let t=L(e);return Array.isArray(t)?t.slice(0,M).map((e,t)=>{if("string"==typeof e)return{label:e.trim()||r.fallbacks.autoOptionLabel(t+1)};if(!Q(e))return{label:r.fallbacks.autoOptionLabel(t+1)};let i=e;return{label:g(I(i,["label","name","title","text","value","choice"]))??r.fallbacks.autoOptionLabel(t+1),description:g(I(i,["description","desc","reason","rationale","deduction"])),preview:g(I(i,["preview","draft","scene","content"])),customPlaceholder:g(I(i,["customPlaceholder","placeholder"])),showIf:it(i.showIf??i.when??i.visibleIf)}}):[]}function Cn(e){return"object"==typeof e&&null!==e&&!("questions"in e)&&("options"in e||"choices"in e||"items"in e||"question"in e||"prompt"in e)}function st(e,t){if("string"==typeof e)return{title:e,options:ie([])};if(!Q(e))return{title:r.fallbacks.autoQuestionTitle(t+1),options:ie([])};let i=e;return{id:I(i,["id"]),title:g(I(i,["title","question","prompt","query","heading"]))??r.fallbacks.autoQuestionTitle(t+1),tabLabel:g(I(i,["tabLabel","tabTitle","tab"])),description:g(I(i,["description","desc","rationale"])),multiSelect:B(i.multiSelect,!1),minSelect:nt(i.minSelect),maxSelect:ot(i.maxSelect),allowEmpty:B(i.allowEmpty,!1),options:ie(be(i.options??i.choices??i.items)),allowCustom:B(i.allowCustom,!0),customPlaceholder:I(i,["customPlaceholder","placeholder"]),showIf:it(i.showIf??i.when??i.visibleIf)}}function In(e){if(void 0===e)return;let t=L(e),i=Array.isArray(t)?t:Cn(t)?[t]:[];return 0!==i.length?i.slice(0,k).map((e,t)=>st(e,t)):void 0}function ie(e){return e.length>0?e:[{label:r.fallbacks.defaultOptionLabel}]}function An(e){if("string"==typeof e){let t=e.trim().toLowerCase();if("follow"===t||"tail"===t)return t;let i=g(e);return i?{after:i}:void 0}let t=L(e);if(!Q(t))return;let i=g(I(t,["after","questionId","anchor","id"]));return i?{after:i}:void 0}function Nn(e){let t=L(e);if(!Q(t))return;let i={},n=he(t.maxQuestions);void 0!==n&&(i.maxQuestions=Math.min(Math.max(1,n),k));let o=g(I(t,["guidance","instructions","hint"]));o&&(i.guidance=o);let s=An(t.insert??t.position);return void 0!==s&&(i.insert=s),i}function On(e,t,i,n){return"string"==typeof e?e:"string"==typeof t?t:n?i:void 0}function K(e){let t=e&&"object"==typeof e?e:L(e);if(!Q(t))return{formTitle:r.fallbacks.defaultFormTitle};let i=Tn({...t}),n=g(I(i,["title","taskTitle"])),o=g(I(i,["formTitle"]))??n??r.fallbacks.defaultFormTitle,s=In(i.questions??i.form??i.survey),a=void 0!==i.options||void 0!==i.choices||void 0!==i.items,l=a?ie(be(i.options??i.choices??i.items)):void 0,u=On(i.question,i.prompt,n,a),c=I(i,["description"]),p=void 0===i.multiSelect?void 0:B(i.multiSelect,!1),d=void 0===i.minSelect?void 0:nt(i.minSelect),m=void 0===i.maxSelect?void 0:ot(i.maxSelect),h=void 0===i.allowEmpty?void 0:B(i.allowEmpty,!1),f=void 0===i.allowCustom?void 0:B(i.allowCustom,!0),x=I(i,["customPlaceholder"]);return{formTitle:o,description:c,expansion:void 0===i.expansion?void 0:Nn(i.expansion),questions:s,question:u,multiSelect:p,minSelect:d,maxSelect:m,allowEmpty:h,options:l,allowCustom:f,customPlaceholder:x}}function ge(e,t){if(!Q(e))return{questions:[],optionAdditions:[]};let i=new Set(t.questionIds),n=[];for(let t of fe(L(e.questions))){if(!Q(t)||!g(I(t,["title","question","prompt","query","heading"]))||0===fe(L(t.options??t.choices??t.items)).length)continue;let e=st(t,n.length),o=new Set;e.options=e.options.filter(e=>!o.has(e.label)&&(o.add(e.label),!0)),void 0!==e.id&&i.has(e.id)&&(e.id=void 0),void 0!==e.id&&i.add(e.id),n.push(e)}let o=[];for(let i of fe(L(e.options??e.optionAdditions))){if(!Q(i))continue;let e=g(I(i,["questionId","question","id"]));if(!e)continue;let n=t.optionLabels.get(e);if(!n)continue;let s=new Set(n),r=be(i.options??i.choices??i.items).filter(e=>!s.has(e.label)&&(s.add(e.label),!0));r.length>0&&o.push({questionId:e,options:r})}return{questions:n,optionAdditions:o}}function fe(e){return Array.isArray(e)?e:[]}function xe(e){let t={formTitle:e.formTitle,formDescription:e.formDescription,guidance:e.guidance,insert:e.insert,maxAdditionalQuestions:e.maxAdditionalQuestions,questions:e.questions.map(e=>({id:e.id,title:e.title,description:e.description,multiSelect:e.multiSelect,options:e.options.map(e=>({label:e.label,description:e.description,conditional:e.showIf.length>0})),conditional:e.showIf.length>0})),answers:e.answers.map(e=>({questionId:e.questionId,selected:(e.multiSelect?e.selectedOptions??[]:e.selectedOption?[e.selectedOption]:[]).map(e=>e.label),note:e.customText}))};return`${r.expansion.userPreamble}\n${JSON.stringify(t)}`}function we(e,t){let i,n=e.indexOf("{"),o=e.lastIndexOf("}");if(n<0||o<=n)throw new Error(r.expansion.errors.invalidReply);try{i=JSON.parse(e.slice(n,o+1))}catch{throw new Error(r.expansion.errors.invalidReply)}return ge(i,t)}function Se(e){return{questionIds:e.map(e=>e.id),optionLabels:new Map(e.map(e=>[e.id,e.options.map(e=>e.label)]))}}import{Type as f}from"typebox";var ye=f.Object({questionId:f.String({description:r.schema.conditionQuestionId}),option:f.Optional(f.String({description:r.schema.conditionOption})),answered:f.Optional(f.Boolean({description:r.schema.conditionAnswered}))});function rt(e){return f.Optional(f.Union([ye,f.Array(ye)],{description:e}))}var Te=f.Object({label:f.String({description:r.schema.optionLabel}),description:f.Optional(f.String({description:r.schema.optionDesc})),preview:f.Optional(f.String({description:r.schema.optionPreview})),customPlaceholder:f.Optional(f.String({description:r.schema.optionCustomPlaceholder})),showIf:rt(r.schema.optionShowIf)}),at=f.Object({id:f.Optional(f.String({description:r.schema.questionId})),title:f.String({description:r.schema.questionTitle}),tabLabel:f.Optional(f.String({description:r.schema.questionTabLabel})),description:f.Optional(f.String({description:r.schema.questionDesc})),multiSelect:f.Optional(f.Boolean({description:r.schema.questionMultiSelect})),minSelect:f.Optional(f.Integer({description:r.schema.questionMinSelect,minimum:0})),maxSelect:f.Optional(f.Integer({description:r.schema.questionMaxSelect,minimum:1})),allowEmpty:f.Optional(f.Boolean({description:r.schema.questionAllowEmpty})),options:f.Array(Te,{description:r.schema.questionOptions,minItems:1,maxItems:M}),allowCustom:f.Optional(f.Boolean({description:r.schema.questionAllowCustom})),customPlaceholder:f.Optional(f.String({description:r.schema.questionCustomPlaceholder})),showIf:rt(r.schema.questionShowIf)}),kn=f.Union([f.Literal("follow"),f.Literal("tail"),f.Object({after:f.String({description:r.schema.expansionInsertAfter})})],{description:r.schema.expansionInsert}),lt=f.Object({maxQuestions:f.Optional(f.Integer({description:r.schema.expansionMaxQuestions,minimum:1,maximum:k})),guidance:f.Optional(f.String({description:r.schema.expansionGuidance})),insert:f.Optional(kn)}),ve=f.Object({formTitle:f.String({description:r.schema.formTitle}),description:f.Optional(f.String({description:r.schema.formDesc})),expansion:f.Optional(lt),questions:f.Optional(f.Array(at,{description:r.schema.formQuestions,minItems:1,maxItems:k})),question:f.Optional(f.String({description:r.schema.formSingleQuestion})),multiSelect:f.Optional(f.Boolean({description:`${r.schema.flatPrefix}${r.schema.questionMultiSelect}`})),minSelect:f.Optional(f.Integer({description:`${r.schema.flatPrefix}${r.schema.questionMinSelect}`,minimum:0})),maxSelect:f.Optional(f.Integer({description:`${r.schema.flatPrefix}${r.schema.questionMaxSelect}`,minimum:1})),allowEmpty:f.Optional(f.Boolean({description:`${r.schema.flatPrefix}${r.schema.questionAllowEmpty}`})),options:f.Optional(f.Array(Te,{description:r.schema.flatQuestionOptions,minItems:1,maxItems:M})),allowCustom:f.Optional(f.Boolean({description:`${r.schema.flatPrefix}${r.schema.questionAllowCustom}`})),customPlaceholder:f.Optional(f.String({description:`${r.schema.flatPrefix}${r.schema.questionCustomPlaceholder}`}))});import{Text as mt}from"@earendil-works/pi-tui";function En(e){return e instanceof Error?e.message:String(e)}function ut(e={}){return{formTitle:e.formTitle??r.fallbacks.defaultFormTitle,formDescription:e.formDescription,questions:e.questions??[]}}function Ce(e={}){let{formTitle:t,formDescription:i,questions:n}=ut(e);return{content:[{type:"text",text:r.markdown.envelopeCancelled}],details:{formTitle:t,formDescription:i,questions:n,answers:[],cancelled:!0}}}function j(e,t,i,n={}){let{formTitle:o,formDescription:s,questions:a}=ut(n);return{content:[{type:"text",text:r.markdown.envelopeError(e,t)}],details:{formTitle:o,formDescription:s,questions:a,answers:[],cancelled:!1,error:i},isError:!0}}function Ie(e,t={}){let i=En(e);return j(r.markdown.errorReasons.runtimeError(i),r.markdown.errorGuidances.runtimeError,r.status.errorExecutionFailed(i),t)}function ct(e,t){return{content:[{type:"text",text:e.formatAnswers(t)}],details:{formTitle:e.formTitle,formDescription:e.formDescription,questions:e.questions,answers:t,cancelled:!1}}}function dt(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`ask_author 结果详情应为普通对象,实际收到 ${JSON.stringify(e)}`);if(!("cancelled"in e&&"answers"in e&&"questions"in e&&"formTitle"in e))throw new Error("ask_author 结果详情缺少 cancelled/answers/questions/formTitle 字段");if("boolean"!=typeof e.cancelled)throw new Error("ask_author 结果详情的 cancelled 字段应为布尔值");if(!Array.isArray(e.answers)||!Array.isArray(e.questions))throw new Error("ask_author 结果详情的 answers/questions 字段应为数组");if("string"!=typeof e.formTitle)throw new Error("ask_author 结果详情的 formTitle 字段应为字符串");return e}function pt(e){let t=e.customText?r.card.questionNoteTag(e.customText):"",i=(e,t)=>t?r.card.optionWithNote(e,t):e;return e.multiSelect?((e.selectedOptions??[]).map(e=>i(e.label,e.customText)).join(r.common.optionSeparator)||r.fallbacks.unselectedOption)+t:e.selectedOption?i(e.selectedOption.label,e.selectedOption.customText)+t:e.customText||r.fallbacks.unselectedOption}function qn(e,t){if(t.cachedArgs===e&&t.cachedCard)return t.cachedCard;let i=K(e),n=i.questions??[],o=i.options??[],s=n.length>0?n.length:o.length>0?1:0,a=n.length>0?n.reduce((e,t)=>e+t.options.length,0):o.length,l={title:i.formTitle,countLabel:s>1?r.card.callQuestionAndOptionCount(s,a):r.card.callOptionCountOnly(a)};return t.cachedArgs=e,t.cachedCard=l,l}function z(e,t){let i=t instanceof mt?t:new mt("",0,0);return i.setText(e),i}function ft(e,t,i){let n=qn(e,i.state);return z(`${t.fg("accent",r.tool.label)} ${t.bold(n.title)} ${t.fg("muted",`(${n.countLabel})`)}`,i.lastComponent)}function ht(e,t,i,n){let o=dt(e.details),{expanded:s}=t;if(o.error){let e=`${i.fg("error",i.bold(r.card.resultErrorShort))} ${i.fg("muted",`${r.common.bulletPrefix}${o.error}`)}`;return z(s?`${e}\n${r.card.errorBullet(i.fg("error",o.error))}`:e,n.lastComponent)}if(o.cancelled)return z(i.fg("warning",r.card.resultCancelled),n.lastComponent);let a=`${i.fg("success",i.bold(r.card.resultCompleted))} ${i.fg("muted",`${r.common.bulletPrefix}${r.card.resultCount(o.answers.length)}`)}`;return z(s?[a,...o.answers.map(e=>r.card.optionBullet(i.bold(e.questionTitle),i.fg("accent",pt(e))))].join("\n"):a,n.lastComponent)}function Ln(e,t){if(!e)return t;let i={input:e.input+t.input,output:e.output+t.output,cacheRead:e.cacheRead+t.cacheRead,cacheWrite:e.cacheWrite+t.cacheWrite,totalTokens:e.totalTokens+t.totalTokens,cost:{input:e.cost.input+t.cost.input,output:e.cost.output+t.cost.output,cacheRead:e.cost.cacheRead+t.cost.cacheRead,cacheWrite:e.cost.cacheWrite+t.cost.cacheWrite,total:e.cost.total+t.cost.total}};return void 0!==e.cacheWrite1h&&void 0!==t.cacheWrite1h&&(i.cacheWrite1h=e.cacheWrite1h+t.cacheWrite1h),void 0!==e.reasoning&&void 0!==t.reasoning&&(i.reasoning=e.reasoning+t.reasoning),i}function Pn(e,t){let i=e.model;if(i)return async(n,o)=>{let s=await e.modelRegistry.complete(i,{systemPrompt:r.expansion.systemPrompt,messages:[{role:"user",content:[{type:"text",text:xe(n)}],timestamp:Date.now()}]},{signal:o});if(s.usage&&t(s.usage),"aborted"===s.stopReason)throw new Error(r.expansion.errors.aborted);if("error"===s.stopReason)throw new Error(s.errorMessage??r.expansion.errors.providerFailed);return we(s.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),Se(n.questions))}}function Qn(e){e.registerTool({name:r.tool.name,label:r.tool.label,description:r.tool.description,promptSnippet:r.tool.promptSnippet,promptGuidelines:[...r.tool.promptGuidelines],parameters:ve,executionMode:"sequential",exposure:"model-only",annotations:{readOnlyHint:!0,openWorldHint:!1},prepareArguments:K,async execute(e,t,i,n,o){let s,a=g(t?.formTitle)??r.fallbacks.defaultFormTitle;if(i?.aborted)return Ce({formTitle:a});if("tui"!==o.mode)return j(r.markdown.errorReasons.nonTui,r.markdown.errorGuidances.nonTui,r.status.errorNonTui,{formTitle:a});try{s=new G(t)}catch(e){return e instanceof R?j(r.markdown.errorReasons.invalidCondition(e.message),r.markdown.errorGuidances.invalidCondition,r.status.errorInvalidCondition(e.message),{formTitle:a}):Ie(e,{formTitle:a})}if(0===s.questions.length)return j(r.markdown.errorReasons.noQuestions,r.markdown.errorGuidances.noQuestions,r.status.errorNoQuestions,{questions:[],formTitle:s.formTitle,formDescription:s.formDescription});let l,u=e=>l?{...e,usage:l}:e,c=t.expansion?Pn(o,e=>{l=Ln(l,e)}):void 0;if(t.expansion&&!c)return j(r.markdown.errorReasons.expansionUnavailable,r.markdown.errorGuidances.expansionUnavailable,r.status.expansionFailed(r.expansion.errors.noModel),{questions:s.questions,formTitle:s.formTitle,formDescription:s.formDescription});let p,d=c?{run:c,guidance:t.expansion?.guidance}:void 0;try{let e=await o.ui.custom((e,t,n,o)=>(p=new oe(e,t,s,o,d),p.bindAbortSignal(i),p));return u(!e||e.cancelled?Ce({questions:e?.questions??s.questions,formTitle:e?.formTitle??s.formTitle,formDescription:e?.formDescription??s.formDescription}):ct(s,e.answers))}catch(e){return u(Ie(e,{questions:s.questions,formTitle:s.formTitle,formDescription:s.formDescription}))}finally{p?.dispose()}},renderCall:ft,renderResult:ht}),e.registerCommand(r.command.name,{description:r.command.description,handler:async(e,t)=>{t.ui.notify(r.command.notify,"info")}})}export{Me as ACTIVE_LOCALE,R as AdaptiveConditionError,G as AskAuthorFormModel,ve as AskAuthorParams,lt as ExpansionSchema,E as ICONS,y as LAYOUT_CONFIG,M as MAX_OPTIONS,k as MAX_QUESTIONS,Te as OptionSchema,at as QuestionSchema,ye as ShowIfConditionSchema,r as TEXTS,Qn as askAuthorExtension,xe as buildExpansionUserMessage,g as cleanOptional,q as cleanText,Qn as default,Qe as detectLocale,Se as expansionContext,ae as normalizeImeKey,W as padToVisibleWidth,we as parseExpansionReply,P as safeLine,K as sanitizeAskAuthorArgs,ge as sanitizeExpansionPayload};
package/dist/layout.d.ts CHANGED
@@ -58,11 +58,11 @@ export declare const ICONS: {
58
58
  /** 补充说明 */
59
59
  readonly note: "󰷬";
60
60
  /** 菜单行首聚焦指示 */
61
- readonly cursor: "";
61
+ readonly cursor: "󰁔";
62
62
  /** 列表与总览页向上方向提示 */
63
- readonly scrollUp: "";
63
+ readonly scrollUp: "󰁝";
64
64
  /** 列表与总览页向下方向提示 */
65
- readonly scrollDown: "";
65
+ readonly scrollDown: "󰁅";
66
66
  /** 多选已勾选(方括号复选框样式) */
67
67
  readonly checkedMulti: "[󰄬] ";
68
68
  /** 多选未勾选(方括号复选框样式) */