@sendevia/pi-ask-author 1.0.2 → 1.0.3
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 +1 -38
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,38 +1 @@
|
|
|
1
|
-
import{keyHint as Oe}from"@earendil-works/pi-coding-agent";import{Text as ke}from"@earendil-works/pi-tui";import{Editor as ft,Key as S,matchesKey as T,visibleWidth as ht}from"@earendil-works/pi-tui";import{truncateToWidth as J,visibleWidth as V,wrapTextWithAnsi as Le}from"@earendil-works/pi-tui";var y={dividerChar:" \u2502 ",dividerThick:"\u2550",dividerThin:"\u2500",dividerWidth:3,leftColMax:46,leftColMin:30,leftColRatio:.42,splitViewMinWidth:72,previewScrollStep:3,singlePreviewHeight:7,splitPreviewHeight:14,summaryPageSize:16,summaryScrollStep:3,visibleOptionCount:7,statusDurationMs:3e3},g={cancel:"\u{F073A}",check:"\u{F012C}",checked:"\u{F043E}",unchecked:"\u{F0130}",error:"\u{F015A}",note:"\u{F0DEC}",cursor:"\uEA9C",scrollUp:"\uEAA1",scrollDown:"\uEA9A",checkedMulti:"[\u{F012C}] ",uncheckedMulti:"[ ] ",checkedSingle:"(\u2022) ",uncheckedSingle:"( ) "},M=30,D=20,B="\0",re=[{opener:"\u300C",closer:"\u300D",marker:"d",maxSpanLength:400,paint:(t,e)=>t.fg("accent",e)},{opener:"\uFF08",closer:"\uFF09",marker:"m",maxSpanLength:400,paint:(t,e)=>t.fg("muted",t.italic(e))}],le=new Map(re.map(t=>[t.opener,t])),ue=new Map(re.map(t=>[t.marker,t])),$="\u2022 ",s={tool:{name:"ask_author",label:"\u5411\u4F5C\u8005\u8BF7\u793A",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-${M}, 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-${M}, 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]
|
|
2
|
-
The author cancelled the consultation. Do not proceed with the discarded decision; propose next steps or ask for clarification in chat.`,envelopeError:(t,e)=>`[Author Consultation Error]
|
|
3
|
-
Failed to consult author: ${t}
|
|
4
|
-
Guidance: ${e}`,errorReasons:{nonTui:"Interactive TUI is unavailable in the current execution mode.",noQuestions:"No valid questions or options were provided in arguments.",runtimeError:t=>`Runtime error during consultation UI execution: ${t}`},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:(t,e,n)=>`${t}. [${e}]: ${n}`,partSeparator:"; ",draftSegmentSeparator:" / ",optionWithDesc:(t,e,n,i)=>`\u3010${t}\u3011${e}${i?` ${i}`:""}${n?` ${n}`:""}`,optionWithoutDesc:(t,e,n)=>`\u3010${t}\u3011${n?` ${n}`:""}${e?` ${e}`:""}`,unselectedOptionNote:(t,e)=>`[Author note on unselected option \u3010${t}\u3011] ${e}`,fallbackQuestionTitle:t=>`Question ${t}`,fallbackOptionLabel:t=>`Option ${t}`},command:{name:"ask-author",description:"\u67E5\u770B ask_author \u521B\u4F5C\u8BF7\u793A\u5DE5\u5177\u8BF4\u660E",notify:"\u5728\u63D0\u793A\u8BCD\u4E2D\u6307\u793A AI \u8C03\u7528 ask_author\uFF0C\u5373\u53EF\u5411\u60A8\u8BF7\u793A\u521B\u4F5C\u51B3\u7B56"},common:{optionSeparator:"\u3001",bulletPrefix:$,helpSeparator:" \u2022 "},tabs:{questionTab:t=>`\u7B2C${t}\u9898`,submitTab:`${g.check} \u63D0\u4EA4\u7B54\u5377`},view:{modeSingle:"[\u5355\u9009]",modeMulti:(t,e,n,i)=>{let o="[\u591A\u9009";return t>1?o+=` \u81F3\u5C11${t}\u9879`:(t===0||i)&&(o+=" \u53EF\u4E0D\u9009"),e<n&&(o+=` \u81F3\u591A${e}\u9879`),`${o}]`},attachedNoteBanner:t=>`${g.note} \u9898\u76EE\u8865\u5145\u8BF4\u660E\uFF1A${t}`,optionAttachedNoteBanner:(t,e)=>`${g.note} [${t}] \u9009\u9879\u8865\u5145\u8BF4\u660E\uFF1A${e}`,listTopMore:t=>` ${g.scrollUp} \u5411\u4E0A\u8FD8\u6709 ${t} \u9879`,listBottomMore:t=>` ${g.scrollDown} \u5411\u4E0B\u8FD8\u6709 ${t} \u9879`,optionNotePanelTitle:"\u9009\u9879\u8865\u5145\u8BF4\u660E",storyDescriptionPanelTitle:"\u60C5\u8282\u8BBE\u5B9A\u63A8\u6F14",storyDraftPanelTitle:"\u6B63\u6587\u8349\u7A3F/\u5206\u955C\u5934\u8BD5\u64B0\u5199",customNotePanelTitle:"\u9898\u76EE\u8865\u5145\u8BF4\u660E",confirmPanelTitle:"\u64CD\u4F5C\u8BF4\u660E",customNotePanelCurrent:"\u5F53\u524D\u586B\u5199\u5185\u5BB9\uFF1A",previewScrollInfo:(t,e,n)=>`(\u884C ${t}-${e}/${n}\uFF0CPgUp/PgDn \u6EDA\u52A8)`,previewNoDraft:"(\u65E0\u5185\u5BB9\u9884\u89C8)",customNotePanelTips:[`${$}\u968F\u65F6\u6309\u300CN\u300D\u6216\u9009\u62E9\u6B64\u9879\u6309\u300CEnter\u300D\u586B\u5199/\u4FEE\u6539\u672C\u9898\u8865\u5145\u8BF4\u660E`,`${$}\u6309\u300Cx\u300D\u6E05\u7A7A\u672C\u9898\u8865\u5145\u8BF4\u660E`,`${$}\u8865\u5145\u8BF4\u660E\u5C06\u968F\u6240\u9009\u9009\u9879\u53CA\u9009\u9879\u4E13\u5C5E\u8865\u5145\u8BF4\u660E\u4E00\u5E76\u63D0\u4EA4\u7ED9 AI \u52A9\u624B`],confirmPanelTips:[`${$}\u6309 \`Enter\` \u786E\u8BA4\u672C\u9898\u5E76\u524D\u5F80\u4E0B\u4E00\u9898`,`${$}\u6700\u540E\u4E00\u9898\u786E\u8BA4\u540E\u81EA\u52A8\u8FDB\u5165\u603B\u89C8\u63D0\u4EA4\u9875`],sectionTitle:t=>`### ${t}`,fieldLabel:t=>`**${t}**`,italicLine:t=>`_${t}_`},menu:{customNoteLabel:`${g.note} \u9898\u76EE\u8865\u5145\u8BF4\u660E`,customNoteLabelFilled:`${g.note} \u9898\u76EE\u8865\u5145\u8BF4\u660E (\u5DF2\u586B\u5199)`,confirmDetailMulti:(t,e)=>`\u5DF2\u9009 ${t}${t<e?`/${e}`:""} \u9879`,confirmLabel:(t,e)=>`${g.check} \u786E\u8BA4\u672C\u9898 (${t}${e?" + \u8865\u5145\u8BF4\u660E":""})`,confirmDesc:"\u786E\u8BA4\u5E76\u524D\u5F80\u4E0B\u4E00\u9898\u6216\u603B\u89C8\u9875"},editor:{title:t=>` ${g.note} \u586B\u5199\u9898\u76EE\u8865\u5145\u8BF4\u660E\uFF08${t}\uFF09`,optionTitle:(t,e)=>` ${g.note} \u586B\u5199\u9009\u9879\u8865\u5145\u8BF4\u660E\uFF08${e} - ${t}\uFF09`,footerHelp:" [Enter] \u4FDD\u5B58\u5E76\u8FD4\u56DE \u2022 [Esc/Ctrl+C] \u53D6\u6D88"},status:{questionNoteSaved:"\u5DF2\u4FDD\u5B58\u672C\u9898\u8865\u5145\u8BF4\u660E",noteCleared:"\u5DF2\u6E05\u7A7A\u672C\u9898\u8865\u5145\u8BF4\u660E",optionNoteSaved:t=>`\u5DF2\u4FDD\u5B58\u300C${t}\u300D\u8865\u5145\u8BF4\u660E`,optionNoteSavedUnselected:t=>`\u5DF2\u4FDD\u5B58\u300C${t}\u300D\u6279\u6CE8\uFF08\u8BE5\u9009\u9879\u672A\u52FE\u9009\uFF0C\u4EC5\u4F5C\u6279\u6CE8\u63D0\u4EA4\uFF09`,optionNoteSavedAtLimit:t=>`\u5DF2\u8FBE\u4E0A\u9650\uFF08\u81F3\u591A ${t} \u9879\uFF09\uFF1A\u6279\u6CE8\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BE5\u9009\u9879\u672A\u52FE\u9009`,optionNoteCleared:t=>`\u5DF2\u6E05\u7A7A\u300C${t}\u300D\u8865\u5145\u8BF4\u660E`,selectedUpToLimit:t=>`\u5DF2\u8FBE\u9009\u62E9\u4E0A\u9650\uFF08\u81F3\u591A ${t} \u9879\uFF09`,maxSelectExceeded:t=>`\u5DF2\u8FBE\u4E0A\u9650\uFF08\u81F3\u591A ${t} \u9879\uFF09\uFF1A\u8BF7\u6309\u300C\u7A7A\u683C\u300D\u53D6\u6D88\u5DF2\u9009\u9879\u540E\u91CD\u9009`,minSelectRequired:t=>`\u672A\u8FBE\u4E0B\u9650\uFF08\u81F3\u5C11\u9700 ${t} \u9879\uFF09\uFF1A\u8BF7\u6309\u300C\u7A7A\u683C\u300D\u7EE7\u7EED\u52FE\u9009\uFF0C\u6216\u6309\u300Cn/N\u300D\u586B\u5199\u8BF4\u660E`,pleaseAnswerBeforeSubmit:"\u672C\u9898\u672A\u5B8C\u6210\uFF1A\u8BF7\u6309\u300C\u7A7A\u683C/Enter\u300D\u9009\u5B9A\u9009\u9879\uFF0C\u6216\u6309\u300Cn/N\u300D\u586B\u5199\u8865\u5145\u8BF4\u660E",editorDiscardConfirm:"\u518D\u6B21\u6309 Esc/Ctrl+C \u653E\u5F03\u4FEE\u6539\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u5C06\u4E22\u5931\uFF09\uFF0C\u7EE7\u7EED\u8F93\u5165\u53EF\u64A4\u9500",errorNonTui:"\u5F53\u524D\u4E3A\u975E\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u73AF\u5883\uFF0C\u65E0\u6CD5\u542F\u52A8\u4EA4\u4E92\u754C\u9762\uFF0C\u8BF7\u5728\u4EA4\u4E92\u5F0F TUI \u4F1A\u8BDD\u4E2D\u91CD\u8BD5",errorNoQuestions:"\u672A\u63D0\u4F9B\u6709\u6548\u7684\u95EE\u9898\u6216\u9009\u9879\uFF0C\u8BF7\u63D0\u4F9B\u81F3\u5C11\u4E00\u4E2A\u5E26\u9009\u9879\u7684\u95EE\u9898",errorExecutionFailed:t=>`\u7EC4\u4EF6\u6267\u884C\u5F02\u5E38\uFF1A${t}\uFF08\u53EF\u4FEE\u6B63\u53C2\u6570\u540E\u91CD\u8BD5\uFF09`},help:{cancel:"Esc/Ctrl+C \u53D6\u6D88",clearNote:"x \u6E05\u7A7A\u8865\u5145\u8BF4\u660E",confirmQuestion:"Enter \u786E\u8BA4",confirmSubmit:"Enter \u63D0\u4EA4",editNote:"n \u8865\u5145\u8BF4\u660E",editOptionNote:"n \u9009\u9879\u8865\u5145\u8BF4\u660E",editQuestionNote:"N \u9898\u76EE\u8865\u5145\u8BF4\u660E",jumpQuestion:"1~9 \u8DF3\u8F6C\u9898\u76EE",moveCursor:"\u2191\u2193/jk \u79FB\u52A8",scrollDraft:"PgUp/PgDn \u6EDA\u52A8\u8349\u7A3F",scrollSummary:"\u2191\u2193/PgUp/PgDn \u6EDA\u52A8",selectOptionSingle:"\u7A7A\u683C/Enter \u9009\u5B9A",switchQuestion:"Tab/\u2190\u2192/hl \u5207\u6362\u9898\u76EE",toggleAll:"a \u5168\u9009/\u6E05\u7A7A",toggleCheckMulti:"\u7A7A\u683C \u52FE\u9009"},summary:{title:"\u3010\u7B54\u5377\u603B\u89C8\u4E0E\u786E\u8BA4\u3011",statusDone:"[\u5DF2\u5B8C\u6210]",statusPending:"[\u672A\u5B8C\u6210]",questionPrefix:(t,e)=>`\u7B2C${t}\u9898\uFF1A${e}`,selectedLabel:"\u5DF2\u9009\uFF1A",optionNoteBadge:`(${g.note} \u6279\u6CE8)`,optionNotePrefix:t=>`${g.note} \u9009\u9879\u8865\u5145\u8BF4\u660E\uFF08${t}\uFF09\uFF1A`,customNoteLabel:`${g.note} \u9898\u76EE\u8865\u5145\u8BF4\u660E\uFF1A`,allDonePrompt:` ${g.check} \u5168\u90E8\u5B8C\u6210\uFF0C\u6309 Enter/Ctrl+S \u63D0\u4EA4\u7B54\u5377\uFF0CTab/hl/1-9 \u8FD4\u56DE\u4FEE\u6539`,pendingWarning:` ${g.unchecked} \u5C1A\u6709\u9898\u76EE\u672A\u5B8C\u6210\uFF0C\u6309 Enter \u524D\u5F80\u4F5C\u7B54\uFF0CTab/hl/1-9 \u5207\u6362\u4FEE\u6539`,topMore:t=>` ${g.scrollUp} \u5411\u4E0A\u8FD8\u6709 ${t} \u884C`,bottomMore:t=>` ${g.scrollDown} \u5411\u4E0B\u8FD8\u6709 ${t} \u884C`},card:{callQuestionAndOptionCount:(t,e)=>`${t} \u9898 \u2022 ${e} \u9009\u9879`,callOptionCountOnly:t=>`${t} \u9009\u9879`,resultCancelled:`${g.cancel} \u5DF2\u53D6\u6D88`,resultErrorShort:`${g.error} \u6267\u884C\u5931\u8D25`,resultCompleted:`${g.check} \u5DF2\u5B8C\u6210`,resultCount:t=>`${t} \u9879`,expandHint:"\u5C55\u5F00\u67E5\u770B\u660E\u7EC6",optionBullet:(t,e)=>`${$}${t}\uFF1A${e}`,optionWithNote:(t,e)=>`${t} [${g.note} ${e}]`,questionNoteTag:t=>` (${g.note} \u9898\u76EE\u8865\u5145\u8BF4\u660E: ${t})`,errorBullet:t=>`${$}\u9519\u8BEF\u539F\u56E0\uFF1A${t}`},fallbacks:{defaultFormTitle:"\u521B\u4F5C\u51B3\u7B56",defaultQuestionTitle:"\u8BF7\u9009\u62E9\u63A5\u4E0B\u6765\u7684\u521B\u4F5C\u65B9\u6848",defaultCustomPlaceholder:"\u8F93\u5165\u672C\u9898\u6574\u4F53\u8865\u5145\u8981\u6C42\u3001\u4F0F\u7B14\u7EC6\u8282\u6216\u4FEE\u6539\u610F\u89C1...",defaultOptionCustomPlaceholder:"\u8F93\u5165\u9488\u5BF9\u8BE5\u9009\u9879\u7684\u5177\u4F53\u8865\u5145\u8981\u6C42\u6216\u4FEE\u6539\u7EC6\u8282...",defaultCustomChoiceName:"\u81EA\u5B9A\u4E49\u65B9\u6848",defaultOptionLabel:"\u9ED8\u8BA4\u65B9\u6848",unnamedOptionLabel:"\u672A\u547D\u540D\u65B9\u6848",unselectedOption:"\u672A\u9009",autoQuestionId:t=>`q_${t}`,autoQuestionTitle:t=>`\u95EE\u9898 ${t}`,autoOptionLabel:t=>`\u9009\u9879 ${t}`}};function I(t,e,n){return Math.max(e,Math.min(t,n))}function L(t,e,n){return I(t,0,Math.max(0,e-n))}function Z(t,e,n){return t.slice(e,e+n)}function N(t){return t?t.replace(/\t/g," ").replace(/\r/g,""):""}function Pe(t){return t.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/\x1b[@-_]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function w(t){let e=t?.trim();return e&&Pe(N(e))||void 0}function F(t){if(typeof t=="string"){if(t.length>1e6)return;try{return JSON.parse(t)}catch{return}}return t}function Qe(t,e,n){let i=V(t);i>=n&&n>0&&(t=J(t,n-1),i=V(t));let o=Math.max(1,n-i),r=" ".repeat(i),u=Le(e,o);return u.length===0?t?[t]:[]:u.map((l,a)=>a===0?t+l:r+l)}function A(t,e,n,i=""){t.push(...Qe(i,e,n))}function k(t,e){if(e<=0)return"";let n=N(t);return V(n)>e?J(n,e):n}function X(t,e){if(e<=0)return"";let n=N(t),i=V(n);return i>=e?J(n,e):n+" ".repeat(e-i)}function ee(t,e=y.dividerThin){return t>0?e.repeat(t):""}function ae(t){if(!t)return;let e=N(t);if(!e.trim())return;let n=e.split(`
|
|
5
|
-
`).map(i=>{let o=i.trim();return o?(o=o.replace(/^(?:[>#]+\s*)+/,""),o=o.replace(/\s+/g," "),o):""}).filter(Boolean);if(n.length!==0)return n.join(s.markdown.draftSegmentSeparator)}function ce(t){return t.replace(/\s+/g," ").trim()}function R(t){return!!t.customText?.trim()}function Re(t){for(let e of t.optionNotes.values())if(e?.trim())return!0;return!1}function te(t){return R(t)||Re(t)}var qe={selectedIndices:new Set,optionNotes:new Map};function _e(t,e,n){let i=t!==void 0,o=I(t??1,0,n),r=I(e??n,o,n);return{minSelect:o,minSelectExplicit:i,maxSelect:r}}function de(t,e){return{id:w(t.id)??s.fallbacks.autoQuestionId(e+1),title:w(t.title)??s.fallbacks.autoQuestionTitle(e+1),description:w(t.description),multiSelect:!!t.multiSelect,..._e(t.minSelect,t.maxSelect,t.options.length),options:t.options.map(n=>({label:w(n.label)??s.fallbacks.unnamedOptionLabel,description:w(n.description),preview:w(n.preview),customPlaceholder:w(n.customPlaceholder)})),allowEmpty:!!t.allowEmpty,allowCustom:t.allowCustom!==!1,customPlaceholder:w(t.customPlaceholder)??s.fallbacks.defaultCustomPlaceholder}}function De(t){let e=new Set;return t.map((n,i)=>{if(!e.has(n.id))return e.add(n.id),n;let o=s.fallbacks.autoQuestionId(i+1);for(let r=2;e.has(o);r++)o=`${o}_${r}`;return e.add(o),{...n,id:o}})}function P(t){return ce(t).replace(/[“”„‟«»]/g,"'").replace(/[\[\]]/g,e=>e==="["?"\uFF3B":"\uFF3D").replace(/[【】]/g,"").replace(/;/g,"\uFF1B")}function Be(t,e){return e===void 0?t:t===s.fallbacks.defaultQuestionTitle||t===s.fallbacks.autoQuestionTitle(e+1)?s.markdown.fallbackQuestionTitle(e+1):t}function me(t,e){return e===void 0?t:t===s.fallbacks.unnamedOptionLabel||t===s.fallbacks.defaultOptionLabel||t===s.fallbacks.autoOptionLabel(e)?s.markdown.fallbackOptionLabel(e):t}var Q=class{formTitle;formDescription;questions;revisionValue=0;states=new Map;constructor(e){let n=e.questions??[],i=n.length>0;this.formTitle=w(e.formTitle)??s.fallbacks.defaultFormTitle,this.formDescription=w(e.description),i?this.questions=De(n.map((o,r)=>de(o,r))):e.options?.length?this.questions=[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)]:this.questions=[]}get revision(){return this.revisionValue}get questionCount(){return this.questions.length}getQuestion(e){return this.questions[e]}getState(e){let n=this.states.get(e);return n||(n={selectedIndices:new Set,optionNotes:new Map},this.states.set(e,n)),n}getSelectedIndices(e){let n=this.states.get(e);return n?Array.from(n.selectedIndices).sort((i,o)=>i-o):[]}bumpRevision(){this.revisionValue++}getMenuItems(e){let n=this.getQuestion(e);if(!n)return[];let i=this.getState(e),o=te(i),r=n.options.map((l,a)=>({type:"option",optionIndex:a,label:l.label,description:l.description,preview:l.preview}));n.allowCustom&&r.push({type:"custom_note",label:R(i)?s.menu.customNoteLabelFilled:s.menu.customNoteLabel});let u=n.multiSelect?s.menu.confirmDetailMulti(i.selectedIndices.size,n.minSelect):i.selectedIndex!==void 0?n.options[i.selectedIndex]?.label??s.fallbacks.unselectedOption:o?s.fallbacks.defaultCustomChoiceName:s.fallbacks.unselectedOption;return r.push({type:"confirm_btn",label:s.menu.confirmLabel(u,o),description:s.menu.confirmDesc}),r}isQuestionAnswered(e){let n=this.questions[e];if(!n)return!1;let i=this.states.get(e)??qe;if(!n.multiSelect)return i.selectedIndex!==void 0||n.allowEmpty||n.allowCustom&&te(i);let o=i.selectedIndices.size;return!!(o>=n.minSelect||o===0&&n.allowEmpty||!n.minSelectExplicit&&o===0&&n.allowCustom&&te(i))}areAllQuestionsAnswered(){return this.questions.every((e,n)=>this.isQuestionAnswered(n))}toggleOption(e,n){let i=this.getQuestion(e);if(!i||!i.options[n])return"limit";let o=this.getState(e);return i.multiSelect?o.selectedIndices.has(n)?(o.selectedIndices.delete(n),this.bumpRevision(),"deselected"):o.selectedIndices.size>=i.maxSelect?"limit":(o.selectedIndices.add(n),this.bumpRevision(),"selected"):(o.selectedIndex=o.selectedIndex===n?void 0:n,this.bumpRevision(),o.selectedIndex===void 0?"deselected":"selected")}commitOption(e,n){let i=this.getQuestion(e);if(!i||!i.options[n])return;let o=this.getState(e);if(!i.multiSelect){o.selectedIndex!==n&&(o.selectedIndex=n,this.bumpRevision());return}o.selectedIndices.has(n)||o.selectedIndices.size>=i.maxSelect||(o.selectedIndices.add(n),this.bumpRevision())}selectAllOrClear(e){let n=this.getQuestion(e);if(!n||!n.multiSelect)return"cleared";let i=this.getState(e);if(i.selectedIndices.size>=n.maxSelect)return i.selectedIndices.clear(),this.bumpRevision(),"cleared";for(let o=0;o<n.options.length&&i.selectedIndices.size<n.maxSelect;o++)i.selectedIndices.add(o);return this.bumpRevision(),"filled"}setOptionNote(e,n,i){let o=this.getQuestion(e);if(!o||!o.options[n])return"cleared";let r=this.getState(e),u=w(i);return this.bumpRevision(),u?(r.optionNotes.set(n,u),o.multiSelect?r.selectedIndices.has(n)?"saved":r.selectedIndices.size>=o.maxSelect?"savedAtLimit":(r.selectedIndices.add(n),"saved"):r.selectedIndex===void 0?(r.selectedIndex=n,"saved"):r.selectedIndex===n?"saved":"savedUnselected"):(r.optionNotes.delete(n),"cleared")}setQuestionNote(e,n){let i=this.getState(e),o=w(n);return i.customText=o,this.bumpRevision(),o?"saved":"cleared"}clearOptionNote(e,n){let i=this.states.get(e);return i?.optionNotes.has(n)?(i.optionNotes.delete(n),this.bumpRevision(),!0):!1}clearQuestionNote(e){let n=this.states.get(e);return n?.customText?.trim()?(n.customText=void 0,this.bumpRevision(),!0):!1}collectOptionNotes(e,n){let i={};if(!n)return i;for(let[o,r]of n.optionNotes){let u=w(r);u&&e.options[o]&&(i[o+1]=u)}return i}compileAnswers(){let e=[];for(let[n,i]of this.questions.entries()){let o=this.states.get(n),r=o?.customText?.trim()?N(o.customText.trim()):void 0,u={questionId:i.id,questionTitle:i.title,customText:r};if(i.multiSelect){let l=this.getSelectedIndices(n),a=this.collectOptionNotes(i,o),d=[];for(let c of l){let p=i.options[c];p&&d.push({...p,customText:a[c+1]})}let m=Object.keys(a).length>0;e.push({...u,multiSelect:!0,selectedOptions:d,selectedIndices:l.map(c=>c+1),optionNotes:m?a:void 0})}else if(o?.selectedIndex!==void 0){let l=i.options[o.selectedIndex],a=this.collectOptionNotes(i,o);e.push({...u,multiSelect:!1,selectedOption:l?{...l,customText:a[o.selectedIndex+1]}:void 0,selectedOptionIndex:o.selectedIndex+1,optionNotes:Object.keys(a).length>0?a:void 0})}else if(this.isQuestionAnswered(n)){let l=this.collectOptionNotes(i,o),a=Object.keys(l).length>0;e.push({...u,multiSelect:!1,optionNotes:a?l:void 0})}}return e}formatAnswers(e){if(e.length===0)return`${s.markdown.envelopePrefix}
|
|
6
|
-
${s.markdown.envelopeEmpty}
|
|
7
|
-
${s.markdown.envelopeSuffix}`;let n=l=>l?`${s.markdown.notePrefix}${P(l)}${s.markdown.noteSuffix}`:"",i=l=>l?`${s.markdown.draftDirectivePrefix}${P(l)}${s.markdown.draftDirectiveSuffix}`:"",o=new Map(this.questions.map(l=>[l.id,l])),r=new Map(this.questions.map((l,a)=>[l.id,a])),u=e.map((l,a)=>{let d=r.get(l.questionId),c=(l.multiSelect?l.selectedOptions??[]:l.selectedOption?[l.selectedOption]:[]).map((b,x)=>{let v=ae(b.preview),O=n(w(b.customText)??""),E=l.multiSelect?l.selectedIndices?.[x]:l.selectedOptionIndex,U=P(me(b.label,E)),H=P(b.description??"");return H?s.markdown.optionWithDesc(U,H,i(v),O):s.markdown.optionWithoutDesc(U,i(v),O)}),p=o.get(l.questionId);if(p&&l.optionNotes){let b=new Set(l.multiSelect?l.selectedIndices??[]:l.selectedOptionIndex!==void 0?[l.selectedOptionIndex]:[]);for(let[x,v]of Object.entries(l.optionNotes)){let O=Number(x);if(b.has(O))continue;let E=p.options[O-1]?.label;E&&v&&c.push(s.markdown.unselectedOptionNote(P(me(E,O)),n(v)))}}l.customText&&c.push(n(l.customText));let h=c.join(s.markdown.partSeparator)||s.markdown.noSelection;return s.markdown.answerLine(a+1,P(Be(l.questionTitle,d)),h)});return`${s.markdown.envelopePrefix}
|
|
8
|
-
${u.join(`
|
|
9
|
-
`)}
|
|
10
|
-
${s.markdown.envelopeSuffix}`}};import{getMarkdownTheme as Fe}from"@earendil-works/pi-coding-agent";import{Markdown as ze}from"@earendil-works/pi-tui";function je(t){let e=Fe();return{...e,heading:n=>t.fg("accent",t.bold(n)),quote:n=>t.fg("muted",n),quoteBorder:n=>t.fg("dim",n),listBullet:n=>t.fg("accent",n),code:n=>Ue(t,n)??e.code(n),codeBlockBorder:n=>t.fg("dim",n),bold:n=>t.bold(n),italic:n=>t.italic(n),link:n=>t.fg("accent",n),linkUrl:n=>t.fg("dim",n)}}function Ue(t,e){if(!e.startsWith(B))return;let n=[],i=0;for(;i<e.length;){if(e.charAt(i)!==B)return;let o=ue.get(e.charAt(i+1));if(!o)return;let r=e.indexOf(B,i+2),u=r<0?e.length:r;n.push(o.paint(t,e.slice(i+2,u))),i=u}return n.length>0?n.join(""):void 0}var He=/^ {0,3}(`{3,}|~{3,})/,Ve=/^ {4,}\S/,Xe=/^ {0,3}(?:<(?=[/!?a-zA-Z])|\|)/,pe=/^ {0,3}(?:\$\$|\\\[)/;function fe(t){for(let e=0;e<t.length;e++){let n=t.charAt(e);if(n==="\\"){if(t.charAt(e+1)==="("||t.charAt(e+1)==="[")return!0;e++;continue}if(n!=="$")continue;let i=t.charAt(e+1);if(!(i===""||/\s/.test(i)))return!0}return!1}var We=/^(?: {0,3}>[ \t]?)+/,Ge=/^ {0,3}\[[^\]\n]*\]:/;function be(t){return t.replace(We,"")}function Ke(t){return t.includes("|")?/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/.test(be(t)):!1}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(t){let e=[],n=0;for(let i of t)e.push(n),n+=i.length+1;return e}function et(t,e,n){let i=new Uint8Array(t.length),o=(c,p)=>{for(let h=c;h<p;h++)i[h]=1},r=c=>{let p=n[c]??0;o(p,p+(e[c]?.length??0))},u=null,l=!1,a=null,d="";for(let c=0;c<e.length;c++){let p=e[c]??"";if(p.trim()===""){l=!1,u!==null&&r(c),a!==null&&r(c);continue}if(a!==null){d+=p,r(c);let v=p.indexOf(a);if(v>=0){let O=p.slice(v+a.length);a=null,fe(O)&&(l=!0)}continue}if(u!==null){r(c),u.test(p)&&(u=null);continue}if(l){r(c);continue}if(Ke(p)){r(c),l=!0;let v=e[c-1];v!==void 0&&v.includes("|")&&r(c-1);continue}let h=He.exec(p),b=h?.[1],x=p.slice(h?.[0].length??0);if(b!==void 0&&(b[0]==="~"||!x.includes("`"))){r(c);let v=b[0]??"`";u=new RegExp(`^ {0,3}${v}{${b.length},}[ \\t]*$`);continue}if(Ve.test(p)){r(c);continue}if(Xe.test(be(p))){r(c),l=!0;continue}if(Ge.test(p)){r(c);continue}if(pe.test(p)){let v=p.replace(pe,"");d=v,r(c),v.includes(v.startsWith("$$")?"$$":"\\]")||(a=v.startsWith("$$")?"$$":"\\]");continue}fe(p)&&(r(c),l=!0)}let m=0;for(;m<t.length;){if(t[m]!=="`"||i[m]===1){m++;continue}let c=0;for(;t[m+c]==="`"&&i[m+c]===0;)c++;let p=tt(t,i,m+c,c);if(p<0)return null;o(m,p+c),m=p+c}return i}function tt(t,e,n,i){for(let o=n;o<t.length;o++){if(t[o]!=="`"||e[o]===1)continue;let r=0;for(;t[o+r]==="`"&&e[o+r]===0;)r++;if(r===i&&t[o+i]!=="`")return o;o+=r-1}return-1}function nt(t,e,n,i){let o=[],r=[];for(let u=0;u<t.length;u++){if(e[u]===1)continue;let l=t[u]??"",a=le.get(l);if(a!==void 0){o.push({template:a,start:u});continue}let d=it(o,l);if(d<0)continue;let m=o[d];if(o.length=d,!m)continue;let c=u+1;if(c-m.start>m.template.maxSpanLength||Je.test(t.slice(m.start,c)))continue;let p=he(i,m.start),h=he(i,c-1);if(!ot(n,p,h))continue;let b=r[r.length-1];for(;b!==void 0&&b.startFlat>=m.start;)r.pop(),b=r[r.length-1];r.push({template:m.template,startFlat:m.start,startLine:p,startCol:m.start-(i[p]??0),endLine:h,endCol:c-(i[h]??0)})}return r}function it(t,e){for(let n=t.length-1;n>=0;n--)if(t[n]?.template.closer===e)return n;return-1}function he(t,e){let n=0,i=Math.max(0,t.length-1);for(;n<i;){let o=n+i+1>>1;(t[o]??0)<=e?n=o:i=o-1}return n}function ot(t,e,n){if(e===n)return!0;for(let i=e+1;i<=n;i++){let o=t[i]??"";if(o.trim()===""||Ye.test(o))return!1}return!0}function st(t,e){let n=[];for(let i of e)n.push(`${B}${i.template.marker}${t.slice(i.start,i.end)}`);return`\`${n.join("")}\``}function rt(t,e){let n=[],i=0,o=0;for(;o<e.length;){let r=e[o];if(!r)break;let u=[r],l=r;for(;o+1<e.length;){let h=e[o+1];if(!h||h.start!==l.end)break;o++,l=h,u.push(h)}let a=r.start,d=l.end,m=t.slice(i,a),c=t.slice(a,d),p=t.charAt(a-1)==="`"||t.charAt(d)==="`";n.push(m,p?c:st(t,u)),i=d,o++}return n.push(t.slice(i)),n.join("")}function lt(t,e,n){for(let i=e;i<n;i++)if(t[i]===1)return!0;return!1}function ut(t,e,n,i){let o=new Map;for(let r of i){let u=(e[r.startLine]??0)+r.startCol,l=(e[r.endLine]??0)+r.endCol;for(let a=r.startLine;a<=r.endLine;a++){let d=e[a]??0,m=d+(t[a]?.length??0),c=Math.max(u,d),p=Math.min(l,m);if(p<=c||lt(n,c,p))continue;let h={start:c-d,end:p-d,template:r.template},b=o.get(a);b?b.push(h):o.set(a,[h])}}return t.map((r,u)=>{let l=o.get(u);return l?(l.sort((a,d)=>a.start-d.start),rt(r,l)):r}).join(`
|
|
11
|
-
`)}function at(t){if(t.length===0)return t;let e=t.split(`
|
|
12
|
-
`),n=Ze(e),i=et(t,e,n);if(i===null)return t;let o=nt(t,i,e,n);return o.length===0?t:ut(e,n,i,o)}function ge(t,e){return`${s.view.sectionTitle(t)}
|
|
13
|
-
|
|
14
|
-
${e.map(n=>`${n}
|
|
15
|
-
`).join("")}`}function Se(t,e,n,i,o){if(!t)return[];let r="";t.type==="option"?(n&&(r+=`${s.view.sectionTitle(s.view.optionNotePanelTitle)}
|
|
16
|
-
|
|
17
|
-
${s.view.fieldLabel(s.view.customNotePanelCurrent)}
|
|
18
|
-
|
|
19
|
-
${N(n)}
|
|
20
|
-
|
|
21
|
-
`),t.description&&(r+=`${s.view.sectionTitle(s.view.storyDescriptionPanelTitle)}
|
|
22
|
-
|
|
23
|
-
${N(t.description)}
|
|
24
|
-
|
|
25
|
-
`),t.preview?r+=`${s.view.sectionTitle(s.view.storyDraftPanelTitle)}
|
|
26
|
-
|
|
27
|
-
${N(t.preview)}
|
|
28
|
-
|
|
29
|
-
`:!t.description&&!n&&(r+=`${s.view.italicLine(s.view.previewNoDraft.trim())}
|
|
30
|
-
|
|
31
|
-
`)):t.type==="custom_note"?(r+=ge(s.view.customNotePanelTitle,s.view.customNotePanelTips),e&&(r+=`
|
|
32
|
-
${s.view.fieldLabel(s.view.customNotePanelCurrent)}
|
|
33
|
-
|
|
34
|
-
${N(e)}
|
|
35
|
-
|
|
36
|
-
`)):r+=ge(s.view.confirmPanelTitle,s.view.confirmPanelTips);let u=je(o);return new ze(r.trim(),1,0,u,void 0,{transform:at}).render(i)}import{visibleWidth as ne,wrapTextWithAnsi as ct}from"@earendil-works/pi-tui";function z(t,e){return t.options[e]?.label??s.fallbacks.autoOptionLabel(e+1)}function dt(t,e,n){return t.type==="option"&&t.optionIndex!==void 0?e.multiSelect?n.selectedIndices.has(t.optionIndex):n.selectedIndex===t.optionIndex:t.type==="custom_note"?R(n):!1}function mt(t,e,n,i){return i.type!=="option"||i.optionIndex===void 0?"":e.multiSelect?n.selectedIndices.has(i.optionIndex)?t.fg("success",g.checkedMulti):t.fg("dim",g.uncheckedMulti):n.selectedIndex===i.optionIndex?t.fg("accent",g.checkedSingle):t.fg("dim",g.uncheckedSingle)}function Te(t,e,n,i,o,r){let u=dt(e,i,o),l=n?t.fg("accent",t.bold(`${g.cursor} `)):" ",a=mt(t,i,o,e),d=`${l}${a}`,m=ne(d),c=" ".repeat(m),p=Math.max(8,r-m),h=e.label;return e.type==="option"&&e.optionIndex!==void 0&&o.optionNotes.get(e.optionIndex)&&(h=`${e.label} ${g.note}`),(ne(h)<=p?[h]:ct(h,p)).map((x,v)=>{if(n){let H=v===0?`${d}${x}`:`${c}${x}`;return t.bg("selectedBg",t.fg("text",t.bold(X(H,r))))}let E=(e.type==="option"||e.type==="custom_note")&&!u?t.fg("dim",x):t.fg("text",x),U=v===0?`${d}${E}`:`${c}${E}`;return k(U,r)})}function we(t,e,n,i){let o=n===e.questionCount,r=[],u=[];for(let m=0;m<e.questionCount;m++){let c=m===n,p=e.isQuestionAnswered(m),h=p?g.checked:g.unchecked,b=p?"success":"muted",x=` ${h} ${s.tabs.questionTab(m+1)} `;u.push(c?t.bg("selectedBg",t.fg("accent",t.bold(x))):t.fg(b,x))}let l=` ${s.tabs.submitTab} `;u.push(o?t.bg("selectedBg",t.fg("success",t.bold(l))):t.fg(e.areAllQuestionsAnswered()?"success":"dim",l));let a="",d=0;for(let m of u){let c=ne(m);d>0&&d+1+c>i?(r.push(k(a,i)),a="",d=0):d>0&&(a+=" ",d+=1),a+=m,d+=c}return r.push(k(a,i)),r.push(t.fg("dim",ee(i))),r}function pt(t){return t.join(s.common.helpSeparator)}function ie(t,e,n,i){A(t,n.fg("dim",pt(e)),i," ")}function j(t,e,n){t.push(e.fg("accent",ee(n,y.dividerThick)))}function ve(t){return[s.help.switchQuestion,...t.questionCount>1?[s.help.jumpQuestion]:[],s.help.scrollSummary,s.help.confirmSubmit,s.help.cancel]}function ye(t,e,n){let i=[];for(let o=0;o<t.questionCount;o++){let r=t.getQuestion(o);if(!r)continue;let u=t.isQuestionAnswered(o),l=t.getState(o),a=u?e.fg("success",s.summary.statusDone):e.fg("warning",s.summary.statusPending);A(i,`${a} ${e.bold(s.summary.questionPrefix(o+1,r.title))}`,n," ");let d=[];if(r.multiSelect)for(let c of t.getSelectedIndices(o)){let p=r.options[c];if(!p)continue;let h=l.optionNotes.get(c);d.push(h?`${p.label} ${s.summary.optionNoteBadge}`:p.label)}else if(l.selectedIndex!==void 0){let c=r.options[l.selectedIndex];if(c){let p=l.optionNotes.get(l.selectedIndex);d.push(p?`${c.label} ${s.summary.optionNoteBadge}`:c.label)}}let m=d.length?e.fg("accent",d.join(s.common.optionSeparator)):e.fg("dim",s.fallbacks.unselectedOption);A(i,`${e.fg("muted",s.summary.selectedLabel)} ${m}`,n," ");for(let[c,p]of l.optionNotes.entries()){let h=r.options[c];h&&p?.trim()&&A(i,`${e.fg("muted",s.summary.optionNotePrefix(h.label))} ${e.fg("accent",p)}`,n," ")}l.customText&&A(i,`${e.fg("muted",s.summary.customNoteLabel)} ${e.fg("accent",l.customText)}`,n," "),i.push("")}return i}var gt=32,W=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,n,i,o){this.tui=e,this.theme=n,this.model=i,this.done=o;let r={borderColor:u=>this.theme.fg("accent",u),selectList:{selectedPrefix:u=>this.theme.fg("accent",u),selectedText:u=>this.theme.fg("accent",u),description:u=>this.theme.fg("muted",u),scrollInfo:u=>this.theme.fg("dim",u),noMatch:u=>this.theme.fg("warning",u)}};this.editor=new ft(this.tui,r),this.editor.focused=!1,this.editor.onSubmit=u=>{let l=this.editTarget;if(!l){this.closeEditor();return}if(l.type==="option"){let a=this.model.getQuestion(this.currentTab),d=l.optionIndex,m=a?z(a,d):s.fallbacks.autoOptionLabel(d+1),c=this.model.setOptionNote(this.currentTab,d,u);c==="cleared"?this.setStatus(s.status.optionNoteCleared(m)):c==="savedAtLimit"&&a?this.setStatus(s.status.optionNoteSavedAtLimit(a.maxSelect)):c==="savedUnselected"?this.setStatus(s.status.optionNoteSavedUnselected(m)):this.setStatus(s.status.optionNoteSaved(m))}else{let a=this.model.setQuestionNote(this.currentTab,u);this.setStatus(a==="saved"?s.status.questionNoteSaved:s.status.noteCleared)}this.touchDerived(),this.closeEditor()}}bindAbortSignal(e){if(!e||this.abortBinding||this.disposed)return;if(e.aborted){queueMicrotask(()=>this.finish(!0));return}let n=()=>this.finish(!0);e.addEventListener("abort",n,{once:!0}),this.abortBinding={signal:e,onAbort:n}}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 typeof e=="number"&&e>0?e:24}get summaryPageSize(){return I(this.terminalRows-10,4,y.summaryPageSize)}get splitPreviewHeight(){return I(this.terminalRows-14,6,y.splitPreviewHeight)}get singlePreviewHeight(){return I(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 n=this.model.getMenuItems(this.currentTab);return this.menuCache={tab:this.currentTab,revision:this.model.revision,items:n},n}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 n=this.model.getState(this.currentTab);this.currentOptionIndex=this.cursorByTab.get(this.currentTab)??n.selectedIndex??0,this.adjustScrollForCurrentOption()}this.touch()}}adjustScrollForCurrentOption(){let e=this.getMenuItems().length;e!==0&&(this.currentOptionIndex=I(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 n=this.getMenuItems().length;if(n===0)return;let i=typeof e=="number"?e:this.currentOptionIndex+e.delta,o=I(i,0,n-1);o!==this.currentOptionIndex&&(this.currentOptionIndex=o,this.cursorByTab.set(this.currentTab,o),this.previewScrollOffset=0,this.adjustScrollForCurrentOption(),this.touch())}getEditTargetForCurrentSelection(){let e=this.currentMenuItem();return e?.type==="option"&&e.optionIndex!==void 0?{type:"option",optionIndex:e.optionIndex}:{type:"question"}}openCustomEditor(e){let n=this.model.getQuestion(this.currentTab);if(!n||!n.allowCustom)return;let i=this.model.getState(this.currentTab),o=e??this.getEditTargetForCurrentSelection();this.editTarget=o,this.inputMode=!0,this.editorEscArmed=!1;let r=o.type==="option"?i.optionNotes.get(o.optionIndex)??"":i.customText??"";this.editor.setText(r),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,n){if(e.type==="option"&&e.optionIndex!==void 0&&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);return}this.setStatus(n.multiSelect?s.status.minSelectRequired(n.minSelect):s.status.pleaseAnswerBeforeSubmit)}handleInput(e){if(this.isFinished||this.disposed)return;let n=T(e,S.escape)||T(e,S.ctrl("c"));if(this.inputMode){if(n){if(this.editor.getText()!==""&&!this.editorEscArmed){this.editorEscArmed=!0,this.setStatus(s.status.editorDiscardConfirm);return}this.closeEditor();return}this.editorEscArmed&&(this.editorEscArmed=!1,this.statusMessage=null),this.editor.handleInput(e),this.touch();return}if(n){this.finish(!0);return}if(/^[1-9]$/.test(e)){let i=parseInt(e,10)-1;if(i<this.model.questionCount){this.switchTab(i);return}}if(T(e,S.tab)||T(e,S.right)||e==="l"){this.switchTab((this.currentTab+1)%this.totalTabs);return}if(T(e,S.shift("tab"))||T(e,S.left)||e==="h"){this.switchTab((this.currentTab-1+this.totalTabs)%this.totalTabs);return}this.isSubmitTab?this.handleSummaryInput(e):this.handleQuestionInput(e)}handleQuestionInput(e){let n=this.model.getQuestion(this.currentTab);if(!n||this.handleNoteShortcut(n,e)||this.handlePreviewScroll(e)||this.handleCursorNavigation(e)||this.handleSelectAllShortcut(n,e))return;let i=this.currentMenuItem();if(i){if(T(e,S.ctrl("s"))){this.confirmAndAdvance(i,n);return}if(T(e,S.space)){this.activateMenuItem(i,n);return}T(e,S.enter)&&(i.type==="custom_note"?this.openCustomEditor({type:"question"}):this.confirmAndAdvance(i,n))}}handleNoteShortcut(e,n){if(!e.allowCustom)return!1;if(n==="N")return this.openCustomEditor({type:"question"}),!0;if(n==="n"||n==="e")return this.openCustomEditor(),!0;if(n==="x"||T(n,S.delete)){let i=this.currentMenuItem();if(i?.type==="option"&&i.optionIndex!==void 0){let o=i.optionIndex;if(this.model.clearOptionNote(this.currentTab,o))return this.setStatus(s.status.optionNoteCleared(z(e,o))),!0}if(this.model.clearQuestionNote(this.currentTab))return this.setStatus(s.status.noteCleared),!0}return!1}handlePreviewScroll(e){let n=0;if(T(e,S.pageUp)||e==="["||T(e,S.alt("up"))?n=-y.previewScrollStep:(T(e,S.pageDown)||e==="]"||T(e,S.alt("down")))&&(n=y.previewScrollStep),n===0)return!1;let i=this.previewViewportObservation,o=i?.viewHeight??this.singlePreviewHeight,r=i?.total??0;return this.previewScrollOffset=L(this.previewScrollOffset+n,r,o),this.touch(),!0}handleCursorNavigation(e){return T(e,S.up)||e==="k"?(this.moveCursor({delta:-1}),!0):T(e,S.down)||e==="j"?(this.moveCursor({delta:1}),!0):T(e,S.home)?(this.moveCursor(0),!0):T(e,S.end)?(this.moveCursor(Number.MAX_SAFE_INTEGER),!0):!1}handleSelectAllShortcut(e,n){return!e.multiSelect||n!=="a"?!1:(this.model.selectAllOrClear(this.currentTab)==="filled"&&e.maxSelect<e.options.length?this.setStatus(s.status.selectedUpToLimit(e.maxSelect)):this.touch(),!0)}activateMenuItem(e,n){if(e.type==="option"&&e.optionIndex!==void 0){this.model.toggleOption(this.currentTab,e.optionIndex)==="limit"?this.setStatus(s.status.maxSelectExceeded(n.maxSelect)):this.touch();return}if(e.type==="custom_note"){this.openCustomEditor({type:"question"});return}this.confirmAndAdvance(e,n)}handleSummaryInput(e){if(T(e,S.enter)||T(e,S.ctrl("s"))){if(this.model.areAllQuestionsAnswered())this.finish(!1);else{let u=this.model.questions.findIndex((l,a)=>!this.model.isQuestionAnswered(a));if(u!==-1){this.switchTab(u);let l=this.model.getQuestion(u);l&&this.setStatus(l.multiSelect?s.status.minSelectRequired(l.minSelect):s.status.pleaseAnswerBeforeSubmit)}}return}if(T(e,S.home)){this.summaryScrollOffset=0,this.touch();return}if(T(e,S.end)){this.summaryScrollOffset=Number.MAX_SAFE_INTEGER,this.touch();return}let n=this.summaryScrollStep(e);if(n===0&&T(e,S.space)&&(n=y.summaryScrollStep),n===0)return;let i=this.summaryCachedLines?.lines.length??0,o=this.summaryPageSize,r=L(this.summaryScrollOffset,i,o);this.summaryScrollOffset=L(r+n,i,o),this.touch()}summaryScrollStep(e){return T(e,S.pageUp)||e==="["||T(e,S.alt("up"))?-y.summaryScrollStep:T(e,S.pageDown)||e==="]"||T(e,S.alt("down"))?y.summaryScrollStep:T(e,S.up)||e==="k"?-1:T(e,S.down)||e==="j"?1:0}render(e){let n=Math.max(20,e),i=this.terminalRows;if(this.cachedLines&&this.cachedWidth===e&&this.cachedLayoutWidth===n&&this.cachedHeight===i)return this.cachedLines;let o=[];j(o,this.theme,n);let r=`${this.currentTab}_${this.model.revision}_${n}`;return(!this.tabCache||this.tabCache.key!==r)&&(this.tabCache={key:r,lines:we(this.theme,this.model,this.currentTab,n)}),o.push(...this.tabCache.lines),this.isSubmitTab?this.renderSubmitSummary(o,n):this.inputMode?this.renderInputMode(o,n):this.renderQuestionView(o,n),this.cachedWidth=e,this.cachedLayoutWidth=n,this.cachedHeight=i,this.cachedLines=o.map(u=>k(u,e)),this.cachedLines}pushStatusMessage(e){this.statusMessage&&(e.push(""),e.push(` ${this.theme.fg("warning",this.statusMessage)}`))}renderSubmitSummary(e,n){e.push(this.theme.fg("accent",this.theme.bold(s.summary.title))),e.push("");let i=n-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,r=o.length,u=this.summaryPageSize,l=L(this.summaryScrollOffset,r,u);l>0&&e.push(this.theme.fg("dim",s.summary.topMore(l)));for(let m of Z(o,l,u))e.push(m);let a=r-(l+u);a>0&&e.push(this.theme.fg("dim",s.summary.bottomMore(a))),e.push("");let d=this.model.areAllQuestionsAnswered()?this.theme.fg("success",this.theme.bold(s.summary.allDonePrompt)):this.theme.fg("warning",s.summary.pendingWarning);A(e,d,i),this.pushStatusMessage(e),e.push(""),ie(e,ve(this.model),this.theme,n),j(e,this.theme,n)}renderInputMode(e,n){let i=this.model.getQuestion(this.currentTab);if(i){if(this.editTarget?.type==="option"){let o=this.editTarget.optionIndex,r=i.options[o],u=z(i,o),l=r?.customPlaceholder??s.fallbacks.defaultOptionCustomPlaceholder;e.push(this.theme.fg("accent",this.theme.bold(s.editor.optionTitle(i.title,u)))),r?.description&&A(e,this.theme.fg("muted",r.description),n," "),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),n," "),e.push(""),e.push(this.theme.fg("accent",` ${i.customPlaceholder}`));e.push("");for(let o of this.editor.render(Math.max(10,n-4)))e.push(` ${o}`);e.push(""),e.push(this.theme.fg("dim",s.editor.footerHelp)),j(e,this.theme,n)}}renderQuestionView(e,n){let i=this.model.getQuestion(this.currentTab);if(!i)return;let o=this.model.getState(this.currentTab),r=this.getMenuItems(),u=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);A(e,` ${u} ${this.theme.bold(i.title)}`,n),i.description&&A(e,this.theme.fg("muted",i.description),n," "),o.customText?.trim()&&A(e,this.theme.fg("success",s.view.attachedNoteBanner(o.customText)),n," ");let l=this.currentMenuItem();if(l?.type==="option"&&l.optionIndex!==void 0){let c=o.optionNotes.get(l.optionIndex)?.trim();if(c){let p=z(i,l.optionIndex);A(e,this.theme.fg("success",s.view.optionAttachedNoteBanner(p,c)),n," ")}}e.push("");let a=i.options.some((c,p)=>!!c.preview||ht(c.description??"")>30||!!o.optionNotes.get(p));n>=y.splitViewMinWidth&&a?this.renderSplitView(e,i,o,r,n):this.pushListItems(e,r,i,o,n-2,a),this.pushStatusMessage(e),e.push("");let d=[s.help.switchQuestion];this.model.questionCount>1&&d.push(s.help.jumpQuestion),d.push(s.help.moveCursor),l?.type==="option"?(d.push(s.help.editOptionNote),d.push(s.help.editQuestionNote)):d.push(s.help.editNote),(l?.type==="option"&&l.optionIndex!==void 0&&o.optionNotes.has(l.optionIndex)||R(o))&&d.push(s.help.clearNote),d.push(i.multiSelect?s.help.toggleCheckMulti:s.help.selectOptionSingle),i.multiSelect&&(d.push(s.help.toggleAll),d.push(s.help.confirmQuestion)),a&&d.push(s.help.scrollDraft),d.push(s.help.cancel),ie(e,d,this.theme,n),j(e,this.theme,n)}previewContentLines(e,n,i,o){if(!e)return[];let r=[this.currentTab,e.type,e.optionIndex??-1,o,n??"",i??""].join(""),u=this.previewCache.get(r);if(u)return u;let l=Se(e,n,i,o,this.theme);if(this.previewCache.size>=gt){let a=this.previewCache.keys().next();a.done||this.previewCache.delete(a.value)}return this.previewCache.set(r,l),l}buildPreviewBox(e,n,i,o,r){let u=this.previewContentLines(e,n,i,o),l=u.length;return this.previewViewportObservation={total:l,viewHeight:r},this.slicePreviewBoxLines(u,L(this.previewScrollOffset,l,r),r,o)}slicePreviewBoxLines(e,n,i,o){let r=e.length,u=L(n,r,i),l=Z(e,u,i).map(a=>k(a,o));if(r>i){let a=s.view.previewScrollInfo(u+1,Math.min(r,u+i),r);l.push(k(` ${this.theme.fg("dim",a)}`,o))}return l}renderSplitView(e,n,i,o,r){let u=I(Math.floor(r*y.leftColRatio),y.leftColMin,y.leftColMax),l=Math.max(20,r-u-y.dividerWidth),a=`${this.currentTab}_${this.currentOptionIndex}_${this.listScrollOffset}_${this.model.revision}_${u}`,d;this.leftColCache&&this.leftColCache.key===a?d=this.leftColCache.lines:(d=[],this.pushListItems(d,o,n,i,u,!1),this.leftColCache={key:a,lines:d});let m=o[this.currentOptionIndex],c=m?.type==="option"&&m.optionIndex!==void 0?i.optionNotes.get(m.optionIndex):void 0,p=this.buildPreviewBox(m,i.customText,c,l,this.splitPreviewHeight),h=Math.max(d.length,p.length);for(let b=0;b<h;b++){let x=d[b]??"",v=p[b]??"";e.push(`${X(x,u)}${this.theme.fg("dim",y.dividerChar)}${k(v,l)}`)}}pushListItems(e,n,i,o,r,u){this.listScrollOffset>0&&e.push(this.theme.fg("dim",s.view.listTopMore(this.listScrollOffset)));let l=n.slice(this.listScrollOffset,this.listScrollOffset+y.visibleOptionCount);for(let[d,m]of l.entries()){if(!m)continue;let c=this.listScrollOffset+d,p=c===this.currentOptionIndex,h=n[c-1];if(h&&h.type==="option"&&m.type!=="option"&&e.push(""),e.push(...Te(this.theme,m,p,i,o,r)),p&&u&&(m.type!=="option"||m.description||m.preview||o.optionNotes.has(m.optionIndex??-1))){e.push("");let b=m.type==="option"&&m.optionIndex!==void 0?o.optionNotes.get(m.optionIndex):void 0,x=this.buildPreviewBox(m,o.customText,b,Math.max(10,r-2),this.singlePreviewHeight);for(let v of x)e.push(v);e.push("")}}let a=n.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}))}),bt=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:M}),allowCustom:f.Optional(f.Boolean({description:s.schema.questionAllowCustom})),customPlaceholder:f.Optional(f.String({description:s.schema.questionCustomPlaceholder}))}),oe=f.Object({formTitle:f.String({description:s.schema.formTitle}),description:f.Optional(f.String({description:s.schema.formDesc})),questions:f.Optional(f.Array(bt,{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:M})),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 K(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function St(t){let e=F(t.raw);return K(e)?e:(delete t.raw,t)}function C(t,e){for(let n of e){let i=t[n];if(typeof i=="string")return i}}function q(t,e){if(typeof t=="boolean")return t;if(t===1)return!0;if(t===0)return!1;if(typeof t=="string"){let n=t.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1}return e}function Ae(t){if(typeof t=="number"&&Number.isFinite(t))return Math.floor(t);if(typeof t=="string"){let e=parseInt(t.trim(),10);return Number.isFinite(e)?e:void 0}}function Ce(t){let e=Ae(t);return e===void 0?void 0:Math.max(0,e)}function Ie(t){let e=Ae(t);return e!==void 0&&e>=1?e:void 0}function Ne(t){let e=F(t);return Array.isArray(e)?e.slice(0,M).map((n,i)=>{if(typeof n=="string")return{label:n.trim()||s.fallbacks.autoOptionLabel(i+1)};if(!K(n))return{label:s.fallbacks.autoOptionLabel(i+1)};let o=n;return{label:w(C(o,["label","name","title","text","value","choice"]))??s.fallbacks.autoOptionLabel(i+1),description:w(C(o,["description","desc","reason","rationale","deduction"])),preview:w(C(o,["preview","draft","scene","content"])),customPlaceholder:w(C(o,["customPlaceholder","placeholder"]))}}):[]}function Tt(t){return typeof t!="object"||t===null||"questions"in t?!1:"options"in t||"choices"in t||"items"in t||"question"in t||"prompt"in t}function wt(t,e){if(typeof t=="string")return{title:t,options:G([])};if(!K(t))return{title:s.fallbacks.autoQuestionTitle(e+1),options:G([])};let n=t;return{id:C(n,["id"]),title:w(C(n,["title","question","prompt","query","heading"]))??s.fallbacks.autoQuestionTitle(e+1),description:w(C(n,["description","desc","rationale"])),multiSelect:q(n.multiSelect,!1),minSelect:Ce(n.minSelect),maxSelect:Ie(n.maxSelect),allowEmpty:q(n.allowEmpty,!1),options:G(Ne(n.options??n.choices??n.items)),allowCustom:q(n.allowCustom,!0),customPlaceholder:C(n,["customPlaceholder","placeholder"])}}function vt(t){if(t===void 0)return;let e=F(t),n=Array.isArray(e)?e:Tt(e)?[e]:[];if(n.length!==0)return n.slice(0,D).map((i,o)=>wt(i,o))}function G(t){return t.length>0?t:[{label:s.fallbacks.defaultOptionLabel}]}function yt(t,e,n,i){return typeof t=="string"?t:typeof e=="string"?e:i?n:void 0}function Y(t){let e=t&&typeof t=="object"?t:F(t);if(!K(e))return{formTitle:s.fallbacks.defaultFormTitle};let n=St({...e}),i=w(C(n,["title","taskTitle"])),o=w(C(n,["formTitle"]))??i??s.fallbacks.defaultFormTitle,r=vt(n.questions??n.form??n.survey),u=n.options??n.choices??n.items,l=n.options!==void 0||n.choices!==void 0||n.items!==void 0,a=l?G(Ne(u)):void 0,d=yt(n.question,n.prompt,i,l),m=C(n,["description"]),c=n.multiSelect===void 0?void 0:q(n.multiSelect,!1),p=n.minSelect===void 0?void 0:Ce(n.minSelect),h=n.maxSelect===void 0?void 0:Ie(n.maxSelect),b=n.allowEmpty===void 0?void 0:q(n.allowEmpty,!1),x=n.allowCustom===void 0?void 0:q(n.allowCustom,!0),v=C(n,["customPlaceholder"]);return{formTitle:o,description:m,questions:r,question:d,multiSelect:c,minSelect:p,maxSelect:h,allowEmpty:b,options:a,allowCustom:x,customPlaceholder:v}}function xt(t){return t instanceof Error?t.message:String(t)}function Me(t={}){return{formTitle:t.formTitle??s.fallbacks.defaultFormTitle,formDescription:t.formDescription,questions:t.questions??[]}}function _(t,e){let n=e instanceof ke?e:new ke("",0,0);return n.setText(t),n}function $e(t={}){let{formTitle:e,formDescription:n,questions:i}=Me(t);return{content:[{type:"text",text:s.markdown.envelopeCancelled}],details:{formTitle:e,formDescription:n,questions:i,answers:[],cancelled:!0}}}function se(t,e,n,i={}){let{formTitle:o,formDescription:r,questions:u}=Me(i);return{content:[{type:"text",text:s.markdown.envelopeError(t,e)}],details:{formTitle:o,formDescription:r,questions:u,answers:[],cancelled:!1,error:n}}}function Ee(t,e={}){let n=xt(t);return se(s.markdown.errorReasons.runtimeError(n),s.markdown.errorGuidances.runtimeError,s.status.errorExecutionFailed(n),e)}function At(t,e){return{content:[{type:"text",text:t.formatAnswers(e)}],details:{formTitle:t.formTitle,formDescription:t.formDescription,questions:t.questions,answers:e,cancelled:!1}}}function Ct(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`ask_author \u7ED3\u679C\u8BE6\u60C5\u5E94\u4E3A\u666E\u901A\u5BF9\u8C61\uFF0C\u5B9E\u9645\u6536\u5230 ${JSON.stringify(t)}`);if(!("cancelled"in t)||!("answers"in t)||!("questions"in t)||!("formTitle"in t))throw new Error("ask_author \u7ED3\u679C\u8BE6\u60C5\u7F3A\u5C11 cancelled/answers/questions/formTitle \u5B57\u6BB5");if(typeof t.cancelled!="boolean")throw new Error("ask_author \u7ED3\u679C\u8BE6\u60C5\u7684 cancelled \u5B57\u6BB5\u5E94\u4E3A\u5E03\u5C14\u503C");if(!Array.isArray(t.answers)||!Array.isArray(t.questions))throw new Error("ask_author \u7ED3\u679C\u8BE6\u60C5\u7684 answers/questions \u5B57\u6BB5\u5E94\u4E3A\u6570\u7EC4");if(typeof t.formTitle!="string")throw new Error("ask_author \u7ED3\u679C\u8BE6\u60C5\u7684 formTitle \u5B57\u6BB5\u5E94\u4E3A\u5B57\u7B26\u4E32");return t}function It(t){let e=t.customText?s.card.questionNoteTag(t.customText):"",n=(i,o)=>o?s.card.optionWithNote(i,o):i;return t.multiSelect?((t.selectedOptions??[]).map(o=>n(o.label,o.customText)).join(s.common.optionSeparator)||s.fallbacks.unselectedOption)+e:t.selectedOption?n(t.selectedOption.label,t.selectedOption.customText)+e:t.customText||s.fallbacks.unselectedOption}function Nt(t,e){if(e.cachedArgs===t&&e.cachedCard)return e.cachedCard;let n=new Q(Y(t)),i=n.questions.reduce((r,u)=>r+u.options.length,0),o={title:n.formTitle,countLabel:n.questions.length>1?s.card.callQuestionAndOptionCount(n.questions.length,i):s.card.callOptionCountOnly(i)};return e.cachedArgs=t,e.cachedCard=o,o}function Ot(t){t.registerTool({name:s.tool.name,label:s.tool.label,description:s.tool.description,promptSnippet:s.tool.promptSnippet,promptGuidelines:[...s.tool.promptGuidelines],parameters:oe,executionMode:"sequential",prepareArguments:Y,async execute(e,n,i,o,r){let u=w(n?.formTitle)??s.fallbacks.defaultFormTitle;if(i?.aborted)return $e({formTitle:u});if(r.mode!=="tui")return se(s.markdown.errorReasons.nonTui,s.markdown.errorGuidances.nonTui,s.status.errorNonTui,{formTitle:u});let l;try{l=new Q(n)}catch(d){return Ee(d,{formTitle:u})}if(l.questions.length===0)return se(s.markdown.errorReasons.noQuestions,s.markdown.errorGuidances.noQuestions,s.status.errorNoQuestions,{questions:[],formTitle:l.formTitle,formDescription:l.formDescription});let a;try{let d=await r.ui.custom((m,c,p,h)=>(a=new W(m,c,l,h),a.bindAbortSignal(i),a));return!d||d.cancelled?$e({questions:d?.questions??l.questions,formTitle:d?.formTitle??l.formTitle,formDescription:d?.formDescription??l.formDescription}):At(l,d.answers)}catch(d){return Ee(d,{questions:l.questions,formTitle:l.formTitle,formDescription:l.formDescription})}finally{a?.dispose()}},renderCall(e,n,i){let o=Nt(e,i.state),r=n.fg("accent",s.tool.label),u=`${n.bold(o.title)} ${n.fg("muted",`(${o.countLabel})`)}`;return _(`${r} ${u}`,i.lastComponent)},renderResult(e,{expanded:n},i,o){let r=Ct(e.details);if(r.error){let a=`${i.fg("error",i.bold(s.card.resultErrorShort))} ${i.fg("muted",`${s.common.bulletPrefix}${r.error}`)}`;return _(n?`${a}
|
|
37
|
-
${s.card.errorBullet(i.fg("error",r.error))}`:`${a} (${Oe("app.tools.expand",s.card.expandHint)})`,o.lastComponent)}if(r.cancelled)return _(i.fg("warning",s.card.resultCancelled),o.lastComponent);let u=`${i.fg("success",i.bold(s.card.resultCompleted))} ${i.fg("muted",`${s.common.bulletPrefix}${s.card.resultCount(r.answers.length)}`)}`;if(!n)return _(`${u} (${Oe("app.tools.expand",s.card.expandHint)})`,o.lastComponent);let l=[u,...r.answers.map(a=>s.card.optionBullet(i.bold(a.questionTitle),i.fg("accent",It(a))))];return _(l.join(`
|
|
38
|
-
`),o.lastComponent)}}),t.registerCommand(s.command.name,{description:s.command.description,handler:async(e,n)=>{n.ui.notify(s.command.notify,"info")}})}export{Q as AskAuthorFormModel,oe as AskAuthorParams,g as ICONS,y as LAYOUT_CONFIG,s as TEXTS,Ot as askAuthorExtension,Ot as default,Y as sanitizeAskAuthorArgs};
|
|
1
|
+
import{keyHint as Oe}from"@earendil-works/pi-coding-agent";import{Text as ke}from"@earendil-works/pi-tui";import{Editor as ft,Key as S,matchesKey as T,visibleWidth as ht}from"@earendil-works/pi-tui";import{truncateToWidth as J,visibleWidth as V,wrapTextWithAnsi as Le}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},g={cancel:"",check:"",checked:"",unchecked:"",error:"",note:"",cursor:"",scrollUp:"",scrollDown:"",checkedMulti:"[] ",uncheckedMulti:"[ ] ",checkedSingle:"(•) ",uncheckedSingle:"( ) "},M=30,D=20,B="\0",re=[{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))}],le=new Map(re.map(e=>[e.opener,e])),ue=new Map(re.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-${M}, 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-${M}, 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:`${g.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=>`${g.note} 题目补充说明:${e}`,optionAttachedNoteBanner:(e,t)=>`${g.note} [${e}] 选项补充说明:${t}`,listTopMore:e=>` ${g.scrollUp} 向上还有 ${e} 项`,listBottomMore:e=>` ${g.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:`${g.note} 题目补充说明`,customNoteLabelFilled:`${g.note} 题目补充说明 (已填写)`,confirmDetailMulti:(e,t)=>`已选 ${e}${e<t?`/${t}`:""} 项`,confirmLabel:(e,t)=>`${g.check} 确认本题 (${e}${t?" + 补充说明":""})`,confirmDesc:"确认并前往下一题或总览页"},editor:{title:e=>` ${g.note} 填写题目补充说明(${e})`,optionTitle:(e,t)=>` ${g.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:`(${g.note} 批注)`,optionNotePrefix:e=>`${g.note} 选项补充说明(${e}):`,customNoteLabel:`${g.note} 题目补充说明:`,allDonePrompt:` ${g.check} 全部完成,按 Enter/Ctrl+S 提交答卷,Tab/hl/1-9 返回修改`,pendingWarning:` ${g.unchecked} 尚有题目未完成,按 Enter 前往作答,Tab/hl/1-9 切换修改`,topMore:e=>` ${g.scrollUp} 向上还有 ${e} 行`,bottomMore:e=>` ${g.scrollDown} 向下还有 ${e} 行`},card:{callQuestionAndOptionCount:(e,t)=>`${e} 题 • ${t} 选项`,callOptionCountOnly:e=>`${e} 选项`,resultCancelled:`${g.cancel} 已取消`,resultErrorShort:`${g.error} 执行失败`,resultCompleted:`${g.check} 已完成`,resultCount:e=>`${e} 项`,expandHint:"展开查看明细",optionBullet:(e,t)=>`${$}${e}:${t}`,optionWithNote:(e,t)=>`${e} [${g.note} ${t}]`,questionNoteTag:e=>` (${g.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 I(e,t,i){return Math.max(t,Math.min(e,i))}function L(e,t,i){return I(e,0,Math.max(0,t-i))}function Z(e,t,i){return e.slice(t,t+i)}function N(e){return e?e.replace(/\t/g," ").replace(/\r/g,""):""}function Pe(e){return e.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/\x1b[@-_]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function w(e){let t=e?.trim();return t&&Pe(N(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=V(e);s>=i&&i>0&&(e=J(e,i-1),s=V(e));let o=Math.max(1,i-s),n=" ".repeat(s),r=Le(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 k(e,t){if(t<=0)return"";let i=N(e);return V(i)>t?J(i,t):i}function X(e,t){if(t<=0)return"";let i=N(e),s=V(i);return s>=t?J(i,t):i+" ".repeat(t-s)}function ee(e,t=y.dividerThin){return e>0?t.repeat(e):""}function ae(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(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 te(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=I(e??1,0,i);return{minSelect:o,minSelectExplicit:s,maxSelect:I(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=te(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&&te(i);let s=i.selectedIndices.size;return!!(s>=t.minSelect||0===s&&t.allowEmpty||!t.minSelectExplicit&&0===s&&t.allowCustom&&te(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()?N(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),bold:t=>e.bold(t),italic:t=>e.italic(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=ue.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 He=/^ {0,3}(`{3,}|~{3,})/,Ve=/^ {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 We=/^(?: {0,3}>[ \t]?)+/,Ge=/^ {0,3}\[[^\]\n]*\]:/;function be(e){return e.replace(We,"")}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=He.exec(i),o=s?.[1],c=i.slice(s?.[0].length??0);if(void 0===o||"~"!==o[0]&&c.includes("`"))if(Ve.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=le.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${N(i)}\n\n`),e.description&&(r+=`${s.view.sectionTitle(s.view.storyDescriptionPanelTitle)}\n\n${N(e.description)}\n\n`),e.preview?r+=`${s.view.sectionTitle(s.view.storyDraftPanelTitle)}\n\n${N(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${N(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 ne,wrapTextWithAnsi as ct}from"@earendil-works/pi-tui";function z(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",g.checkedMulti):e.fg("dim",g.uncheckedMulti):i.selectedIndex===s.optionIndex?e.fg("accent",g.checkedSingle):e.fg("dim",g.uncheckedSingle)}function Te(e,t,i,s,o,n){let r=dt(t,s,o),l=`${i?e.fg("accent",e.bold(`${g.cursor} `)):" "}${mt(e,s,o,t)}`,a=ne(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} ${g.note}`),(ne(d)<=c?[d]:ct(d,c)).map((s,o)=>{if(i)return e.bg("selectedBg",e.fg("text",e.bold(X(0===o?`${l}${s}`:`${u}${s}`,n))));let a=e.fg("option"!==t.type&&"custom_note"!==t.type||r?"text":"dim",s);return k(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?g.checked:g.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=ne(e);c>0&&c+1+t>o?(r.push(k(u,o)),u="",c=0):c>0&&(u+=" ",c+=1),u+=e,c+=t}return r.push(k(u,o)),r.push(e.fg("dim",ee(o))),r}function pt(e){return e.join(s.common.helpSeparator)}function ie(e,t,i,s){A(e,i.fg("dim",pt(t)),s," ")}function j(e,t,i){e.push(t.fg("accent",ee(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 gt=32,W=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,this.editor=new ft(this.tui,{borderColor:e=>this.theme.fg("accent",e),selectList:{selectedPrefix:e=>this.theme.fg("accent",e),selectedText:e=>this.theme.fg("accent",e),description:e=>this.theme.fg("muted",e),scrollInfo:e=>this.theme.fg("dim",e),noMatch:e=>this.theme.fg("warning",e)}}),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?z(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 I(this.terminalRows-10,4,y.summaryPageSize)}get splitPreviewHeight(){return I(this.terminalRows-14,6,y.splitPreviewHeight)}get singlePreviewHeight(){return I(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=I(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=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),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=T(e,S.escape)||T(e,S.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)}T(e,S.tab)||T(e,S.right)||"l"===e?this.switchTab((this.currentTab+1)%this.totalTabs):T(e,S.shift("tab"))||T(e,S.left)||"h"===e?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(T(e,S.ctrl("s")))return void this.confirmAndAdvance(i,t);if(T(e,S.space))return void this.activateMenuItem(i,t);T(e,S.enter)&&("custom_note"===i.type?this.openCustomEditor({type:"question"}):this.confirmAndAdvance(i,t))}}handleNoteShortcut(e,t){if(!e.allowCustom)return!1;if("N"===t)return this.openCustomEditor({type:"question"}),!0;if("n"===t||"e"===t)return this.openCustomEditor(),!0;if("x"===t||T(t,S.delete)){let t=this.currentMenuItem();if("option"===t?.type&&void 0!==t.optionIndex){let i=t.optionIndex;if(this.model.clearOptionNote(this.currentTab,i))return this.setStatus(s.status.optionNoteCleared(z(e,i))),!0}if(this.model.clearQuestionNote(this.currentTab))return this.setStatus(s.status.noteCleared),!0}return!1}handlePreviewScroll(e){let t=0;if(T(e,S.pageUp)||"["===e||T(e,S.alt("up"))?t=-y.previewScrollStep:(T(e,S.pageDown)||"]"===e||T(e,S.alt("down")))&&(t=y.previewScrollStep),0===t)return!1;let i=this.previewViewportObservation,s=i?.viewHeight??this.singlePreviewHeight;return this.previewScrollOffset=L(this.previewScrollOffset+t,i?.total??0,s),this.touch(),!0}handleCursorNavigation(e){return T(e,S.up)||"k"===e?(this.moveCursor({delta:-1}),!0):T(e,S.down)||"j"===e?(this.moveCursor({delta:1}),!0):T(e,S.home)?(this.moveCursor(0),!0):!!T(e,S.end)&&(this.moveCursor(Number.MAX_SAFE_INTEGER),!0)}handleSelectAllShortcut(e,t){return!(!e.multiSelect||"a"!==t||("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(T(e,S.enter)||T(e,S.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(T(e,S.home))return this.summaryScrollOffset=0,void this.touch();if(T(e,S.end))return this.summaryScrollOffset=Number.MAX_SAFE_INTEGER,void this.touch();let t=this.summaryScrollStep(e);if(0===t&&T(e,S.space)&&(t=y.summaryScrollStep),0===t)return;let i=this.summaryCachedLines?.lines.length??0,o=this.summaryPageSize,n=L(this.summaryScrollOffset,i,o);this.summaryScrollOffset=L(n+t,i,o),this.touch()}summaryScrollStep(e){return T(e,S.pageUp)||"["===e||T(e,S.alt("up"))?-y.summaryScrollStep:T(e,S.pageDown)||"]"===e||T(e,S.alt("down"))?y.summaryScrollStep:T(e,S.up)||"k"===e?-1:T(e,S.down)||"j"===e?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=[];j(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=>k(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=L(this.summaryScrollOffset,n,r);l>0&&e.push(this.theme.fg("dim",s.summary.topMore(l)));for(let t of Z(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(""),ie(e,ve(this.model),this.theme,t),j(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=z(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)),j(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=z(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||ht(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),ie(e,a,this.theme,t),j(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>=gt){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,L(this.previewScrollOffset,r,o),o,s)}slicePreviewBoxLines(e,t,i,o){let n=e.length,r=L(t,n,i),l=Z(e,r,i).map(e=>k(e,o));if(n>i){let e=s.view.previewScrollInfo(r+1,Math.min(n,r+i),n);l.push(k(` ${this.theme.fg("dim",e)}`,o))}return l}renderSplitView(e,t,i,s,o){let n,r=I(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(`${X(n[t]??"",r)}${this.theme.fg("dim",y.dividerChar)}${k(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}))}),bt=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:M}),allowCustom:f.Optional(f.Boolean({description:s.schema.questionAllowCustom})),customPlaceholder:f.Optional(f.String({description:s.schema.questionCustomPlaceholder}))}),oe=f.Object({formTitle:f.String({description:s.schema.formTitle}),description:f.Optional(f.String({description:s.schema.formDesc})),questions:f.Optional(f.Array(bt,{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:M})),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 K(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function St(e){let t=F(e.raw);return K(t)?t:(delete e.raw,e)}function C(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,M).map((e,t)=>{if("string"==typeof e)return{label:e.trim()||s.fallbacks.autoOptionLabel(t+1)};if(!K(e))return{label:s.fallbacks.autoOptionLabel(t+1)};let i=e;return{label:w(C(i,["label","name","title","text","value","choice"]))??s.fallbacks.autoOptionLabel(t+1),description:w(C(i,["description","desc","reason","rationale","deduction"])),preview:w(C(i,["preview","draft","scene","content"])),customPlaceholder:w(C(i,["customPlaceholder","placeholder"]))}}):[]}function Tt(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 wt(e,t){if("string"==typeof e)return{title:e,options:G([])};if(!K(e))return{title:s.fallbacks.autoQuestionTitle(t+1),options:G([])};let i=e;return{id:C(i,["id"]),title:w(C(i,["title","question","prompt","query","heading"]))??s.fallbacks.autoQuestionTitle(t+1),description:w(C(i,["description","desc","rationale"])),multiSelect:q(i.multiSelect,!1),minSelect:Ce(i.minSelect),maxSelect:Ie(i.maxSelect),allowEmpty:q(i.allowEmpty,!1),options:G(Ne(i.options??i.choices??i.items)),allowCustom:q(i.allowCustom,!0),customPlaceholder:C(i,["customPlaceholder","placeholder"])}}function vt(e){if(void 0===e)return;let t=F(e),i=Array.isArray(t)?t:Tt(t)?[t]:[];return 0!==i.length?i.slice(0,D).map((e,t)=>wt(e,t)):void 0}function G(e){return e.length>0?e:[{label:s.fallbacks.defaultOptionLabel}]}function yt(e,t,i,s){return"string"==typeof e?e:"string"==typeof t?t:s?i:void 0}function Y(e){let t=e&&"object"==typeof e?e:F(e);if(!K(t))return{formTitle:s.fallbacks.defaultFormTitle};let i=St({...t}),o=w(C(i,["title","taskTitle"])),n=w(C(i,["formTitle"]))??o??s.fallbacks.defaultFormTitle,r=vt(i.questions??i.form??i.survey),l=void 0!==i.options||void 0!==i.choices||void 0!==i.items,a=l?G(Ne(i.options??i.choices??i.items)):void 0,u=yt(i.question,i.prompt,o,l);return{formTitle:n,description:C(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:C(i,["customPlaceholder"])}}function xt(e){return e instanceof Error?e.message:String(e)}function Me(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 $e(e={}){let{formTitle:t,formDescription:i,questions:o}=Me(e);return{content:[{type:"text",text:s.markdown.envelopeCancelled}],details:{formTitle:t,formDescription:i,questions:o,answers:[],cancelled:!0}}}function se(e,t,i,o={}){let{formTitle:n,formDescription:r,questions:l}=Me(o);return{content:[{type:"text",text:s.markdown.envelopeError(e,t)}],details:{formTitle:n,formDescription:r,questions:l,answers:[],cancelled:!1,error:i}}}function Ee(e,t={}){let i=xt(e);return se(s.markdown.errorReasons.runtimeError(i),s.markdown.errorGuidances.runtimeError,s.status.errorExecutionFailed(i),t)}function At(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 Ct(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 It(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 Nt(e,t){if(t.cachedArgs===e&&t.cachedCard)return t.cachedCard;let i=new Q(Y(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:oe,executionMode:"sequential",prepareArguments:Y,async execute(e,t,i,o,n){let r,l,a=w(t?.formTitle)??s.fallbacks.defaultFormTitle;if(i?.aborted)return $e({formTitle:a});if("tui"!==n.mode)return se(s.markdown.errorReasons.nonTui,s.markdown.errorGuidances.nonTui,s.status.errorNonTui,{formTitle:a});try{r=new Q(t)}catch(e){return Ee(e,{formTitle:a})}if(0===r.questions.length)return se(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 W(e,t,r,o),l.bindAbortSignal(i),l));return!e||e.cancelled?$e({questions:e?.questions??r.questions,formTitle:e?.formTitle??r.formTitle,formDescription:e?.formDescription??r.formDescription}):At(r,e.answers)}catch(e){return Ee(e,{questions:r.questions,formTitle:r.formTitle,formDescription:r.formDescription})}finally{l?.dispose()}},renderCall(e,t,i){let o=Nt(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=Ct(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} (${Oe("app.tools.expand",s.card.expandHint)})`,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",It(e))))].join("\n"):`${r} (${Oe("app.tools.expand",s.card.expandHint)})`,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,oe as AskAuthorParams,g as ICONS,y as LAYOUT_CONFIG,s as TEXTS,Ot as askAuthorExtension,Ot as default,Y as sanitizeAskAuthorArgs};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sendevia/pi-ask-author",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"description": "面向文字创作者的决策询问 Pi 扩展",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"dist"
|
|
24
24
|
],
|
|
25
25
|
"scripts": {
|
|
26
|
-
"build": "tsc
|
|
26
|
+
"build": "tsc && esbuild src/index.ts --bundle --format=esm --platform=node --target=ESNext --external:@earendil-works/* --external:typebox --minify --tree-shaking=true --legal-comments=none --drop:debugger --drop:console --outfile=dist/index.js && terser dist/index.js --compress passes=3,pure_getters=true --mangle --output dist/index.js",
|
|
27
27
|
"prepack": "pnpm build",
|
|
28
28
|
"check": "tsc --noEmit -p tsconfig.json"
|
|
29
29
|
},
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"@earendil-works/pi-coding-agent": "^0.85.1",
|
|
32
32
|
"@earendil-works/pi-tui": "^0.85.1",
|
|
33
33
|
"esbuild": "^0.28.2",
|
|
34
|
+
"terser": "^5.51.2",
|
|
34
35
|
"typebox": "^1.3.31",
|
|
35
36
|
"typescript": "^7.0.2"
|
|
36
37
|
},
|