@sendevia/pi-ask-author 1.0.6 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{Text as ke}from"@earendil-works/pi-tui";import{getSelectListTheme as ft}from"@earendil-works/pi-coding-agent";import{Editor as ht,Key as b,matchesKey as h,visibleWidth as gt}from"@earendil-works/pi-tui";import{stripTerminalSequences as Le,truncateToWidth as Y,visibleWidth as ue,wrapTextWithAnsi as Me}from"@earendil-works/pi-tui";var y={dividerChar:" │ ",dividerThick:"═",dividerThin:"─",dividerWidth:3,leftColMax:46,leftColMin:30,leftColRatio:.42,splitViewMinWidth:72,previewScrollStep:3,singlePreviewHeight:7,splitPreviewHeight:14,summaryPageSize:16,summaryScrollStep:3,visibleOptionCount:7,statusDurationMs:3e3},S={cancel:"󰜺",check:"󰄬",checked:"󰐾",unchecked:"󰄰",error:"󰅚",note:"󰷬",cursor:"",scrollUp:"",scrollDown:"",checkedMulti:"[󰄬] ",uncheckedMulti:"[ ] ",checkedSingle:"(•) ",uncheckedSingle:"( ) "},L=30,D=20,B="\0",se=[{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))}],re=new Map(se.map(e=>[e.opener,e])),le=new Map(se.map(e=>[e.marker,e])),$="• ",s={tool:{name:"ask_author",label:"向作者请示",description:"Consult the author on novel creative decisions, plot branches, scene drafting, or story settings. Supports single and batched questions with plot deductions and draft previews.",promptSnippet:"Consult author on novel creative decisions, plot branches, scene drafting, or story settings",promptGuidelines:["Invoke ask_author DIRECTLY without conversational preambles or greetings whenever author confirmation is needed for plot, characters, scenes, branches, or settings.","ask_author modes: Always provide a concise formTitle. Use flat mode (formTitle + question + options) for single decisions, or the questions array for batch consultations. Batch interrelated decisions into one ask_author call; never make consecutive single-question calls.","ask_author payload minimization: Strictly omit optional fields (id, description, minSelect, maxSelect, allowEmpty, allowCustom, customPlaceholder) when using default behavior. Never output auto-generated IDs or default boolean flags.","ask_author option quality: Provide clear, descriptive labels summarizing the core action (never generic placeholders like 'Option A'). Include cause-and-effect plot deductions in description, and draft excerpts or dialogue in preview when helpful.","ask_author multi-select & notes: Set multiSelect: true only when choices are not mutually exclusive. The author can always submit free-form notes alongside choices (both per-question and per-option).","ask_author draft directives: Confirmed draft previews are automatically condensed into single-line directives in the ask_author result to guide subsequent story drafting.","ask_author envelopes: [Author Decision Cancelled] means do not proceed with the discarded decision; [Author Consultation Error] means fix the arguments and retry once, then continue without the confirmation if it fails again."]},schema:{optionLabel:"Concise, descriptive label summarizing the action or choice",optionDesc:"Plot consequences, rationale, or deduction (optional)",optionPreview:"Draft prose excerpt or scene storyboard preview (optional, Markdown)",optionCustomPlaceholder:"Placeholder text for option note input (optional)",questionId:"Question identifier (optional, omit unless needed)",questionTitle:"Question title (e.g., 'Choose the next route')",questionDesc:"Context or background for this question (optional)",questionMultiSelect:"Allow multiple selections (default false)",questionMinSelect:"Minimum selections required (default 1)",questionMaxSelect:"Maximum selections allowed (default: all options)",questionAllowEmpty:"Allow submitting with zero selections (default false)",questionOptions:`Candidate options (1-${L}, 2-10 recommended)`,questionAllowCustom:"Allow author free-form custom notes (default true)",questionCustomPlaceholder:"Placeholder text for author note input (optional)",formTitle:"Concise title describing the overall consultation task",formDesc:"Overall context or background for the consultation (optional)",formQuestions:`Batched related questions (1-${D}); batch interrelated decisions into one call instead of consecutive single-question calls`,formSingleQuestion:"Question title for flat single-question mode",flatPrefix:"(Flat single-question mode only) ",flatQuestionOptions:`Candidate options for flat single-question mode (1-${L}, 2-10 recommended)`},markdown:{envelopePrefix:"[Author Decision Finalized]",envelopeSuffix:"Execute workflow and writing strictly according to the author decisions and draft directives above without conversational acknowledgments.",envelopeCancelled:"[Author Decision Cancelled]\nThe author cancelled the consultation. Do not proceed with the discarded decision; propose next steps or ask for clarification in chat.",envelopeError:(e,t)=>`[Author Consultation Error]\nFailed to consult author: ${e}\nGuidance: ${t}`,errorReasons:{nonTui:"Interactive TUI is unavailable in the current execution mode.",noQuestions:"No valid questions or options were provided in arguments.",runtimeError:e=>`Runtime error during consultation UI execution: ${e}`},errorGuidances:{nonTui:"Proceed using defaults or ask user via standard chat/message if crucial.",noQuestions:"Provide at least one question with concrete options.",runtimeError:"Check arguments format and retry with valid questions and options."},envelopeEmpty:"Author submitted the form without any answers. Proceed with your defaults, or ask a follow-up question in chat if the decision is crucial.",noSelection:"(No selection; 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,s)=>`【${e}】${t}${s?` ${s}`:""}${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}`},command:{name:"ask-author",description:"查看 ask_author 创作请示工具说明",notify:"在提示词中指示 AI 调用 ask_author,即可向您请示创作决策"},common:{optionSeparator:"、",bulletPrefix:$,helpSeparator:" • "},tabs:{questionTab:e=>`第${e}题`,submitTab:`${S.check} 提交答卷`},view:{modeSingle:"[单选]",modeMulti:(e,t,i,s)=>{let o="[多选";return e>1?o+=` 至少${e}项`:(0===e||s)&&(o+=" 可不选"),t<i&&(o+=` 至多${t}项`),`${o}]`},attachedNoteBanner:e=>`${S.note} 题目补充说明:${e}`,optionAttachedNoteBanner:(e,t)=>`${S.note} [${e}] 选项补充说明:${t}`,listTopMore:e=>` ${S.scrollUp} 向上还有 ${e} 项`,listBottomMore:e=>` ${S.scrollDown} 向下还有 ${e} 项`,optionNotePanelTitle:"选项补充说明",storyDescriptionPanelTitle:"情节设定推演",storyDraftPanelTitle:"正文草稿/分镜头试撰写",customNotePanelTitle:"题目补充说明",confirmPanelTitle:"操作说明",customNotePanelCurrent:"当前填写内容:",previewScrollInfo:(e,t,i)=>`(行 ${e}-${t}/${i},PgUp/PgDn 滚动)`,previewNoDraft:"(无内容预览)",customNotePanelTips:[`${$}随时按「N」或选择此项按「Enter」填写/修改本题补充说明`,`${$}按「x」清空本题补充说明`,`${$}补充说明将随所选选项及选项专属补充说明一并提交给 AI 助手`],confirmPanelTips:[`${$}按 \`Enter\` 确认本题并前往下一题`,`${$}最后一题确认后自动进入总览提交页`],sectionTitle:e=>`### ${e}`,fieldLabel:e=>`**${e}**`,italicLine:e=>`_${e}_`},menu:{customNoteLabel:`${S.note} 题目补充说明`,customNoteLabelFilled:`${S.note} 题目补充说明 (已填写)`,confirmDetailMulti:(e,t)=>`已选 ${e}${e<t?`/${t}`:""} 项`,confirmLabel:(e,t)=>`${S.check} 确认本题 (${e}${t?" + 补充说明":""})`,confirmDesc:"确认并前往下一题或总览页"},editor:{title:e=>` ${S.note} 填写题目补充说明(${e})`,optionTitle:(e,t)=>` ${S.note} 填写选项补充说明(${t} - ${e})`,footerHelp:" [Enter] 保存并返回 • [Esc/Ctrl+C] 取消"},status:{questionNoteSaved:"已保存本题补充说明",noteCleared:"已清空本题补充说明",optionNoteSaved:e=>`已保存「${e}」补充说明`,optionNoteSavedUnselected:e=>`已保存「${e}」批注(该选项未勾选,仅作批注提交)`,optionNoteSavedAtLimit:e=>`已达上限(至多 ${e} 项):批注已保存,但该选项未勾选`,optionNoteCleared:e=>`已清空「${e}」补充说明`,selectedUpToLimit:e=>`已达选择上限(至多 ${e} 项)`,maxSelectExceeded:e=>`已达上限(至多 ${e} 项):请按「空格」取消已选项后重选`,minSelectRequired:e=>`未达下限(至少需 ${e} 项):请按「空格」继续勾选,或按「n/N」填写说明`,pleaseAnswerBeforeSubmit:"本题未完成:请按「空格/Enter」选定选项,或按「n/N」填写补充说明",editorDiscardConfirm:"再次按 Esc/Ctrl+C 放弃修改(未保存内容将丢失),继续输入可撤销",errorNonTui:"当前为非交互式终端环境,无法启动交互界面,请在交互式 TUI 会话中重试",errorNoQuestions:"未提供有效的问题或选项,请提供至少一个带选项的问题",errorExecutionFailed:e=>`组件执行异常:${e}(可修正参数后重试)`},help:{cancel:"Esc/Ctrl+C 取消",clearNote:"x 清空补充说明",confirmQuestion:"Enter 确认",confirmSubmit:"Enter 提交",editNote:"n 补充说明",editOptionNote:"n 选项补充说明",editQuestionNote:"N 题目补充说明",jumpQuestion:"1~9 跳转题目",moveCursor:"↑↓/jk 移动",scrollDraft:"PgUp/PgDn 滚动草稿",scrollSummary:"↑↓/PgUp/PgDn 滚动",selectOptionSingle:"空格/Enter 选定",switchQuestion:"Tab/←→/hl 切换题目",toggleAll:"a 全选/清空",toggleCheckMulti:"空格 勾选"},summary:{title:"【答卷总览与确认】",statusDone:"[已完成]",statusPending:"[未完成]",questionPrefix:(e,t)=>`第${e}题:${t}`,selectedLabel:"已选:",optionNoteBadge:`(${S.note} 批注)`,optionNotePrefix:e=>`${S.note} 选项补充说明(${e}):`,customNoteLabel:`${S.note} 题目补充说明:`,allDonePrompt:` ${S.check} 全部完成,按 Enter/Ctrl+S 提交答卷,Tab/hl/1-9 返回修改`,pendingWarning:` ${S.unchecked} 尚有题目未完成,按 Enter 前往作答,Tab/hl/1-9 切换修改`,topMore:e=>` ${S.scrollUp} 向上还有 ${e} 行`,bottomMore:e=>` ${S.scrollDown} 向下还有 ${e} 行`},card:{callQuestionAndOptionCount:(e,t)=>`${e} 题 • ${t} 选项`,callOptionCountOnly:e=>`${e} 选项`,resultCancelled:`${S.cancel} 已取消`,resultErrorShort:`${S.error} 执行失败`,resultCompleted:`${S.check} 已完成`,resultCount:e=>`${e} 项`,optionBullet:(e,t)=>`${$}${e}:${t}`,optionWithNote:(e,t)=>`${e} [${S.note} ${t}]`,questionNoteTag:e=>` (${S.note} 题目补充说明: ${e})`,errorBullet:e=>`${$}错误原因:${e}`},fallbacks:{defaultFormTitle:"创作决策",defaultQuestionTitle:"请选择接下来的创作方案",defaultCustomPlaceholder:"输入本题整体补充要求、伏笔细节或修改意见...",defaultOptionCustomPlaceholder:"输入针对该选项的具体补充要求或修改细节...",defaultCustomChoiceName:"自定义方案",defaultOptionLabel:"默认方案",unnamedOptionLabel:"未命名方案",unselectedOption:"未选",autoQuestionId:e=>`q_${e}`,autoQuestionTitle:e=>`问题 ${e}`,autoOptionLabel:e=>`选项 ${e}`}};function N(e,t,i){return Math.max(t,Math.min(e,i))}function M(e,t,i){return N(e,0,Math.max(0,t-i))}function J(e,t,i){return e.slice(t,t+i)}function C(e){return e?e.replace(/\t/g," ").replace(/\r/g,""):""}function Pe(e){return Le(e).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function w(e){let t=e?.trim();return t&&Pe(C(t))||void 0}function F(e){if("string"==typeof e){if(e.length>1e6)return;try{return JSON.parse(e)}catch{return}}return e}function Qe(e,t,i){let s=ue(e);s>=i&&i>0&&(e=Y(e,i-1),s=ue(e));let o=Math.max(1,i-s),n=" ".repeat(s),r=Me(t,o);return 0===r.length?e?[e]:[]:r.map((t,i)=>0===i?e+t:n+t)}function A(e,t,i,s=""){e.push(...Qe(s,t,i))}function O(e,t){return t<=0?"":Y(C(e),t)}function z(e,t){return t<=0?"":Y(C(e),t,"...",!0)}function Z(e,t=y.dividerThin){return e>0?t.repeat(e):""}function ae(e){if(!e)return;let t=C(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(s.markdown.draftSegmentSeparator):void 0}function ce(e){return e.replace(/\s+/g," ").trim()}function R(e){return!!e.customText?.trim()}function Re(e){for(let t of e.optionNotes.values())if(t?.trim())return!0;return!1}function ee(e){return R(e)||Re(e)}var qe={selectedIndices:new Set,optionNotes:new Map};function _e(e,t,i){let s=void 0!==e,o=N(e??1,0,i);return{minSelect:o,minSelectExplicit:s,maxSelect:N(t??i,o,i)}}function de(e,t){return{id:w(e.id)??s.fallbacks.autoQuestionId(t+1),title:w(e.title)??s.fallbacks.autoQuestionTitle(t+1),description:w(e.description),multiSelect:!!e.multiSelect,..._e(e.minSelect,e.maxSelect,e.options.length),options:e.options.map(e=>({label:w(e.label)??s.fallbacks.unnamedOptionLabel,description:w(e.description),preview:w(e.preview),customPlaceholder:w(e.customPlaceholder)})),allowEmpty:!!e.allowEmpty,allowCustom:!1!==e.allowCustom,customPlaceholder:w(e.customPlaceholder)??s.fallbacks.defaultCustomPlaceholder}}function De(e){let t=new Set;return e.map((e,i)=>{if(!t.has(e.id))return t.add(e.id),e;let o=s.fallbacks.autoQuestionId(i+1);for(let e=2;t.has(o);e++)o=`${o}_${e}`;return t.add(o),{...e,id:o}})}function P(e){return ce(e).replace(/[“”„‟«»]/g,"'").replace(/[\[\]]/g,e=>"["===e?"[":"]").replace(/[【】]/g,"").replace(/;/g,";")}function Be(e,t){return void 0===t?e:e===s.fallbacks.defaultQuestionTitle||e===s.fallbacks.autoQuestionTitle(t+1)?s.markdown.fallbackQuestionTitle(t+1):e}function me(e,t){return void 0===t?e:e===s.fallbacks.unnamedOptionLabel||e===s.fallbacks.defaultOptionLabel||e===s.fallbacks.autoOptionLabel(t)?s.markdown.fallbackOptionLabel(t):e}var Q=class{formTitle;formDescription;questions;revisionValue=0;states=new Map;constructor(e){let t=e.questions??[],i=t.length>0;this.formTitle=w(e.formTitle)??s.fallbacks.defaultFormTitle,this.formDescription=w(e.description),this.questions=i?De(t.map((e,t)=>de(e,t))):e.options?.length?[de({title:w(e.question)??s.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},0)]:[]}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}getSelectedIndices(e){let t=this.states.get(e);return t?Array.from(t.selectedIndices).sort((e,t)=>e-t):[]}bumpRevision(){this.revisionValue++}getMenuItems(e){let t=this.getQuestion(e);if(!t)return[];let i=this.getState(e),o=ee(i),n=t.options.map((e,t)=>({type:"option",optionIndex:t,label:e.label,description:e.description,preview:e.preview}));t.allowCustom&&n.push({type:"custom_note",label:R(i)?s.menu.customNoteLabelFilled:s.menu.customNoteLabel});let r=t.multiSelect?s.menu.confirmDetailMulti(i.selectedIndices.size,t.minSelect):void 0!==i.selectedIndex?t.options[i.selectedIndex]?.label??s.fallbacks.unselectedOption:o?s.fallbacks.defaultCustomChoiceName:s.fallbacks.unselectedOption;return n.push({type:"confirm_btn",label:s.menu.confirmLabel(r,o),description:s.menu.confirmDesc}),n}isQuestionAnswered(e){let t=this.questions[e];if(!t)return!1;let i=this.states.get(e)??qe;if(!t.multiSelect)return void 0!==i.selectedIndex||t.allowEmpty||t.allowCustom&&ee(i);let s=i.selectedIndices.size;return!!(s>=t.minSelect||0===s&&t.allowEmpty||!t.minSelectExplicit&&0===s&&t.allowCustom&&ee(i))}areAllQuestionsAnswered(){return this.questions.every((e,t)=>this.isQuestionAnswered(t))}toggleOption(e,t){let i=this.getQuestion(e);if(!i||!i.options[t])return"limit";let s=this.getState(e);return i.multiSelect?s.selectedIndices.has(t)?(s.selectedIndices.delete(t),this.bumpRevision(),"deselected"):s.selectedIndices.size>=i.maxSelect?"limit":(s.selectedIndices.add(t),this.bumpRevision(),"selected"):(s.selectedIndex=s.selectedIndex===t?void 0:t,this.bumpRevision(),void 0===s.selectedIndex?"deselected":"selected")}commitOption(e,t){let i=this.getQuestion(e);if(!i||!i.options[t])return;let s=this.getState(e);i.multiSelect?s.selectedIndices.has(t)||s.selectedIndices.size>=i.maxSelect||(s.selectedIndices.add(t),this.bumpRevision()):s.selectedIndex!==t&&(s.selectedIndex=t,this.bumpRevision())}selectAllOrClear(e){let t=this.getQuestion(e);if(!t||!t.multiSelect)return"cleared";let i=this.getState(e);if(i.selectedIndices.size>=t.maxSelect)return i.selectedIndices.clear(),this.bumpRevision(),"cleared";for(let e=0;e<t.options.length&&i.selectedIndices.size<t.maxSelect;e++)i.selectedIndices.add(e);return this.bumpRevision(),"filled"}setOptionNote(e,t,i){let s=this.getQuestion(e);if(!s||!s.options[t])return"cleared";let o=this.getState(e),n=w(i);return this.bumpRevision(),n?(o.optionNotes.set(t,n),s.multiSelect?o.selectedIndices.has(t)?"saved":o.selectedIndices.size>=s.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),s=w(t);return i.customText=s,this.bumpRevision(),s?"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){let i={};if(!t)return i;for(let[s,o]of t.optionNotes){let t=w(o);t&&e.options[s]&&(i[s+1]=t)}return i}compileAnswers(){let e=[];for(let[t,i]of this.questions.entries()){let s=this.states.get(t),o=s?.customText?.trim()?C(s.customText.trim()):void 0,n={questionId:i.id,questionTitle:i.title,customText:o};if(i.multiSelect){let o=this.getSelectedIndices(t),r=this.collectOptionNotes(i,s),l=[];for(let e of o){let t=i.options[e];t&&l.push({...t,customText:r[e+1]})}let a=Object.keys(r).length>0;e.push({...n,multiSelect:!0,selectedOptions:l,selectedIndices:o.map(e=>e+1),optionNotes:a?r:void 0})}else if(void 0!==s?.selectedIndex){let t=i.options[s.selectedIndex],o=this.collectOptionNotes(i,s);e.push({...n,multiSelect:!1,selectedOption:t?{...t,customText:o[s.selectedIndex+1]}:void 0,selectedOptionIndex:s.selectedIndex+1,optionNotes:Object.keys(o).length>0?o:void 0})}else if(this.isQuestionAnswered(t)){let t=this.collectOptionNotes(i,s),o=Object.keys(t).length>0;e.push({...n,multiSelect:!1,optionNotes:o?t:void 0})}}return e}formatAnswers(e){if(0===e.length)return`${s.markdown.envelopePrefix}\n${s.markdown.envelopeEmpty}\n${s.markdown.envelopeSuffix}`;let t=e=>e?`${s.markdown.notePrefix}${P(e)}${s.markdown.noteSuffix}`:"",i=e=>e?`${s.markdown.draftDirectivePrefix}${P(e)}${s.markdown.draftDirectiveSuffix}`:"",o=new Map(this.questions.map(e=>[e.id,e])),n=new Map(this.questions.map((e,t)=>[e.id,t])),r=e.map((e,r)=>{let l=n.get(e.questionId),a=(e.multiSelect?e.selectedOptions??[]:e.selectedOption?[e.selectedOption]:[]).map((o,n)=>{let r=ae(o.preview),l=t(w(o.customText)??""),a=P(me(o.label,e.multiSelect?e.selectedIndices?.[n]:e.selectedOptionIndex)),u=P(o.description??"");return u?s.markdown.optionWithDesc(a,u,i(r),l):s.markdown.optionWithoutDesc(a,i(r),l)}),u=o.get(e.questionId);if(u&&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 r=u.options[e-1]?.label;r&&n&&a.push(s.markdown.unselectedOptionNote(P(me(r,e)),t(n)))}}e.customText&&a.push(t(e.customText));let c=a.join(s.markdown.partSeparator)||s.markdown.noSelection;return s.markdown.answerLine(r+1,P(Be(e.questionTitle,l)),c)});return`${s.markdown.envelopePrefix}\n${r.join("\n")}\n${s.markdown.envelopeSuffix}`}};import{getMarkdownTheme as Fe}from"@earendil-works/pi-coding-agent";import{Markdown as ze}from"@earendil-works/pi-tui";function je(e){let t=Fe();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=>Ue(e,i)??t.code(i),codeBlockBorder:t=>e.fg("dim",t),link:t=>e.fg("accent",t),linkUrl:t=>e.fg("dim",t)}}function Ue(e,t){if(!t.startsWith(B))return;let i=[],s=0;for(;s<t.length;){if(t.charAt(s)!==B)return;let o=le.get(t.charAt(s+1));if(!o)return;let n=t.indexOf(B,s+2),r=n<0?t.length:n;i.push(o.paint(e,t.slice(s+2,r))),s=r}return i.length>0?i.join(""):void 0}var Ve=/^ {0,3}(`{3,}|~{3,})/,We=/^ {4,}\S/,Xe=/^ {0,3}(?:<(?=[/!?a-zA-Z])|\|)/,pe=/^ {0,3}(?:\$\$|\\\[)/;function fe(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 s=e.charAt(t+1);if(""!==s&&!/\s/.test(s))return!0}return!1}var He=/^(?: {0,3}>[ \t]?)+/,Ge=/^ {0,3}\[[^\]\n]*\]:/;function be(e){return e.replace(He,"")}function Ke(e){return!!e.includes("|")&&/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/.test(be(e))}var Ye=/^ {0,3}(?:#{1,6}[ \t]|[-+*][ \t]|\d{1,9}[.)][ \t]|>|\||`{3,}|~{3,})/,Je=/[`*_\[\]<>$\\|]|~~|&(?:[A-Za-z][A-Za-z0-9]*|#\d+|#[xX][0-9a-fA-F]+);/;function Ze(e){let t=[],i=0;for(let s of e)t.push(i),i+=s.length+1;return t}function et(e,t,i){let s=new Uint8Array(e.length),o=(e,t)=>{for(let i=e;i<t;i++)s[i]=1},n=e=>{let s=i[e]??0;o(s,s+(t[e]?.length??0))},r=null,l=!1,a=null,u="";for(let e=0;e<t.length;e++){let i=t[e]??"";if(""===i.trim()){l=!1,null!==r&&n(e),null!==a&&n(e);continue}if(null!==a){u+=i,n(e);let t=i.indexOf(a);if(t>=0){let e=i.slice(t+a.length);a=null,fe(e)&&(l=!0)}continue}if(null!==r){n(e),r.test(i)&&(r=null);continue}if(l){n(e);continue}if(Ke(i)){n(e),l=!0;let i=t[e-1];void 0!==i&&i.includes("|")&&n(e-1);continue}let s=Ve.exec(i),o=s?.[1],c=i.slice(s?.[0].length??0);if(void 0===o||"~"!==o[0]&&c.includes("`"))if(We.test(i))n(e);else if(Xe.test(be(i)))n(e),l=!0;else if(Ge.test(i))n(e);else{if(pe.test(i)){let t=i.replace(pe,"");u=t,n(e),t.includes(t.startsWith("$$")?"$$":"\\]")||(a=t.startsWith("$$")?"$$":"\\]");continue}fe(i)&&(n(e),l=!0)}else n(e),r=new RegExp(`^ {0,3}${o[0]??"`"}{${o.length},}[ \\t]*$`)}let c=0;for(;c<e.length;){if("`"!==e[c]||1===s[c]){c++;continue}let t=0;for(;"`"===e[c+t]&&0===s[c+t];)t++;let i=tt(e,s,c+t,t);if(i<0)return null;o(c,i+t),c=i+t}return s}function tt(e,t,i,s){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===s&&"`"!==e[o+s])return o;o+=i-1}return-1}function nt(e,t,i,s){let o=[],n=[];for(let r=0;r<e.length;r++){if(1===t[r])continue;let l=e[r]??"",a=re.get(l);if(void 0!==a){o.push({template:a,start:r});continue}let u=it(o,l);if(u<0)continue;let c=o[u];if(o.length=u,!c)continue;let d=r+1;if(d-c.start>c.template.maxSpanLength||Je.test(e.slice(c.start,d)))continue;let h=he(s,c.start),m=he(s,d-1);if(!ot(i,h,m))continue;let p=n[n.length-1];for(;void 0!==p&&p.startFlat>=c.start;)n.pop(),p=n[n.length-1];n.push({template:c.template,startFlat:c.start,startLine:h,startCol:c.start-(s[h]??0),endLine:m,endCol:d-(s[m]??0)})}return n}function it(e,t){for(let i=e.length-1;i>=0;i--)if(e[i]?.template.closer===t)return i;return-1}function he(e,t){let i=0,s=Math.max(0,e.length-1);for(;i<s;){let o=i+s+1>>1;(e[o]??0)<=t?i=o:s=o-1}return i}function ot(e,t,i){if(t===i)return!0;for(let s=t+1;s<=i;s++){let t=e[s]??"";if(""===t.trim()||Ye.test(t))return!1}return!0}function st(e,t){let i=[];for(let s of t)i.push(`${B}${s.template.marker}${e.slice(s.start,s.end)}`);return`\`${i.join("")}\``}function rt(e,t){let i=[],s=0,o=0;for(;o<t.length;){let n=t[o];if(!n)break;let r=[n],l=n;for(;o+1<t.length;){let e=t[o+1];if(!e||e.start!==l.end)break;o++,l=e,r.push(e)}let a=n.start,u=l.end,c=e.slice(s,a),d=e.slice(a,u),h="`"===e.charAt(a-1)||"`"===e.charAt(u);i.push(c,h?d:st(e,r)),s=u,o++}return i.push(e.slice(s)),i.join("")}function lt(e,t,i){for(let s=t;s<i;s++)if(1===e[s])return!0;return!1}function ut(e,t,i,s){let o=new Map;for(let n of s){let s=(t[n.startLine]??0)+n.startCol,r=(t[n.endLine]??0)+n.endCol;for(let l=n.startLine;l<=n.endLine;l++){let a=t[l]??0,u=a+(e[l]?.length??0),c=Math.max(s,a),d=Math.min(r,u);if(d<=c||lt(i,c,d))continue;let h={start:c-a,end:d-a,template:n.template},m=o.get(l);m?m.push(h):o.set(l,[h])}}return e.map((e,t)=>{let i=o.get(t);return i?(i.sort((e,t)=>e.start-t.start),rt(e,i)):e}).join("\n")}function at(e){if(0===e.length)return e;let t=e.split("\n"),i=Ze(t),s=et(e,t,i);if(null===s)return e;let o=nt(e,s,t,i);return 0===o.length?e:ut(t,i,s,o)}function ge(e,t){return`${s.view.sectionTitle(e)}\n\n${t.map(e=>`${e}\n`).join("")}`}function Se(e,t,i,o,n){if(!e)return[];let r="";"option"===e.type?(i&&(r+=`${s.view.sectionTitle(s.view.optionNotePanelTitle)}\n\n${s.view.fieldLabel(s.view.customNotePanelCurrent)}\n\n${C(i)}\n\n`),e.description&&(r+=`${s.view.sectionTitle(s.view.storyDescriptionPanelTitle)}\n\n${C(e.description)}\n\n`),e.preview?r+=`${s.view.sectionTitle(s.view.storyDraftPanelTitle)}\n\n${C(e.preview)}\n\n`:!e.description&&!i&&(r+=`${s.view.italicLine(s.view.previewNoDraft.trim())}\n\n`)):"custom_note"===e.type?(r+=ge(s.view.customNotePanelTitle,s.view.customNotePanelTips),t&&(r+=`\n${s.view.fieldLabel(s.view.customNotePanelCurrent)}\n\n${C(t)}\n\n`)):r+=ge(s.view.confirmPanelTitle,s.view.confirmPanelTips);let l=je(n);return new ze(r.trim(),1,0,l,void 0,{transform:at}).render(o)}import{visibleWidth as te,wrapTextWithAnsi as ct}from"@earendil-works/pi-tui";function j(e,t){return e.options[t]?.label??s.fallbacks.autoOptionLabel(t+1)}function dt(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&&R(i)}function mt(e,t,i,s){return"option"!==s.type||void 0===s.optionIndex?"":t.multiSelect?i.selectedIndices.has(s.optionIndex)?e.fg("success",S.checkedMulti):e.fg("dim",S.uncheckedMulti):i.selectedIndex===s.optionIndex?e.fg("accent",S.checkedSingle):e.fg("dim",S.uncheckedSingle)}function Te(e,t,i,s,o,n){let r=dt(t,s,o),l=`${i?e.fg("accent",e.bold(`${S.cursor} `)):" "}${mt(e,s,o,t)}`,a=te(l),u=" ".repeat(a),c=Math.max(8,n-a),d=t.label;return"option"===t.type&&void 0!==t.optionIndex&&o.optionNotes.get(t.optionIndex)&&(d=`${t.label} ${S.note}`),(te(d)<=c?[d]:ct(d,c)).map((s,o)=>{if(i)return e.bg("selectedBg",e.fg("text",e.bold(z(0===o?`${l}${s}`:`${u}${s}`,n))));let a=e.fg("option"!==t.type&&"custom_note"!==t.type||r?"text":"dim",s);return O(0===o?`${l}${a}`:`${u}${a}`,n)})}function we(e,t,i,o){let n=i===t.questionCount,r=[],l=[];for(let o=0;o<t.questionCount;o++){let n=o===i,r=t.isQuestionAnswered(o),a=r?"success":"muted",u=` ${r?S.checked:S.unchecked} ${s.tabs.questionTab(o+1)} `;l.push(n?e.bg("selectedBg",e.fg("accent",e.bold(u))):e.fg(a,u))}let a=` ${s.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=te(e);c>0&&c+1+t>o?(r.push(O(u,o)),u="",c=0):c>0&&(u+=" ",c+=1),u+=e,c+=t}return r.push(O(u,o)),r.push(e.fg("dim",Z(o))),r}function pt(e){return e.join(s.common.helpSeparator)}function ne(e,t,i,s){A(e,i.fg("dim",pt(t)),s," ")}function U(e,t,i){e.push(t.fg("accent",Z(i,y.dividerThick)))}function ve(e){return[s.help.switchQuestion,...e.questionCount>1?[s.help.jumpQuestion]:[],s.help.scrollSummary,s.help.confirmSubmit,s.help.cancel]}function ye(e,t,i){let o=[];for(let n=0;n<e.questionCount;n++){let r=e.getQuestion(n);if(!r)continue;let l=e.isQuestionAnswered(n),a=e.getState(n);A(o,`${l?t.fg("success",s.summary.statusDone):t.fg("warning",s.summary.statusPending)} ${t.bold(s.summary.questionPrefix(n+1,r.title))}`,i," ");let u=[];if(r.multiSelect)for(let t of e.getSelectedIndices(n)){let e=r.options[t];if(!e)continue;let i=a.optionNotes.get(t);u.push(i?`${e.label} ${s.summary.optionNoteBadge}`:e.label)}else if(void 0!==a.selectedIndex){let e=r.options[a.selectedIndex];if(e){let t=a.optionNotes.get(a.selectedIndex);u.push(t?`${e.label} ${s.summary.optionNoteBadge}`:e.label)}}let c=u.length?t.fg("accent",u.join(s.common.optionSeparator)):t.fg("dim",s.fallbacks.unselectedOption);A(o,`${t.fg("muted",s.summary.selectedLabel)} ${c}`,i," ");for(let[e,n]of a.optionNotes.entries()){let l=r.options[e];l&&n?.trim()&&A(o,`${t.fg("muted",s.summary.optionNotePrefix(l.label))} ${t.fg("accent",n)}`,i," ")}a.customText&&A(o,`${t.fg("muted",s.summary.customNoteLabel)} ${t.fg("accent",a.customText)}`,i," "),o.push("")}return o}var bt=32,X=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.leftColCache=void 0)}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;previewCache=new Map;summaryCachedLines;tabCache;leftColCache;menuCache;previewViewportObservation;editTarget;editor;constructor(e,t,i,o){this.tui=e,this.theme=t,this.model=i,this.done=o;let n={borderColor:e=>this.theme.fg("accent",e),selectList:ft()};this.editor=new ht(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?j(i,o):s.fallbacks.autoOptionLabel(o+1),r=this.model.setOptionNote(this.currentTab,o,e);this.setStatus("cleared"===r?s.status.optionNoteCleared(n):"savedAtLimit"===r&&i?s.status.optionNoteSavedAtLimit(i.maxSelect):"savedUnselected"===r?s.status.optionNoteSavedUnselected(n):s.status.optionNoteSaved(n))}else{let t=this.model.setQuestionNote(this.currentTab,e);this.setStatus("saved"===t?s.status.questionNoteSaved:s.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.previewCache.clear(),this.summaryCachedLines=void 0,this.tabCache=void 0,this.leftColCache=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()}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 totalTabs(){return this.model.questionCount+1}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 summaryPageSize(){return N(this.terminalRows-10,4,y.summaryPageSize)}get splitPreviewHeight(){return N(this.terminalRows-14,6,y.splitPreviewHeight)}get singlePreviewHeight(){return N(this.terminalRows-18,3,y.singlePreviewHeight)}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){if(e!==this.currentTab){if(this.currentTab=e,this.previewScrollOffset=0,this.summaryScrollOffset=0,this.listScrollOffset=0,this.menuCache=void 0,this.isSubmitTab)this.currentOptionIndex=0;else{let e=this.model.getState(this.currentTab);this.currentOptionIndex=this.cursorByTab.get(this.currentTab)??e.selectedIndex??0,this.adjustScrollForCurrentOption()}this.touch()}}adjustScrollForCurrentOption(){let e=this.getMenuItems().length;0!==e&&(this.currentOptionIndex=N(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=N("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),s=e??this.getEditTargetForCurrentSelection();this.editTarget=s,this.inputMode=!0,this.editorEscArmed=!1;let o="option"===s.type?i.optionNotes.get(s.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){"option"===e.type&&void 0!==e.optionIndex&&this.model.commitOption(this.currentTab,e.optionIndex),this.model.isQuestionAnswered(this.currentTab)?this.switchTab(this.currentTab<this.model.questionCount-1?this.currentTab+1:this.model.questionCount):this.setStatus(t.multiSelect?s.status.minSelectRequired(t.minSelect):s.status.pleaseAnswerBeforeSubmit)}handleInput(e){if(this.isFinished||this.disposed)return;let t=h(e,b.escape)||h(e,b.ctrl("c"));if(this.inputMode)return t?""===this.editor.getText()||this.editorEscArmed?void this.closeEditor():(this.editorEscArmed=!0,void this.setStatus(s.status.editorDiscardConfirm)):(this.editorEscArmed&&(this.editorEscArmed=!1,this.statusMessage=null),this.editor.handleInput(e),void this.touch());if(t)this.finish(!0);else{if(/^[1-9]$/.test(e)){let t=parseInt(e,10)-1;if(t<this.model.questionCount)return void this.switchTab(t)}h(e,b.tab)||h(e,b.right)||h(e,"l")?this.switchTab((this.currentTab+1)%this.totalTabs):h(e,b.shift("tab"))||h(e,b.left)||h(e,"h")?this.switchTab((this.currentTab-1+this.totalTabs)%this.totalTabs):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(h(e,b.ctrl("s")))return void this.confirmAndAdvance(i,t);if(h(e,b.space))return void this.activateMenuItem(i,t);h(e,b.enter)&&("custom_note"===i.type?this.openCustomEditor({type:"question"}):this.confirmAndAdvance(i,t))}}handleNoteShortcut(e,t){if(!e.allowCustom)return!1;if(h(t,b.shift("n")))return this.openCustomEditor({type:"question"}),!0;if(h(t,"n")||h(t,"e"))return this.openCustomEditor(),!0;if(h(t,"x")||h(t,b.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(s.status.optionNoteCleared(j(e,i))),!0}if(this.model.clearQuestionNote(this.currentTab))return this.setStatus(s.status.noteCleared),!0}return!1}handlePreviewScroll(e){let t=0;if(h(e,b.pageUp)||h(e,b.leftbracket)||h(e,b.alt("up"))?t=-y.previewScrollStep:(h(e,b.pageDown)||h(e,b.rightbracket)||h(e,b.alt("down")))&&(t=y.previewScrollStep),0===t)return!1;let i=this.previewViewportObservation,s=i?.viewHeight??this.singlePreviewHeight;return this.previewScrollOffset=M(this.previewScrollOffset+t,i?.total??0,s),this.touch(),!0}handleCursorNavigation(e){return h(e,b.up)||h(e,"k")?(this.moveCursor({delta:-1}),!0):h(e,b.down)||h(e,"j")?(this.moveCursor({delta:1}),!0):h(e,b.home)?(this.moveCursor(0),!0):!!h(e,b.end)&&(this.moveCursor(Number.MAX_SAFE_INTEGER),!0)}handleSelectAllShortcut(e,t){return!(!e.multiSelect||!h(t,"a")||("filled"===this.model.selectAllOrClear(this.currentTab)&&e.maxSelect<e.options.length?this.setStatus(s.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(s.status.maxSelectExceeded(t.maxSelect)):this.touch()}handleSummaryInput(e){if(h(e,b.enter)||h(e,b.ctrl("s"))){if(this.model.areAllQuestionsAnswered())this.finish(!1);else{let e=this.model.questions.findIndex((e,t)=>!this.model.isQuestionAnswered(t));if(-1!==e){this.switchTab(e);let t=this.model.getQuestion(e);t&&this.setStatus(t.multiSelect?s.status.minSelectRequired(t.minSelect):s.status.pleaseAnswerBeforeSubmit)}}return}if(h(e,b.home))return this.summaryScrollOffset=0,void this.touch();if(h(e,b.end))return this.summaryScrollOffset=Number.MAX_SAFE_INTEGER,void this.touch();let t=this.summaryScrollStep(e);if(0===t&&h(e,b.space)&&(t=y.summaryScrollStep),0===t)return;let i=this.summaryCachedLines?.lines.length??0,o=this.summaryPageSize,n=M(this.summaryScrollOffset,i,o);this.summaryScrollOffset=M(n+t,i,o),this.touch()}summaryScrollStep(e){return h(e,b.pageUp)||h(e,b.leftbracket)||h(e,b.alt("up"))?-y.summaryScrollStep:h(e,b.pageDown)||h(e,b.rightbracket)||h(e,b.alt("down"))?y.summaryScrollStep:h(e,b.up)||h(e,"k")?-1:h(e,b.down)||h(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 s=[];U(s,this.theme,t);let o=`${this.currentTab}_${this.model.revision}_${t}`;return(!this.tabCache||this.tabCache.key!==o)&&(this.tabCache={key:o,lines:we(this.theme,this.model,this.currentTab,t)}),s.push(...this.tabCache.lines),this.isSubmitTab?this.renderSubmitSummary(s,t):this.inputMode?this.renderInputMode(s,t):this.renderQuestionView(s,t),this.cachedWidth=e,this.cachedLayoutWidth=t,this.cachedHeight=i,this.cachedLines=s.map(t=>O(t,e)),this.cachedLines}pushStatusMessage(e){this.statusMessage&&(e.push(""),e.push(` ${this.theme.fg("warning",this.statusMessage)}`))}renderSubmitSummary(e,t){e.push(this.theme.fg("accent",this.theme.bold(s.summary.title))),e.push("");let i=t-2;(!this.summaryCachedLines||this.summaryCachedLines.width!==i||this.summaryCachedLines.revision!==this.model.revision)&&(this.summaryCachedLines={width:i,revision:this.model.revision,lines:ye(this.model,this.theme,i)});let o=this.summaryCachedLines.lines,n=o.length,r=this.summaryPageSize,l=M(this.summaryScrollOffset,n,r);l>0&&e.push(this.theme.fg("dim",s.summary.topMore(l)));for(let t of J(o,l,r))e.push(t);let a=n-(l+r);a>0&&e.push(this.theme.fg("dim",s.summary.bottomMore(a))),e.push(""),A(e,this.model.areAllQuestionsAnswered()?this.theme.fg("success",this.theme.bold(s.summary.allDonePrompt)):this.theme.fg("warning",s.summary.pendingWarning),i),this.pushStatusMessage(e),e.push(""),ne(e,ve(this.model),this.theme,t),U(e,this.theme,t)}renderInputMode(e,t){let i=this.model.getQuestion(this.currentTab);if(i){if("option"===this.editTarget?.type){let o=this.editTarget.optionIndex,n=i.options[o],r=j(i,o),l=n?.customPlaceholder??s.fallbacks.defaultOptionCustomPlaceholder;e.push(this.theme.fg("accent",this.theme.bold(s.editor.optionTitle(i.title,r)))),n?.description&&A(e,this.theme.fg("muted",n.description),t," "),e.push(""),e.push(this.theme.fg("accent",` ${l}`))}else e.push(this.theme.fg("accent",this.theme.bold(s.editor.title(i.title)))),i.description&&A(e,this.theme.fg("muted",i.description),t," "),e.push(""),e.push(this.theme.fg("accent",` ${i.customPlaceholder}`));e.push("");for(let i of this.editor.render(Math.max(10,t-4)))e.push(` ${i}`);e.push(""),e.push(this.theme.fg("dim",s.editor.footerHelp)),U(e,this.theme,t)}}renderQuestionView(e,t){let i=this.model.getQuestion(this.currentTab);if(!i)return;let o=this.model.getState(this.currentTab),n=this.getMenuItems();A(e,` ${i.multiSelect?this.theme.fg("warning",s.view.modeMulti(i.minSelect,i.maxSelect,i.options.length,i.allowEmpty)):this.theme.fg("accent",s.view.modeSingle)} ${this.theme.bold(i.title)}`,t),i.description&&A(e,this.theme.fg("muted",i.description),t," "),o.customText?.trim()&&A(e,this.theme.fg("success",s.view.attachedNoteBanner(o.customText)),t," ");let r=this.currentMenuItem();if("option"===r?.type&&void 0!==r.optionIndex){let n=o.optionNotes.get(r.optionIndex)?.trim();if(n){let o=j(i,r.optionIndex);A(e,this.theme.fg("success",s.view.optionAttachedNoteBanner(o,n)),t," ")}}e.push("");let l=i.options.some((e,t)=>!!e.preview||gt(e.description??"")>30||!!o.optionNotes.get(t));t>=y.splitViewMinWidth&&l?this.renderSplitView(e,i,o,n,t):this.pushListItems(e,n,i,o,t-2,l),this.pushStatusMessage(e),e.push("");let a=[s.help.switchQuestion];this.model.questionCount>1&&a.push(s.help.jumpQuestion),a.push(s.help.moveCursor),"option"===r?.type?(a.push(s.help.editOptionNote),a.push(s.help.editQuestionNote)):a.push(s.help.editNote),("option"===r?.type&&void 0!==r.optionIndex&&o.optionNotes.has(r.optionIndex)||R(o))&&a.push(s.help.clearNote),a.push(i.multiSelect?s.help.toggleCheckMulti:s.help.selectOptionSingle),i.multiSelect&&(a.push(s.help.toggleAll),a.push(s.help.confirmQuestion)),l&&a.push(s.help.scrollDraft),a.push(s.help.cancel),ne(e,a,this.theme,t),U(e,this.theme,t)}previewContentLines(e,t,i,s){if(!e)return[];let o=[this.currentTab,e.type,e.optionIndex??-1,s,t??"",i??""].join(""),n=this.previewCache.get(o);if(n)return n;let r=Se(e,t,i,s,this.theme);if(this.previewCache.size>=bt){let e=this.previewCache.keys().next();e.done||this.previewCache.delete(e.value)}return this.previewCache.set(o,r),r}buildPreviewBox(e,t,i,s,o){let n=this.previewContentLines(e,t,i,s),r=n.length;return this.previewViewportObservation={total:r,viewHeight:o},this.slicePreviewBoxLines(n,M(this.previewScrollOffset,r,o),o,s)}slicePreviewBoxLines(e,t,i,o){let n=e.length,r=M(t,n,i),l=J(e,r,i).map(e=>O(e,o));if(n>i){let e=s.view.previewScrollInfo(r+1,Math.min(n,r+i),n);l.push(O(` ${this.theme.fg("dim",e)}`,o))}return l}renderSplitView(e,t,i,s,o){let n,r=N(Math.floor(o*y.leftColRatio),y.leftColMin,y.leftColMax),l=Math.max(20,o-r-y.dividerWidth),a=`${this.currentTab}_${this.currentOptionIndex}_${this.listScrollOffset}_${this.model.revision}_${r}`;this.leftColCache&&this.leftColCache.key===a?n=this.leftColCache.lines:(n=[],this.pushListItems(n,s,t,i,r,!1),this.leftColCache={key:a,lines:n});let u=s[this.currentOptionIndex],c="option"===u?.type&&void 0!==u.optionIndex?i.optionNotes.get(u.optionIndex):void 0,d=this.buildPreviewBox(u,i.customText,c,l,this.splitPreviewHeight),h=Math.max(n.length,d.length);for(let t=0;t<h;t++){let i=d[t]??"";e.push(`${z(n[t]??"",r)}${this.theme.fg("dim",y.dividerChar)}${O(i,l)}`)}}pushListItems(e,t,i,o,n,r){this.listScrollOffset>0&&e.push(this.theme.fg("dim",s.view.listTopMore(this.listScrollOffset)));let l=t.slice(this.listScrollOffset,this.listScrollOffset+y.visibleOptionCount);for(let[s,a]of l.entries()){if(!a)continue;let l=this.listScrollOffset+s,u=l===this.currentOptionIndex,c=t[l-1];if(c&&"option"===c.type&&"option"!==a.type&&e.push(""),e.push(...Te(this.theme,a,u,i,o,n)),u&&r&&("option"!==a.type||a.description||a.preview||o.optionNotes.has(a.optionIndex??-1))){e.push("");let t="option"===a.type&&void 0!==a.optionIndex?o.optionNotes.get(a.optionIndex):void 0,i=this.buildPreviewBox(a,o.customText,t,Math.max(10,n-2),this.singlePreviewHeight);for(let t of i)e.push(t);e.push("")}}let a=t.length-(this.listScrollOffset+y.visibleOptionCount);a>0&&e.push(this.theme.fg("dim",s.view.listBottomMore(a)))}};import{Type as f}from"typebox";var xe=f.Object({label:f.String({description:s.schema.optionLabel}),description:f.Optional(f.String({description:s.schema.optionDesc})),preview:f.Optional(f.String({description:s.schema.optionPreview})),customPlaceholder:f.Optional(f.String({description:s.schema.optionCustomPlaceholder}))}),St=f.Object({id:f.Optional(f.String({description:s.schema.questionId})),title:f.String({description:s.schema.questionTitle}),description:f.Optional(f.String({description:s.schema.questionDesc})),multiSelect:f.Optional(f.Boolean({description:s.schema.questionMultiSelect})),minSelect:f.Optional(f.Integer({description:s.schema.questionMinSelect,minimum:0})),maxSelect:f.Optional(f.Integer({description:s.schema.questionMaxSelect,minimum:1})),allowEmpty:f.Optional(f.Boolean({description:s.schema.questionAllowEmpty})),options:f.Array(xe,{description:s.schema.questionOptions,minItems:1,maxItems:L}),allowCustom:f.Optional(f.Boolean({description:s.schema.questionAllowCustom})),customPlaceholder:f.Optional(f.String({description:s.schema.questionCustomPlaceholder}))}),ie=f.Object({formTitle:f.String({description:s.schema.formTitle}),description:f.Optional(f.String({description:s.schema.formDesc})),questions:f.Optional(f.Array(St,{description:s.schema.formQuestions,minItems:1,maxItems:D})),question:f.Optional(f.String({description:s.schema.formSingleQuestion})),multiSelect:f.Optional(f.Boolean({description:`${s.schema.flatPrefix}${s.schema.questionMultiSelect}`})),minSelect:f.Optional(f.Integer({description:`${s.schema.flatPrefix}${s.schema.questionMinSelect}`,minimum:0})),maxSelect:f.Optional(f.Integer({description:`${s.schema.flatPrefix}${s.schema.questionMaxSelect}`,minimum:1})),allowEmpty:f.Optional(f.Boolean({description:`${s.schema.flatPrefix}${s.schema.questionAllowEmpty}`})),options:f.Optional(f.Array(xe,{description:s.schema.flatQuestionOptions,minItems:1,maxItems:L})),allowCustom:f.Optional(f.Boolean({description:`${s.schema.flatPrefix}${s.schema.questionAllowCustom}`})),customPlaceholder:f.Optional(f.String({description:`${s.schema.flatPrefix}${s.schema.questionCustomPlaceholder}`}))});function G(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Tt(e){let t=F(e.raw);return G(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 q(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 Ae(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 Ce(e){let t=Ae(e);return void 0===t?void 0:Math.max(0,t)}function Ie(e){let t=Ae(e);return void 0!==t&&t>=1?t:void 0}function Ne(e){let t=F(e);return Array.isArray(t)?t.slice(0,L).map((e,t)=>{if("string"==typeof e)return{label:e.trim()||s.fallbacks.autoOptionLabel(t+1)};if(!G(e))return{label:s.fallbacks.autoOptionLabel(t+1)};let i=e;return{label:w(I(i,["label","name","title","text","value","choice"]))??s.fallbacks.autoOptionLabel(t+1),description:w(I(i,["description","desc","reason","rationale","deduction"])),preview:w(I(i,["preview","draft","scene","content"])),customPlaceholder:w(I(i,["customPlaceholder","placeholder"]))}}):[]}function wt(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 vt(e,t){if("string"==typeof e)return{title:e,options:H([])};if(!G(e))return{title:s.fallbacks.autoQuestionTitle(t+1),options:H([])};let i=e;return{id:I(i,["id"]),title:w(I(i,["title","question","prompt","query","heading"]))??s.fallbacks.autoQuestionTitle(t+1),description:w(I(i,["description","desc","rationale"])),multiSelect:q(i.multiSelect,!1),minSelect:Ce(i.minSelect),maxSelect:Ie(i.maxSelect),allowEmpty:q(i.allowEmpty,!1),options:H(Ne(i.options??i.choices??i.items)),allowCustom:q(i.allowCustom,!0),customPlaceholder:I(i,["customPlaceholder","placeholder"])}}function yt(e){if(void 0===e)return;let t=F(e),i=Array.isArray(t)?t:wt(t)?[t]:[];return 0!==i.length?i.slice(0,D).map((e,t)=>vt(e,t)):void 0}function H(e){return e.length>0?e:[{label:s.fallbacks.defaultOptionLabel}]}function xt(e,t,i,s){return"string"==typeof e?e:"string"==typeof t?t:s?i:void 0}function K(e){let t=e&&"object"==typeof e?e:F(e);if(!G(t))return{formTitle:s.fallbacks.defaultFormTitle};let i=Tt({...t}),o=w(I(i,["title","taskTitle"])),n=w(I(i,["formTitle"]))??o??s.fallbacks.defaultFormTitle,r=yt(i.questions??i.form??i.survey),l=void 0!==i.options||void 0!==i.choices||void 0!==i.items,a=l?H(Ne(i.options??i.choices??i.items)):void 0,u=xt(i.question,i.prompt,o,l);return{formTitle:n,description:I(i,["description"]),questions:r,question:u,multiSelect:void 0===i.multiSelect?void 0:q(i.multiSelect,!1),minSelect:void 0===i.minSelect?void 0:Ce(i.minSelect),maxSelect:void 0===i.maxSelect?void 0:Ie(i.maxSelect),allowEmpty:void 0===i.allowEmpty?void 0:q(i.allowEmpty,!1),options:a,allowCustom:void 0===i.allowCustom?void 0:q(i.allowCustom,!0),customPlaceholder:I(i,["customPlaceholder"])}}function At(e){return e instanceof Error?e.message:String(e)}function Ee(e={}){return{formTitle:e.formTitle??s.fallbacks.defaultFormTitle,formDescription:e.formDescription,questions:e.questions??[]}}function _(e,t){let i=t instanceof ke?t:new ke("",0,0);return i.setText(e),i}function Oe(e={}){let{formTitle:t,formDescription:i,questions:o}=Ee(e);return{content:[{type:"text",text:s.markdown.envelopeCancelled}],details:{formTitle:t,formDescription:i,questions:o,answers:[],cancelled:!0}}}function oe(e,t,i,o={}){let{formTitle:n,formDescription:r,questions:l}=Ee(o);return{content:[{type:"text",text:s.markdown.envelopeError(e,t)}],details:{formTitle:n,formDescription:r,questions:l,answers:[],cancelled:!1,error:i}}}function $e(e,t={}){let i=At(e);return oe(s.markdown.errorReasons.runtimeError(i),s.markdown.errorGuidances.runtimeError,s.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 It(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 Nt(e){let t=e.customText?s.card.questionNoteTag(e.customText):"",i=(e,t)=>t?s.card.optionWithNote(e,t):e;return e.multiSelect?((e.selectedOptions??[]).map(e=>i(e.label,e.customText)).join(s.common.optionSeparator)||s.fallbacks.unselectedOption)+t:e.selectedOption?i(e.selectedOption.label,e.selectedOption.customText)+t:e.customText||s.fallbacks.unselectedOption}function kt(e,t){if(t.cachedArgs===e&&t.cachedCard)return t.cachedCard;let i=new Q(K(e)),o=i.questions.reduce((e,t)=>e+t.options.length,0),n={title:i.formTitle,countLabel:i.questions.length>1?s.card.callQuestionAndOptionCount(i.questions.length,o):s.card.callOptionCountOnly(o)};return t.cachedArgs=e,t.cachedCard=n,n}function Ot(e){e.registerTool({name:s.tool.name,label:s.tool.label,description:s.tool.description,promptSnippet:s.tool.promptSnippet,promptGuidelines:[...s.tool.promptGuidelines],parameters:ie,executionMode:"sequential",prepareArguments:K,async execute(e,t,i,o,n){let r,l,a=w(t?.formTitle)??s.fallbacks.defaultFormTitle;if(i?.aborted)return Oe({formTitle:a});if("tui"!==n.mode)return oe(s.markdown.errorReasons.nonTui,s.markdown.errorGuidances.nonTui,s.status.errorNonTui,{formTitle:a});try{r=new Q(t)}catch(e){return $e(e,{formTitle:a})}if(0===r.questions.length)return oe(s.markdown.errorReasons.noQuestions,s.markdown.errorGuidances.noQuestions,s.status.errorNoQuestions,{questions:[],formTitle:r.formTitle,formDescription:r.formDescription});try{let e=await n.ui.custom((e,t,s,o)=>(l=new X(e,t,r,o),l.bindAbortSignal(i),l));return!e||e.cancelled?Oe({questions:e?.questions??r.questions,formTitle:e?.formTitle??r.formTitle,formDescription:e?.formDescription??r.formDescription}):Ct(r,e.answers)}catch(e){return $e(e,{questions:r.questions,formTitle:r.formTitle,formDescription:r.formDescription})}finally{l?.dispose()}},renderCall(e,t,i){let o=kt(e,i.state);return _(`${t.fg("accent",s.tool.label)} ${t.bold(o.title)} ${t.fg("muted",`(${o.countLabel})`)}`,i.lastComponent)},renderResult(e,{expanded:t},i,o){let n=It(e.details);if(n.error){let e=`${i.fg("error",i.bold(s.card.resultErrorShort))} ${i.fg("muted",`${s.common.bulletPrefix}${n.error}`)}`;return _(t?`${e}\n${s.card.errorBullet(i.fg("error",n.error))}`:e,o.lastComponent)}if(n.cancelled)return _(i.fg("warning",s.card.resultCancelled),o.lastComponent);let r=`${i.fg("success",i.bold(s.card.resultCompleted))} ${i.fg("muted",`${s.common.bulletPrefix}${s.card.resultCount(n.answers.length)}`)}`;return _(t?[r,...n.answers.map(e=>s.card.optionBullet(i.bold(e.questionTitle),i.fg("accent",Nt(e))))].join("\n"):r,o.lastComponent)}}),e.registerCommand(s.command.name,{description:s.command.description,handler:async(e,t)=>{t.ui.notify(s.command.notify,"info")}})}export{Q as AskAuthorFormModel,ie as AskAuthorParams,S as ICONS,y as LAYOUT_CONFIG,s as TEXTS,Ot as askAuthorExtension,w as cleanOptional,C as cleanText,Ot as default,z as padToVisibleWidth,O as safeLine,K as sanitizeAskAuthorArgs};
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};
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @file layout.ts
3
+ * @description 终端布局几何、图标字形与载荷上限的单一源头
4
+ *
5
+ * 核心架构特性:
6
+ * - 纯常量模块,零插件内依赖;任何模块可在不装载语言资源的前提下引用布局数值与图标
7
+ * - `LAYOUT_CONFIG` / `ICONS` / `MAX_*` 集中声明可调参数与强制上限,语言文件通过 `{icon.<键>}` 占位符引用图标
8
+ *
9
+ * 依赖方向:layout.ts → 无插件内依赖;被 format / schema / texts / view-rows / view-question / component 消费
10
+ */
11
+ /** TUI 视图几何、分栏与滚动行为配置(数值项均标注单位 ms / cols / lines;分隔线条目为字符文本,不带单位) */
12
+ export declare const LAYOUT_CONFIG: {
13
+ /** 双栏中间分隔符文本 */
14
+ readonly dividerChar: " │ ";
15
+ /** 外层框架分割线字符(双横线) */
16
+ readonly dividerThick: "═";
17
+ /** 内部内容分割线字符(单横线) */
18
+ readonly dividerThin: "─";
19
+ /** 中间分隔符可见宽度 (cols) */
20
+ readonly dividerWidth: 3;
21
+ /** 左栏最大可见宽度 (cols) */
22
+ readonly leftColMax: 46;
23
+ /** 左栏最小可见宽度 (cols) */
24
+ readonly leftColMin: 30;
25
+ /** 宽屏双栏下左栏占视口比例 */
26
+ readonly leftColRatio: 0.42;
27
+ /** 触发宽屏双栏的终端最小列宽 (cols) */
28
+ readonly splitViewMinWidth: 72;
29
+ /** Tab 栏自定义短标签的最大可见宽度 (cols);超出部分由 `truncateToWidth` 截断 */
30
+ readonly tabLabelMaxWidth: 14;
31
+ /** 预览区单次翻页滚动行数 (lines) */
32
+ readonly previewScrollStep: 3;
33
+ /** 窄屏单栏折叠预览区最大可见行数 (lines) */
34
+ readonly singlePreviewHeight: 7;
35
+ /** 宽屏双栏右侧预览区最大可见行数 (lines) */
36
+ readonly splitPreviewHeight: 14;
37
+ /** 总览页单页最大内容行数 (lines) */
38
+ readonly summaryPageSize: 16;
39
+ /** 总览页单次滚动步长 (lines) */
40
+ readonly summaryScrollStep: 3;
41
+ /** 菜单每页最大可见选项数 (项) */
42
+ readonly visibleOptionCount: 7;
43
+ /** 底部状态通知停留时长 (ms) */
44
+ readonly statusDurationMs: 3000;
45
+ };
46
+ /** Nerd Font 状态与操作语义图标字典(按语义分区排列;四个选择指示符自带 1 空格尾随填充以拉开与标签的间距;语言文件通过 `{icon.<键>}` 占位符引用) */
47
+ export declare const ICONS: {
48
+ /** 取消 / 中止 */
49
+ readonly cancel: "󰜺";
50
+ /** 完成与确认(结果卡片与总览页完成态) */
51
+ readonly check: "󰄬";
52
+ /** 题目已完成 */
53
+ readonly checked: "󰐾";
54
+ /** 题目未完成 */
55
+ readonly unchecked: "󰄰";
56
+ /** 失败 */
57
+ readonly error: "󰅚";
58
+ /** 补充说明 */
59
+ readonly note: "󰷬";
60
+ /** 菜单行首聚焦指示 */
61
+ readonly cursor: "";
62
+ /** 列表与总览页向上方向提示 */
63
+ readonly scrollUp: "";
64
+ /** 列表与总览页向下方向提示 */
65
+ readonly scrollDown: "";
66
+ /** 多选已勾选(方括号复选框样式) */
67
+ readonly checkedMulti: "[󰄬] ";
68
+ /** 多选未勾选(方括号复选框样式) */
69
+ readonly uncheckedMulti: "[ ] ";
70
+ /** 单选已选中(圆括号圆钮样式) */
71
+ readonly checkedSingle: "(•) ";
72
+ /** 单选未选中(圆括号圆钮样式) */
73
+ readonly uncheckedSingle: "( ) ";
74
+ };
75
+ /** 单题最大选项数上限(项;同时约束 `schema.ts` 的 `options.maxItems` 与 `sanitize.ts` 的选项截断) */
76
+ export declare const MAX_OPTIONS = 30;
77
+ /** 单份问卷最大题目数上限(题;同时约束 `schema.ts` 的 `questions.maxItems` 与 `sanitize.ts` 的题目截断) */
78
+ export declare const MAX_QUESTIONS = 20;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * @file llm-texts.ts
3
+ * @description 面向大语言模型的协议文案:工具元数据、TypeBox 字段描述与返回封套模板
4
+ *
5
+ * 核心架构特性:
6
+ * - 全部文案恒为英文,不参与语言切换,保证封套与工具声明的前缀缓存稳定
7
+ * - 唯一非英文片段为封套选项标签定界符 `【】`;作者文本在 `model.ts` 编译前已经消毒,无法击穿令牌边界
8
+ * - 新增字段描述或错误路径时只需扩充本文件,作者界面文案仍由 `lang/*.json` 提供
9
+ *
10
+ * 依赖方向:llm-texts.ts → layout.ts(`MAX_OPTIONS` / `MAX_QUESTIONS` 插值);被 texts.ts 组装进 `TEXTS`
11
+ */
12
+ /** 面向大模型的提示词、字段描述与返回封套:作为协议常量固定为英文,提升前缀缓存命中率 */
13
+ export declare const LLM_TEXTS: {
14
+ /** 工具注册元数据(`label` 面向作者,取自语言文件,故在此缺席) */
15
+ readonly tool: {
16
+ /** 工具调用名(LLM 协议标识,注册为 `ask_author`;不出现在作者界面) */
17
+ readonly name: "ask_author";
18
+ /** 工具说明(LLM 端英文;一句话能力概要与适用场景) */
19
+ readonly 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.";
20
+ /** `Available tools` 区块单行条目(LLM 端英文;动词引导,无句末标点,缺省则工具不进入该区块) */
21
+ readonly promptSnippet: "Ask the author to choose narrative directions with options, draft previews, and conditional follow-ups";
22
+ /**
23
+ * `Guidelines` 区块附加条目(LLM 端英文;分类标签前缀 + 行为要求)
24
+ * 约定:宿主把条目扁平追加进 `Guidelines` 且不加工具名前缀,故每条首词必须显式点名 `ask_author`
25
+ */
26
+ readonly promptGuidelines: readonly ["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."];
27
+ };
28
+ /** LLM 端 TypeBox 字段描述字典(单句浓缩英文,仅声明语义、必要性与省略规则;数量约束来自 {@link MAX_OPTIONS} / {@link MAX_QUESTIONS} 插值) */
29
+ readonly schema: {
30
+ /** 选项标签(必须填写;要求简明动作导向,禁止占位式命名) */
31
+ readonly optionLabel: "Concrete action or choice label";
32
+ /** 选项情节推演(可选;作者端渲染为「情节设定推演」预览面板) */
33
+ readonly optionDesc: "Consequences or rationale (optional)";
34
+ /** 选项草稿预览(可选;作者端渲染为「正文草稿/分镜头试撰写」预览面板) */
35
+ readonly optionPreview: "Markdown draft or storyboard excerpt (optional)";
36
+ /** 选项批注占位符(可选;作者端作为选项补充说明编辑器的输入框占位文本) */
37
+ readonly optionCustomPlaceholder: "Placeholder for the option note (optional)";
38
+ /** 选项显示条件(可选;条件不成立时该选项不展示) */
39
+ readonly optionShowIf: "Show only when an earlier answer matches (condition or array; all must hold)";
40
+ /** 题目 ID(可选;仅在后续 showIf 引用时需要) */
41
+ readonly questionId: "Stable id for showIf references (optional)";
42
+ /** 题目标题(必须填写;作者端呈现为题头与总览页条目) */
43
+ readonly questionTitle: "Question text";
44
+ /** Tab 栏短标签(可选;缺省时 Tab 栏显示 `Q<序号>`,显式给出可让作者在一屏内区分多题) */
45
+ readonly questionTabLabel: "Short label for the tab bar (default: Q<index>)";
46
+ /** 题目背景说明(可选;作者端呈现为题头下方的上下文行) */
47
+ readonly questionDesc: "Context for the question (optional)";
48
+ /** 多选开关(可选;默认 false,开启后作者端展示多选模式标签与方框勾选指示符) */
49
+ readonly questionMultiSelect: "Allow multiple selections (default false)";
50
+ /** 最小勾选数(可选;默认 1,仅多选生效,作者端据此标注强制下限) */
51
+ readonly questionMinSelect: "Minimum selections (default 1)";
52
+ /** 最大勾选数(可选;默认全部选项,仅多选生效,小于选项总数时作者端追加上限标注) */
53
+ readonly questionMaxSelect: "Maximum selections (default: all options)";
54
+ /** 零勾选提交开关(可选;默认 false,仅多选生效,开启后作者端标注可不选) */
55
+ readonly questionAllowEmpty: "Allow submitting with no selection (default false)";
56
+ /** 候选选项列表(必须填写;1~{@link MAX_OPTIONS} 项;建议 2~10 项) */
57
+ readonly questionOptions: "Candidate options (1-30, 2-10 recommended)";
58
+ /** 自由批注开关(可选;默认 true,开启后作者端可额外提交非选项文本) */
59
+ readonly questionAllowCustom: "Allow author notes (default true)";
60
+ /** 作者批注占位符(可选;作者端作为题目补充说明编辑器的输入框占位文本) */
61
+ readonly questionCustomPlaceholder: "Placeholder for the author note (optional)";
62
+ /** 题目显示条件(可选;条件不成立时该题不展示,也不计入答卷) */
63
+ readonly questionShowIf: "Show only when an earlier answer matches (condition or array; all must hold)";
64
+ /** 显示条件引用的题目 ID(必须为本次表单中更早出现的题目) */
65
+ readonly conditionQuestionId: "Id of an earlier question";
66
+ /** 显示条件匹配的选项(引用题目的选项标签;作者选中该选项时条件成立) */
67
+ readonly conditionOption: "Option label that activates the condition";
68
+ /** 显示条件的作答存在性(缺省等价于 true;与 option 同时给出时忽略) */
69
+ readonly conditionAnswered: "Match any answer (default true) or no answer (false); ignored with option";
70
+ /** 问卷标题(必须填写;作者端呈现为卡片标题与总览页标题) */
71
+ readonly formTitle: "Short title for the consultation";
72
+ /** 问卷背景(可选;作者端呈现为问卷级上下文) */
73
+ readonly formDesc: "Overall context (optional)";
74
+ /** 批量模式题目数组(可选;1~{@link MAX_QUESTIONS} 题;与平铺单题模式互斥) */
75
+ readonly formQuestions: "Related questions (1-20); batch related decisions into one call";
76
+ /** 平铺模式的题目标题(可选;与批量模式的 `questionTitle` 同义) */
77
+ readonly formSingleQuestion: "Question for flat mode";
78
+ /** 平铺单题模式字段描述的统一区分前缀(LLM 端英文,`schema.ts` 逐字段拼接) */
79
+ readonly flatPrefix: "(Flat single-question mode only) ";
80
+ /** 平铺模式候选选项列表(可选;1~{@link MAX_OPTIONS} 项;建议 2~10 项) */
81
+ readonly flatQuestionOptions: "Options for flat mode (1-30, 2-10 recommended)";
82
+ };
83
+ /**
84
+ * LLM 端返回封套与纠正指令模板(全英文确定性结构,提升 Prompt Cache 命中率)
85
+ *
86
+ * 约定:首行方括号封套令牌 `[Author Decision Finalized]` / `[Author Decision Cancelled]` / `[Author Consultation Error]`;行内令牌 `[Author note: …]` / `[Draft directive: …]`;选项标签定界符 `【】`
87
+ * 语言归属:`【】` 是本区段唯一的非英文片段,`model.ts` 的 `sanitizeEnvelopeText` 剥离作者文本中的 `【】` 并把 ASCII `;` 归一为全角 `;`,插值文本无法击穿上述定界符
88
+ */
89
+ readonly markdown: {
90
+ /** 完成封套首行标识(固定英文令牌,恒为返回正文第一行) */
91
+ readonly envelopePrefix: "[Author Decision Finalized]";
92
+ /** 完成封套收尾指令(固定英文单行,驱动后续写作) */
93
+ readonly envelopeSuffix: "Proceed with the author decisions and draft directives above without conversational acknowledgment.";
94
+ /** 取消封套(固定两行:标识行 + 禁止沿用被丢弃决策的英文处置指令) */
95
+ readonly envelopeCancelled: "[Author Decision Cancelled]\nThe author cancelled. Do not proceed with the discarded decision; propose next steps or ask for clarification.";
96
+ /**
97
+ * 构建错误封套(固定三行:标识行 + 原因行 + 指引行)
98
+ * @param reason - 面向 LLM 的英文失败原因(取自 `errorReasons`)
99
+ * @param guidance - 面向 LLM 的英文纠正指引(取自 `errorGuidances`)
100
+ */
101
+ readonly envelopeError: (reason: string, guidance: string) => string;
102
+ /** 错误封套原因行字典(英文单句,按失败路径枚举) */
103
+ readonly errorReasons: {
104
+ /** 非交互式终端环境无法启动 TUI(对应作者端 `status.errorNonTui`) */
105
+ readonly nonTui: "Interactive TUI is unavailable in the current mode.";
106
+ /** 入参无有效题目或选项(对应作者端 `status.errorNoQuestions`) */
107
+ readonly noQuestions: "No questions or options were provided.";
108
+ /** 构建执行期异常的原因行(`details` 为宿主异常摘要,对应作者端 `status.errorExecutionFailed`) */
109
+ readonly runtimeError: (details: string) => string;
110
+ /** 自适应条件引用无效(对应作者端 `status.errorInvalidCondition`) */
111
+ readonly invalidCondition: (details: string) => string;
112
+ };
113
+ /** 错误封套纠正指引行字典(英文单句,与 `errorReasons` 一一对应) */
114
+ readonly errorGuidances: {
115
+ /** `nonTui` 的纠正指引 */
116
+ readonly nonTui: "Use defaults, or ask the user in chat if the decision is crucial.";
117
+ /** `noQuestions` 的纠正指引 */
118
+ readonly noQuestions: "Provide at least one question with concrete options.";
119
+ /** `runtimeError` 的纠正指引 */
120
+ readonly runtimeError: "Check the arguments and retry with valid questions and options.";
121
+ /** `invalidCondition` 的纠正指引 */
122
+ readonly invalidCondition: "Reference an earlier question id plus one of its option labels, or use answered.";
123
+ };
124
+ /** 自适应条件引用校验的英文诊断消息(拼入错误封套原因行) */
125
+ readonly adaptiveErrors: {
126
+ /** 条件引用的题目 ID 不存在 */
127
+ readonly unknownQuestion: (questionId: string) => string;
128
+ /** 条件引用的题目不在该条件所属题目之前 */
129
+ readonly forwardQuestion: (questionId: string) => string;
130
+ /** 条件引用的选项标签在目标题目中不存在 */
131
+ readonly unknownOption: (questionId: string, option: string) => string;
132
+ };
133
+ /** 空答卷封套正文(作者未作答时的英文处置指令,位于首尾标识之间) */
134
+ readonly envelopeEmpty: "The author submitted no answers. Use your defaults, or ask a follow-up if the decision is crucial.";
135
+ /** 单题无任何作答(未勾选且无批注)时的英文占位正文 */
136
+ readonly noSelection: "(No selection; the author skipped this question)";
137
+ /** 行内批注令牌左定界符(尾随 1 空格,与 `noteSuffix` 成对) */
138
+ readonly notePrefix: "[Author note: ";
139
+ /** 行内批注令牌右定界符 */
140
+ readonly noteSuffix: "]";
141
+ /** 分镜头草稿指令令牌左定界符(尾随 1 空格,与 `draftDirectiveSuffix` 成对) */
142
+ readonly draftDirectivePrefix: "[Draft directive: ";
143
+ /** 分镜头草稿指令令牌右定界符 */
144
+ readonly draftDirectiveSuffix: "]";
145
+ /** 构建封套单题作答行(`index` 为 1-based 题号,`title` 为题目标题,`body` 为单行正文) */
146
+ readonly answerLine: (index: number, title: string, body: string) => string;
147
+ /** 同一作答行内多个片段(选项推演 / 批注令牌 / 草稿指令)的分隔符(纯 ASCII;作者文本中的 `;` 已在 `sanitizeEnvelopeText` 归一为全角 `;` 消除歧义) */
148
+ readonly partSeparator: "; ";
149
+ /** 正文草稿 / 分镜头草稿压缩为单行指令时的分镜头片段分隔符(LLM 端纯 ASCII) */
150
+ readonly draftSegmentSeparator: " / ";
151
+ /**
152
+ * 构建带情节推演的选项片段:`【标签】推演 [Author note: …] [Draft directive: …]`
153
+ * @param label - 选项标签原文(调用方已过 `sanitizeEnvelopeText`)
154
+ * @param desc - 选项情节推演 / 设定阐述(调用方已过 `sanitizeEnvelopeText`)
155
+ * @param draftDirective - 已包装的 `[Draft directive: …]` 令牌(可选,非原文)
156
+ * @param note - 已包装的 `[Author note: …]` 令牌(可选,非原文)
157
+ * @returns 输出顺序恒为「标签 → 推演 → 批注 → 草稿指令」,与形参顺序不同处在于批注先于草稿
158
+ */
159
+ readonly optionWithDesc: (label: string, desc: string, draftDirective?: string, note?: string) => string;
160
+ /**
161
+ * 构建无情节推演的选项片段:`【标签】[Author note: …] [Draft directive: …]`
162
+ * @param label - 选项标签原文(调用方已过 `sanitizeEnvelopeText`)
163
+ * @param draftDirective - 已包装的 `[Draft directive: …]` 令牌(可选,非原文)
164
+ * @param note - 已包装的 `[Author note: …]` 令牌(可选,非原文)
165
+ * @returns 输出顺序恒为「标签 → 批注 → 草稿指令」,与形参顺序不同处在于批注先于草稿
166
+ */
167
+ readonly optionWithoutDesc: (label: string, draftDirective?: string, note?: string) => string;
168
+ /**
169
+ * 构建未选中选项上的孤立批注片段(英文前缀 + 标签 + 批注令牌)
170
+ * @param label - 选项标签原文(调用方已过 `sanitizeEnvelopeText`)
171
+ * @param note - 已包装的 `[Author note: …]` 令牌(非原文)
172
+ */
173
+ readonly unselectedOptionNote: (label: string, note: string) => string;
174
+ /** 生成题目标题的英文占位(`index` 为 1-based 题号;仅封套编译期替换 `fallbacks.autoQuestionTitle` 与 `fallbacks.defaultQuestionTitle`,作者界面保留语言文件中的占位) */
175
+ readonly fallbackQuestionTitle: (index: number) => string;
176
+ /** 生成选项标签的英文占位(`index` 为 1-based 选项序号;仅封套编译期替换 `fallbacks.autoOptionLabel` / `fallbacks.unnamedOptionLabel` / `fallbacks.defaultOptionLabel`,作者界面保留语言文件中的占位) */
177
+ readonly fallbackOptionLabel: (index: number) => string;
178
+ };
179
+ };