@caveman-ai/cli 1.3.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/learn-tui.js CHANGED
@@ -1,61 +1,61 @@
1
1
  // Bundled interactive UI. @clack/prompts remains a build-time dependency only.
2
- var ee=Object.create;var It=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty;var oe=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(s){throw e=0,s}};var ae=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ie(e))!ne.call(t,o)&&o!==s&&It(t,o,{get:()=>e[o],enumerable:!(i=se(e,o))||i.enumerable});return t};var St=(t,e,s)=>(s=t!=null?ee(re(t)):{},ae(e||!t||!t.__esModule?It(s,"default",{value:t,enumerable:!0}):s,t));var dt=oe((us,kt)=>{"use strict";var pt={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let s="";return t<0?s+=`\x1B[${-t}D`:t>0&&(s+=`\x1B[${t}C`),e<0?s+=`\x1B[${-e}A`:e>0&&(s+=`\x1B[${e}B`),s},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ie={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},Se={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let s=0;s<t;s++)e+=this.line+(s<t-1?pt.up():"");return t&&(e+=pt.left),e}};kt.exports={cursor:pt,scroll:Ie,erase:Se,beep:"\x07"}});import{styleText as be}from"node:util";import{stdout as gt,stdin as Dt}from"node:process";import*as G from"node:readline";import _e from"node:readline";var bt=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let s=0;for(t.lastIndex=0;t.test(e);)s+=1;return e.length-s}})(),_t=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,xt=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var ue=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,le=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Et=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ce=/\t{1,1000}/y,Ct=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),he=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,pe=new RegExp("\\p{M}+","gu"),de={limit:1/0,ellipsis:""},Tt=(t,e={},s={})=>{let i=e.limit??1/0,o=e.ellipsis??"",u=e?.ellipsisWidth??(o?Tt(o,de,s).width:0),n=0,r=s.controlWidth??0,l=s.tabWidth??8,d=s.emojiWidth??2,g=2,h=s.regularWidth??1,p=s.wideWidth??g,m=[[he,h],[ue,n],[le,r],[ce,l],[Ct,d],[Et,p]],c=0,$=0,b=t.length,A=0,R=!1,L=b,F=Math.max(0,i-u),v=0,_=0,I=0,S=0;t:for(;;){if(_>v||$>=b&&$>c){let x=t.slice(v,_)||t.slice(c,$);A=0;for(let P of x.replaceAll(pe,"")){let C=P.codePointAt(0)||0;if(_t(C)?S=g:xt(C)?S=p:S=h,I+S>F&&(L=Math.min(L,Math.max(v,c)+A)),I+S>i){R=!0;break t}A+=P.length,I+=S}v=_=0}if($>=b)break t;for(let x=0,P=m.length;x<P;x++){let[C,Y]=m[x];if(C.lastIndex=$,C.test(t)){if(A=C===Et?bt(t.slice($,C.lastIndex)):C===Ct?1:C.lastIndex-$,S=A*Y,I+S>F&&(L=Math.min(L,$+Math.floor((F-I)/Y))),I+S>i){R=!0;break t}I+=S,v=c,_=$,$=c=C.lastIndex;continue t}}$+=1}return{width:R?F:I,index:R?L:b,truncated:R,ellipsed:R&&i>=u}},Mt=Tt;var me={limit:1/0,ellipsis:"",ellipsisWidth:0},ge=(t,e={})=>Mt(t,me,e).width,T=ge;var X="\x1B",Ot="\x9B",fe=39,ct="\x07",Rt="[",$e="]",Pt="m",ht=`${$e}8;;`,At=new RegExp(`(?:\\${Rt}(?<code>\\d+)m|\\${ht}(?<uri>.*)${ct})`,"y"),Ft=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Lt=t=>`${X}${Rt}${t}${Pt}`,Vt=t=>`${X}${ht}${t}${ct}`,lt=(t,e,s)=>{let i=e[Symbol.iterator](),o=!1,u=!1,n=t.at(-1),r=n===void 0?0:T(n),l=i.next(),d=i.next(),g=0;for(;!l.done;){let h=l.value,p=T(h);r+p<=s?t[t.length-1]+=h:(t.push(h),r=0),(h===X||h===Ot)&&(o=!0,u=e.startsWith(ht,g+1)),o?u?h===ct&&(o=!1,u=!1):h===Pt&&(o=!1):(r+=p,r===s&&!d.done&&(t.push(""),r=0)),l=d,d=i.next(),g+=h.length}n=t.at(-1),!r&&n!==void 0&&n.length&&t.length>1&&(t[t.length-2]+=t.pop())},ve=t=>{let e=t.split(" "),s=e.length;for(;s&&!T(e[s-1]);)s--;return s===e.length?t:e.slice(0,s).join(" ")+e.slice(s).join("")},ye=(t,e,s={})=>{if(s.trim!==!1&&t.trim()==="")return"";let i="",o,u,n=t.split(" "),r=[""],l=0;for(let h=0;h<n.length;h++){let p=n[h];if(s.trim!==!1){let c=r.at(-1)??"",$=c.trimStart();c.length!==$.length&&(r[r.length-1]=$,l=T($))}h!==0&&(l>=e&&(s.wordWrap===!1||s.trim===!1)&&(r.push(""),l=0),(l||s.trim===!1)&&(r[r.length-1]+=" ",l++));let m=T(p);if(s.hard&&m>e){let c=e-l,$=1+Math.floor((m-c-1)/e);Math.floor((m-1)/e)<$&&r.push(""),lt(r,p,e),l=T(r.at(-1)??"");continue}if(l+m>e&&l&&m){if(s.wordWrap===!1&&l<e){lt(r,p,e),l=T(r.at(-1)??"");continue}r.push(""),l=0}if(l+m>e&&s.wordWrap===!1){lt(r,p,e),l=T(r.at(-1)??"");continue}r[r.length-1]+=p,l+=m}s.trim!==!1&&(r=r.map(h=>ve(h)));let d=r.join(`
2
+ var ee=Object.create;var It=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty;var oe=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(s){throw e=0,s}};var ae=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ie(e))!ne.call(t,o)&&o!==s&&It(t,o,{get:()=>e[o],enumerable:!(i=se(e,o))||i.enumerable});return t};var St=(t,e,s)=>(s=t!=null?ee(re(t)):{},ae(e||!t||!t.__esModule?It(s,"default",{value:t,enumerable:!0}):s,t));var dt=oe((us,Nt)=>{"use strict";var pt={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let s="";return t<0?s+=`\x1B[${-t}D`:t>0&&(s+=`\x1B[${t}C`),e<0?s+=`\x1B[${-e}A`:e>0&&(s+=`\x1B[${e}B`),s},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ie={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},Se={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let s=0;s<t;s++)e+=this.line+(s<t-1?pt.up():"");return t&&(e+=pt.left),e}};Nt.exports={cursor:pt,scroll:Ie,erase:Se,beep:"\x07"}});import{styleText as be}from"node:util";import{stdout as gt,stdin as Dt}from"node:process";import*as j from"node:readline";import _e from"node:readline";var bt=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let s=0;for(t.lastIndex=0;t.test(e);)s+=1;return e.length-s}})(),_t=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,xt=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var ue=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,le=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ct=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ce=/\t{1,1000}/y,Et=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),he=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,pe=new RegExp("\\p{M}+","gu"),de={limit:1/0,ellipsis:""},Tt=(t,e={},s={})=>{let i=e.limit??1/0,o=e.ellipsis??"",u=e?.ellipsisWidth??(o?Tt(o,de,s).width:0),n=0,r=s.controlWidth??0,l=s.tabWidth??8,d=s.emojiWidth??2,g=2,h=s.regularWidth??1,p=s.wideWidth??g,m=[[he,h],[ue,n],[le,r],[ce,l],[Et,d],[Ct,p]],c=0,$=0,b=t.length,A=0,R=!1,L=b,F=Math.max(0,i-u),v=0,_=0,I=0,S=0;t:for(;;){if(_>v||$>=b&&$>c){let x=t.slice(v,_)||t.slice(c,$);A=0;for(let P of x.replaceAll(pe,"")){let E=P.codePointAt(0)||0;if(_t(E)?S=g:xt(E)?S=p:S=h,I+S>F&&(L=Math.min(L,Math.max(v,c)+A)),I+S>i){R=!0;break t}A+=P.length,I+=S}v=_=0}if($>=b)break t;for(let x=0,P=m.length;x<P;x++){let[E,Y]=m[x];if(E.lastIndex=$,E.test(t)){if(A=E===Ct?bt(t.slice($,E.lastIndex)):E===Et?1:E.lastIndex-$,S=A*Y,I+S>F&&(L=Math.min(L,$+Math.floor((F-I)/Y))),I+S>i){R=!0;break t}I+=S,v=c,_=$,$=c=E.lastIndex;continue t}}$+=1}return{width:R?F:I,index:R?L:b,truncated:R,ellipsed:R&&i>=u}},Mt=Tt;var me={limit:1/0,ellipsis:"",ellipsisWidth:0},ge=(t,e={})=>Mt(t,me,e).width,T=ge;var X="\x1B",Ot="\x9B",fe=39,ct="\x07",Rt="[",$e="]",Pt="m",ht=`${$e}8;;`,At=new RegExp(`(?:\\${Rt}(?<code>\\d+)m|\\${ht}(?<uri>.*)${ct})`,"y"),Ft=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Lt=t=>`${X}${Rt}${t}${Pt}`,Vt=t=>`${X}${ht}${t}${ct}`,lt=(t,e,s)=>{let i=e[Symbol.iterator](),o=!1,u=!1,n=t.at(-1),r=n===void 0?0:T(n),l=i.next(),d=i.next(),g=0;for(;!l.done;){let h=l.value,p=T(h);r+p<=s?t[t.length-1]+=h:(t.push(h),r=0),(h===X||h===Ot)&&(o=!0,u=e.startsWith(ht,g+1)),o?u?h===ct&&(o=!1,u=!1):h===Pt&&(o=!1):(r+=p,r===s&&!d.done&&(t.push(""),r=0)),l=d,d=i.next(),g+=h.length}n=t.at(-1),!r&&n!==void 0&&n.length&&t.length>1&&(t[t.length-2]+=t.pop())},ve=t=>{let e=t.split(" "),s=e.length;for(;s&&!T(e[s-1]);)s--;return s===e.length?t:e.slice(0,s).join(" ")+e.slice(s).join("")},ye=(t,e,s={})=>{if(s.trim!==!1&&t.trim()==="")return"";let i="",o,u,n=t.split(" "),r=[""],l=0;for(let h=0;h<n.length;h++){let p=n[h];if(s.trim!==!1){let c=r.at(-1)??"",$=c.trimStart();c.length!==$.length&&(r[r.length-1]=$,l=T($))}h!==0&&(l>=e&&(s.wordWrap===!1||s.trim===!1)&&(r.push(""),l=0),(l||s.trim===!1)&&(r[r.length-1]+=" ",l++));let m=T(p);if(s.hard&&m>e){let c=e-l,$=1+Math.floor((m-c-1)/e);Math.floor((m-1)/e)<$&&r.push(""),lt(r,p,e),l=T(r.at(-1)??"");continue}if(l+m>e&&l&&m){if(s.wordWrap===!1&&l<e){lt(r,p,e),l=T(r.at(-1)??"");continue}r.push(""),l=0}if(l+m>e&&s.wordWrap===!1){lt(r,p,e),l=T(r.at(-1)??"");continue}r[r.length-1]+=p,l+=m}s.trim!==!1&&(r=r.map(h=>ve(h)));let d=r.join(`
3
3
  `),g=!1;for(let h=0;h<d.length;h++){let p=d[h];if(i+=p,g)g=!1;else if(g=p>="\uD800"&&p<="\uDBFF",g)continue;if(p===X||p===Ot){At.lastIndex=h+1;let c=At.exec(d)?.groups;if(c?.code!==void 0){let $=Number.parseFloat(c.code);o=$===fe?void 0:$}else c?.uri!==void 0&&(u=c.uri.length===0?void 0:c.uri)}if(d[h+1]===`
4
4
  `){u&&(i+=Vt(""));let m=o?Ft(o):void 0;o&&m&&(i+=Lt(m))}else p===`
5
- `&&(o&&Ft(o)&&(i+=Lt(o)),u&&(i+=Vt(u)))}return i},we=/\r?\n/;function k(t,e,s){return String(t).normalize().split(we).map(i=>ye(i,e,s)).join(`
6
- `)}var M=St(dt(),1);import{ReadStream as Nt}from"node:tty";function Z(t,e,s){if(!s.some(n=>!n.disabled))return t;let i=t+e,o=Math.max(s.length-1,0),u=i<0?o:i>o?0:i;return s[u]?.disabled?Z(u,e<0?-1:1,s):u}var xe=["up","down","left","right","space","enter","cancel"],Ee=["January","February","March","April","May","June","July","August","September","October","November","December"],E={actions:new Set(xe),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...Ee],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function ft(t,e){if(typeof t=="string")return E.aliases.get(t)===e;for(let s of t)if(s!==void 0&&ft(s,e))return!0;return!1}function Ce(t,e){if(t===e)return;let s=t.split(`
5
+ `&&(o&&Ft(o)&&(i+=Lt(o)),u&&(i+=Vt(u)))}return i},we=/\r?\n/;function N(t,e,s){return String(t).normalize().split(we).map(i=>ye(i,e,s)).join(`
6
+ `)}var M=St(dt(),1);import{ReadStream as kt}from"node:tty";function Z(t,e,s){if(!s.some(n=>!n.disabled))return t;let i=t+e,o=Math.max(s.length-1,0),u=i<0?o:i>o?0:i;return s[u]?.disabled?Z(u,e<0?-1:1,s):u}var xe=["up","down","left","right","space","enter","cancel"],Ce=["January","February","March","April","May","June","July","August","September","October","November","December"],C={actions:new Set(xe),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...Ce],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function ft(t,e){if(typeof t=="string")return C.aliases.get(t)===e;for(let s of t)if(s!==void 0&&ft(s,e))return!0;return!1}function Ee(t,e){if(t===e)return;let s=t.split(`
7
7
  `),i=e.split(`
8
- `),o=Math.max(s.length,i.length),u=[];for(let n=0;n<o;n++)s[n]!==i[n]&&u.push(n);return{lines:u,numLinesBefore:s.length,numLinesAfter:i.length,numLines:o}}var Te=globalThis.process.platform.startsWith("win"),mt=Symbol("clack:cancel");function W(t){return t===mt}function Q(t,e){let s=t;s.isTTY&&s.setRawMode(e)}function Gt({input:t=Dt,output:e=gt,overwrite:s=!0,hideCursor:i=!0}={}){let o=G.createInterface({input:t,output:e,prompt:"",tabSize:1});G.emitKeypressEvents(t,o),t instanceof Nt&&t.isTTY&&t.setRawMode(!0);let u=(n,{name:r,sequence:l})=>{let d=String(n);if(ft([d,r,l],"cancel")){i&&e.write(M.cursor.show),process.exit(0);return}if(!s)return;G.moveCursor(e,r==="return"?0:-1,r==="return"?-1:0,()=>{G.clearLine(e,1,()=>{t.once("keypress",u)})})};return i&&e.write(M.cursor.hide),t.once("keypress",u),()=>{t.off("keypress",u),i&&e.write(M.cursor.show),t instanceof Nt&&t.isTTY&&!Te&&t.setRawMode(!1),o.terminal=!1,o.close()}}var K=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,$t=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function st(t,e,s,i=s,o=s,u){let n=K(t??gt);return k(e,n-s.length,{hard:!0,trim:!1}).split(`
8
+ `),o=Math.max(s.length,i.length),u=[];for(let n=0;n<o;n++)s[n]!==i[n]&&u.push(n);return{lines:u,numLinesBefore:s.length,numLinesAfter:i.length,numLines:o}}var Te=globalThis.process.platform.startsWith("win"),mt=Symbol("clack:cancel");function U(t){return t===mt}function Q(t,e){let s=t;s.isTTY&&s.setRawMode(e)}function Gt({input:t=Dt,output:e=gt,overwrite:s=!0,hideCursor:i=!0}={}){let o=j.createInterface({input:t,output:e,prompt:"",tabSize:1});j.emitKeypressEvents(t,o),t instanceof kt&&t.isTTY&&t.setRawMode(!0);let u=(n,{name:r,sequence:l})=>{let d=String(n);if(ft([d,r,l],"cancel")){i&&e.write(M.cursor.show),process.exit(0);return}if(!s)return;j.moveCursor(e,r==="return"?0:-1,r==="return"?-1:0,()=>{j.clearLine(e,1,()=>{t.once("keypress",u)})})};return i&&e.write(M.cursor.hide),t.once("keypress",u),()=>{t.off("keypress",u),i&&e.write(M.cursor.show),t instanceof kt&&t.isTTY&&!Te&&t.setRawMode(!1),o.terminal=!1,o.close()}}var H=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,$t=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function st(t,e,s,i=s,o=s,u){let n=H(t??gt);return N(e,n-s.length,{hard:!0,trim:!1}).split(`
9
9
  `).map((r,l,d)=>{let g=u?u(r,l):r;return l===0?`${i}${g}`:l===d.length-1?`${o}${g}`:`${s}${g}`}).join(`
10
- `)}function jt(t,e){if("~standard"in t){let s=t["~standard"].validate(e);if(s instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return s.issues?.at(0)?.message}return t(e)}var tt=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,s=!0){let{input:i=Dt,output:o=gt,render:u,signal:n,...r}=e;this.opts=r,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=u.bind(this),this._track=s,this._abortSignal=n,this.input=i,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(e,s){let i=this._subscribers.get(e)??[];i.push(s),this._subscribers.set(e,i)}on(e,s){this.setSubscriber(e,{cb:s})}once(e,s){this.setSubscriber(e,{cb:s,once:!0})}emit(e,...s){let i=this._subscribers.get(e)??[],o=[];for(let u of i)u.cb(...s),u.once&&o.push(()=>i.splice(i.indexOf(u),1));for(let u of o)u()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(mt);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=_e.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Q(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(M.cursor.show),this.output.off("resize",this.render),Q(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(M.cursor.show),this.output.off("resize",this.render),Q(this.input,!1),e(mt)})})}_isActionKey(e,s){return e===" "}_shouldSubmit(e,s){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,s){this.userInput=e??"",this.emit("userInput",this.userInput),s&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,s){if(this._track&&s.name!=="return"&&(s.name&&this._isActionKey(e,s)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),s?.name&&(!this._track&&E.aliases.has(s.name)&&this.emit("cursor",E.aliases.get(s.name)),E.actions.has(s.name)&&this.emit("cursor",s.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,s),s?.name==="return"&&this._shouldSubmit(e,s)){if(this.opts.validate){let i=jt(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}ft([e,s?.name,s?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
11
- `),Q(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=k(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
- `).length-1;this.output.write(M.cursor.move(-999,e*-1))}render(){let e=k(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(M.cursor.hide);else{let s=Ce(this._prevFrame,e),i=$t(this.output);if(this.restoreCursor(),s){let o=Math.max(0,s.numLinesAfter-i),u=Math.max(0,s.numLinesBefore-i),n=s.lines.find(r=>r>=o);if(n===void 0){this._prevFrame=e;return}if(s.lines.length===1){this.output.write(M.cursor.move(0,n-u)),this.output.write(M.erase.lines(1));let r=e.split(`
10
+ `)}function jt(t,e){if("~standard"in t){let s=t["~standard"].validate(e);if(s instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return s.issues?.at(0)?.message}return t(e)}var tt=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,s=!0){let{input:i=Dt,output:o=gt,render:u,signal:n,...r}=e;this.opts=r,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=u.bind(this),this._track=s,this._abortSignal=n,this.input=i,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(e,s){let i=this._subscribers.get(e)??[];i.push(s),this._subscribers.set(e,i)}on(e,s){this.setSubscriber(e,{cb:s})}once(e,s){this.setSubscriber(e,{cb:s,once:!0})}emit(e,...s){let i=this._subscribers.get(e)??[],o=[];for(let u of i)u.cb(...s),u.once&&o.push(()=>i.splice(i.indexOf(u),1));for(let u of o)u()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(mt);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=_e.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Q(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(M.cursor.show),this.output.off("resize",this.render),Q(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(M.cursor.show),this.output.off("resize",this.render),Q(this.input,!1),e(mt)})})}_isActionKey(e,s){return e===" "}_shouldSubmit(e,s){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,s){this.userInput=e??"",this.emit("userInput",this.userInput),s&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,s){if(this._track&&s.name!=="return"&&(s.name&&this._isActionKey(e,s)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),s?.name&&(!this._track&&C.aliases.has(s.name)&&this.emit("cursor",C.aliases.get(s.name)),C.actions.has(s.name)&&this.emit("cursor",s.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,s),s?.name==="return"&&this._shouldSubmit(e,s)){if(this.opts.validate){let i=jt(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}ft([e,s?.name,s?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
11
+ `),Q(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=N(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
+ `).length-1;this.output.write(M.cursor.move(-999,e*-1))}render(){let e=N(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(M.cursor.hide);else{let s=Ee(this._prevFrame,e),i=$t(this.output);if(this.restoreCursor(),s){let o=Math.max(0,s.numLinesAfter-i),u=Math.max(0,s.numLinesBefore-i),n=s.lines.find(r=>r>=o);if(n===void 0){this._prevFrame=e;return}if(s.lines.length===1){this.output.write(M.cursor.move(0,n-u)),this.output.write(M.erase.lines(1));let r=e.split(`
13
13
  `);this.output.write(r[n]),this._prevFrame=e,this.output.write(M.cursor.move(0,r.length-n-1));return}else if(s.lines.length>1){if(o<u)n=o;else{let l=n-u;l>0&&this.output.write(M.cursor.move(0,l))}this.output.write(M.erase.down());let r=e.split(`
14
14
  `).slice(n);this.output.write(r.join(`
15
- `)),this._prevFrame=e;return}}this.output.write(M.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var Wt=class extends tt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let s=this.options.findIndex(({value:o})=>o===e.initialValue),i=s===-1?0:s;this.cursor=this.options[i]?.disabled?Z(i,1,this.options):i,this.changeValue(),this.on("cursor",o=>{switch(o){case"left":case"up":this.cursor=Z(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Z(this.cursor,1,this.options);break}this.changeValue()})}};var et=class extends tt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let s=e.slice(0,this.cursor),i=e.slice(this.cursor,this.cursor+1),o=e.slice(this.cursor+1);return`${s}${be("inverse",i)}${o}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",s=>{this._setValue(s)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as a,stripVTControlCharacters as Cs}from"node:util";import O from"node:process";var H=St(dt(),1);function Me(){return O.platform!=="win32"?O.env.TERM!=="linux":!!O.env.CI||!!O.env.WT_SESSION||!!O.env.TERMINUS_SUBLIME||O.env.ConEmuTask==="{cmd::Cmder}"||O.env.TERM_PROGRAM==="Terminus-Sublime"||O.env.TERM_PROGRAM==="vscode"||O.env.TERM==="xterm-256color"||O.env.TERM==="alacritty"||O.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var vt=Me(),Ae=()=>process.env.CI==="true";var f=(t,e)=>vt?t:e,Fe=f("\u25C6","*"),Ht=f("\u25A0","x"),qt=f("\u25B2","x"),rt=f("\u25C7","o"),Le=f("\u250C","T"),y=f("\u2502","|"),U=f("\u2514","\u2014"),Fs=f("\u2510","T"),Ls=f("\u2518","\u2014"),Ve=f("\u25CF",">"),Ut=f("\u25CB"," "),Vs=f("\u25FB","[\u2022]"),Os=f("\u25FC","[+]"),Rs=f("\u25FB","[ ]"),Ps=f("\u25AA","\u2022"),Bt=f("\u2500","-"),Oe=f("\u256E","+"),Re=f("\u251C","+"),Pe=f("\u256F","+"),ke=f("\u2570","+"),ks=f("\u256D","+"),Ne=f("\u25CF","\u2022"),De=f("\u25C6","*"),Ge=f("\u25B2","!"),je=f("\u25A0","x"),Jt=t=>{switch(t){case"initial":case"active":return a("cyan",Fe);case"cancel":return a("red",Ht);case"error":return a("yellow",qt);case"submit":return a("green",rt)}},We=t=>{switch(t){case"initial":case"active":return a("cyan",y);case"cancel":return a("red",y);case"error":return a("yellow",y);case"submit":return a("green",y)}};function Ue(t,e){let s=[`${e?`${a("cyan",y)} `:""}${t.join(" \u2022 ")}`];return e&&s.push(a("cyan",U)),s}var Kt=(t,e,s,i,o,u=!1)=>{let n=e,r=0;if(u)for(let l=i-1;l>=s;l--){let d=t[l];if(d&&(n-=d.length),r++,n<=o)break}else for(let l=s;l<i;l++){let d=t[l];if(d&&(n-=d.length),r++,n<=o)break}return{lineCount:n,removals:r}},Be=({cursor:t,options:e,style:s,output:i=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:u=0,rowPadding:n=4})=>{let r=K(i)-u,l=$t(i),d=a("dim","..."),g=Math.max(l-n,0),h=Math.max(Math.min(o,g),5),p=0;t>=h-3&&(p=Math.max(Math.min(t-h+3,e.length-h),0));let m=h<e.length&&p>0,c=h<e.length&&p+h<e.length,$=Math.min(p+h,e.length),b=[],A=0;m&&A++,c&&A++;let R=p+(m?1:0),L=$-(c?1:0);for(let v=R;v<L;v++){let _=e[v],I=_?s(_,v===t):"",S=k(I,r,{hard:!0,trim:!1}).split(`
16
- `);b.push(S),A+=S.length}if(A>g){let v=0,_=0,I=A,S=t-R,x=g,P=()=>Kt(b,I,0,S,x),C=()=>Kt(b,I,S+1,b.length,x,!0);m?({lineCount:I,removals:v}=P(),I>x&&(c||(x-=1),{lineCount:I,removals:_}=C())):(c||(x-=1),{lineCount:I,removals:_}=C(),I>x&&(x-=1,{lineCount:I,removals:v}=P())),v>0&&(m=!0,b.splice(0,v)),_>0&&(c=!0,b.splice(b.length-_,_))}let F=[];m&&F.push(d);for(let v of b)for(let _ of v)F.push(_);return c&&F.push(d),F};var Ns=[`${a("dim","\u2191/\u2193")} to navigate`,`${a("dim","Space:")} select`,`${a("dim","Enter:")} confirm`];var j={message:(t=[],{symbol:e=a("gray",y),secondarySymbol:s=a("gray",y),output:i=process.stdout,spacing:o=1,withGuide:u}={})=>{let n=[],r=u??E.withGuide,l=r?s:"",d=r?`${e} `:"",g=r?`${s} `:"";for(let p=0;p<o;p++)n.push(l);let h=Array.isArray(t)?t:t.split(`
15
+ `)),this._prevFrame=e;return}}this.output.write(M.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var Wt=class extends tt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let s=this.options.findIndex(({value:o})=>o===e.initialValue),i=s===-1?0:s;this.cursor=this.options[i]?.disabled?Z(i,1,this.options):i,this.changeValue(),this.on("cursor",o=>{switch(o){case"left":case"up":this.cursor=Z(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Z(this.cursor,1,this.options);break}this.changeValue()})}};var et=class extends tt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let s=e.slice(0,this.cursor),i=e.slice(this.cursor,this.cursor+1),o=e.slice(this.cursor+1);return`${s}${be("inverse",i)}${o}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",s=>{this._setValue(s)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as a,stripVTControlCharacters as Es}from"node:util";import O from"node:process";var q=St(dt(),1);function Me(){return O.platform!=="win32"?O.env.TERM!=="linux":!!O.env.CI||!!O.env.WT_SESSION||!!O.env.TERMINUS_SUBLIME||O.env.ConEmuTask==="{cmd::Cmder}"||O.env.TERM_PROGRAM==="Terminus-Sublime"||O.env.TERM_PROGRAM==="vscode"||O.env.TERM==="xterm-256color"||O.env.TERM==="alacritty"||O.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var vt=Me(),Ae=()=>process.env.CI==="true";var f=(t,e)=>vt?t:e,Fe=f("\u25C6","*"),Ht=f("\u25A0","x"),qt=f("\u25B2","x"),rt=f("\u25C7","o"),Le=f("\u250C","T"),y=f("\u2502","|"),B=f("\u2514","\u2014"),Fs=f("\u2510","T"),Ls=f("\u2518","\u2014"),Ve=f("\u25CF",">"),Ut=f("\u25CB"," "),Vs=f("\u25FB","[\u2022]"),Os=f("\u25FC","[+]"),Rs=f("\u25FB","[ ]"),Ps=f("\u25AA","\u2022"),Bt=f("\u2500","-"),Oe=f("\u256E","+"),Re=f("\u251C","+"),Pe=f("\u256F","+"),Ne=f("\u2570","+"),Ns=f("\u256D","+"),ke=f("\u25CF","\u2022"),De=f("\u25C6","*"),Ge=f("\u25B2","!"),je=f("\u25A0","x"),Jt=t=>{switch(t){case"initial":case"active":return a("cyan",Fe);case"cancel":return a("red",Ht);case"error":return a("yellow",qt);case"submit":return a("green",rt)}},We=t=>{switch(t){case"initial":case"active":return a("cyan",y);case"cancel":return a("red",y);case"error":return a("yellow",y);case"submit":return a("green",y)}};function Ue(t,e){let s=[`${e?`${a("cyan",y)} `:""}${t.join(" \u2022 ")}`];return e&&s.push(a("cyan",B)),s}var Kt=(t,e,s,i,o,u=!1)=>{let n=e,r=0;if(u)for(let l=i-1;l>=s;l--){let d=t[l];if(d&&(n-=d.length),r++,n<=o)break}else for(let l=s;l<i;l++){let d=t[l];if(d&&(n-=d.length),r++,n<=o)break}return{lineCount:n,removals:r}},Be=({cursor:t,options:e,style:s,output:i=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:u=0,rowPadding:n=4})=>{let r=H(i)-u,l=$t(i),d=a("dim","..."),g=Math.max(l-n,0),h=Math.max(Math.min(o,g),5),p=0;t>=h-3&&(p=Math.max(Math.min(t-h+3,e.length-h),0));let m=h<e.length&&p>0,c=h<e.length&&p+h<e.length,$=Math.min(p+h,e.length),b=[],A=0;m&&A++,c&&A++;let R=p+(m?1:0),L=$-(c?1:0);for(let v=R;v<L;v++){let _=e[v],I=_?s(_,v===t):"",S=N(I,r,{hard:!0,trim:!1}).split(`
16
+ `);b.push(S),A+=S.length}if(A>g){let v=0,_=0,I=A,S=t-R,x=g,P=()=>Kt(b,I,0,S,x),E=()=>Kt(b,I,S+1,b.length,x,!0);m?({lineCount:I,removals:v}=P(),I>x&&(c||(x-=1),{lineCount:I,removals:_}=E())):(c||(x-=1),{lineCount:I,removals:_}=E(),I>x&&(x-=1,{lineCount:I,removals:v}=P())),v>0&&(m=!0,b.splice(0,v)),_>0&&(c=!0,b.splice(b.length-_,_))}let F=[];m&&F.push(d);for(let v of b)for(let _ of v)F.push(_);return c&&F.push(d),F};var ks=[`${a("dim","\u2191/\u2193")} to navigate`,`${a("dim","Space:")} select`,`${a("dim","Enter:")} confirm`];var G={message:(t=[],{symbol:e=a("gray",y),secondarySymbol:s=a("gray",y),output:i=process.stdout,spacing:o=1,withGuide:u}={})=>{let n=[],r=u??C.withGuide,l=r?s:"",d=r?`${e} `:"",g=r?`${s} `:"";for(let p=0;p<o;p++)n.push(l);let h=Array.isArray(t)?t:t.split(`
17
17
  `);if(h.length>0){let[p,...m]=h;p.length>0?n.push(`${d}${p}`):n.push(r?e:"");for(let c of m)c.length>0?n.push(`${g}${c}`):n.push(r?s:"")}i.write(`${n.join(`
18
18
  `)}
19
- `)},info:(t,e)=>{j.message(t,{...e,symbol:a("blue",Ne)})},success:(t,e)=>{j.message(t,{...e,symbol:a("green",De)})},step:(t,e)=>{j.message(t,{...e,symbol:a("green",rt)})},warn:(t,e)=>{j.message(t,{...e,symbol:a("yellow",Ge)})},warning:(t,e)=>{j.warn(t,e)},error:(t,e)=>{j.message(t,{...e,symbol:a("red",je)})}},nt=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??E.withGuide?`${a("gray",U)} `:"";s.write(`${i}${a("red",t)}
19
+ `)},info:(t,e)=>{G.message(t,{...e,symbol:a("blue",ke)})},success:(t,e)=>{G.message(t,{...e,symbol:a("green",De)})},step:(t,e)=>{G.message(t,{...e,symbol:a("green",rt)})},warn:(t,e)=>{G.message(t,{...e,symbol:a("yellow",Ge)})},warning:(t,e)=>{G.warn(t,e)},error:(t,e)=>{G.message(t,{...e,symbol:a("red",je)})}},nt=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??C.withGuide?`${a("gray",B)} `:"";s.write(`${i}${a("red",t)}
20
20
 
21
- `)},Yt=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??E.withGuide?`${a("gray",Le)} `:"";s.write(`${i}${t}
22
- `)},q=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??E.withGuide?`${a("gray",y)}
23
- ${a("gray",U)} `:"";s.write(`${i}${t}
21
+ `)},Yt=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??C.withGuide?`${a("gray",Le)} `:"";s.write(`${i}${t}
22
+ `)},J=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??C.withGuide?`${a("gray",y)}
23
+ ${a("gray",B)} `:"";s.write(`${i}${t}
24
24
 
25
- `)};var Ke=t=>t,He=(t,e,s)=>{let i={hard:!0,trim:!1},o=k(t,e,i).split(`
26
- `),u=o.reduce((l,d)=>Math.max(T(d),l),0),n=o.map(s).reduce((l,d)=>Math.max(T(d),l),0),r=e-(n-u);return k(t,r,i)},ot=(t="",e="",s)=>{let i=s?.output??O.stdout,o=s?.withGuide??E.withGuide,u=s?.format??Ke,n=["",...He(t,K(i)-6,u).split(`
25
+ `)};var Ke=t=>t,He=(t,e,s)=>{let i={hard:!0,trim:!1},o=N(t,e,i).split(`
26
+ `),u=o.reduce((l,d)=>Math.max(T(d),l),0),n=o.map(s).reduce((l,d)=>Math.max(T(d),l),0),r=e-(n-u);return N(t,r,i)},ot=(t="",e="",s)=>{let i=s?.output??O.stdout,o=s?.withGuide??C.withGuide,u=s?.format??Ke,n=["",...He(t,H(i)-6,u).split(`
27
27
  `).map(u),""],r=T(e),l=Math.max(n.reduce((p,m)=>{let c=T(m);return c>p?c:p},0),r)+2,d=n.map(p=>`${a("gray",y)} ${p}${" ".repeat(l-T(p))}${a("gray",y)}`).join(`
28
28
  `),g=o?`${a("gray",y)}
29
- `:"",h=o?Re:ke;i.write(`${g}${a("green",rt)} ${a("reset",e)} ${a("gray",Bt.repeat(Math.max(l-r-1,1))+Oe)}
29
+ `:"",h=o?Re:Ne;i.write(`${g}${a("green",rt)} ${a("reset",e)} ${a("gray",Bt.repeat(Math.max(l-r-1,1))+Oe)}
30
30
  ${d}
31
31
  ${a("gray",h+Bt.repeat(l+2)+Pe)}
32
- `)};var qe=t=>a("magenta",t),zt=({indicator:t="dots",onCancel:e,output:s=process.stdout,cancelMessage:i,errorMessage:o,frames:u=vt?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:n=vt?80:120,signal:r,...l}={})=>{let d=Ae(),g,h,p=!1,m=!1,c="",$,b=performance.now(),A=K(s),R=l?.styleFrame??qe,L=w=>{let V=w>1?o??E.messages.error:i??E.messages.cancel;m=w===1,p&&(B(V,w),m&&typeof e=="function"&&e())},F=()=>L(2),v=()=>L(1),_=()=>{process.on("uncaughtExceptionMonitor",F),process.on("unhandledRejection",F),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",L),r&&r.addEventListener("abort",v)},I=()=>{process.removeListener("uncaughtExceptionMonitor",F),process.removeListener("unhandledRejection",F),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",L),r&&r.removeEventListener("abort",v)},S=()=>{if($===void 0)return;d&&s.write(`
33
- `);let w=k($,A,{hard:!0,trim:!1}).split(`
34
- `);w.length>1&&s.write(H.cursor.up(w.length-1)),s.write(H.cursor.to(0)),s.write(H.erase.down())},x=w=>w.replace(/\.+$/,""),P=w=>{let V=(performance.now()-w)/1e3,N=Math.floor(V/60),D=Math.floor(V%60);return N>0?`[${N}m ${D}s]`:`[${D}s]`},C=l.withGuide??E.withGuide,Y=(w="")=>{p=!0,g=Gt({output:s}),c=x(w),b=performance.now(),C&&s.write(`${a("gray",y)}
35
- `);let V=0,N=0;_(),h=setInterval(()=>{if(d&&c===$)return;S(),$=c;let D=R(u[V]),z;if(d)z=`${D} ${c}...`;else if(t==="timer")z=`${D} ${c} ${P(b)}`;else{let te=".".repeat(Math.floor(N)).slice(0,3);z=`${D} ${c}${te}`}let Zt=k(z,A,{hard:!0,trim:!1});s.write(Zt),V=V+1<u.length?V+1:0,N=N<4?N+.125:0},n)},B=(w="",V=0,N=!1)=>{if(!p)return;p=!1,clearInterval(h),S();let D=V===0?a("green",rt):V===1?a("red",Ht):a("red",qt);c=w??c,N||(t==="timer"?s.write(`${D} ${c} ${P(b)}
32
+ `)};var qe=t=>a("magenta",t),zt=({indicator:t="dots",onCancel:e,output:s=process.stdout,cancelMessage:i,errorMessage:o,frames:u=vt?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:n=vt?80:120,signal:r,...l}={})=>{let d=Ae(),g,h,p=!1,m=!1,c="",$,b=performance.now(),A=H(s),R=l?.styleFrame??qe,L=w=>{let V=w>1?o??C.messages.error:i??C.messages.cancel;m=w===1,p&&(K(V,w),m&&typeof e=="function"&&e())},F=()=>L(2),v=()=>L(1),_=()=>{process.on("uncaughtExceptionMonitor",F),process.on("unhandledRejection",F),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",L),r&&r.addEventListener("abort",v)},I=()=>{process.removeListener("uncaughtExceptionMonitor",F),process.removeListener("unhandledRejection",F),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",L),r&&r.removeEventListener("abort",v)},S=()=>{if($===void 0)return;d&&s.write(`
33
+ `);let w=N($,A,{hard:!0,trim:!1}).split(`
34
+ `);w.length>1&&s.write(q.cursor.up(w.length-1)),s.write(q.cursor.to(0)),s.write(q.erase.down())},x=w=>w.replace(/\.+$/,""),P=w=>{let V=(performance.now()-w)/1e3,k=Math.floor(V/60),D=Math.floor(V%60);return k>0?`[${k}m ${D}s]`:`[${D}s]`},E=l.withGuide??C.withGuide,Y=(w="")=>{p=!0,g=Gt({output:s}),c=x(w),b=performance.now(),E&&s.write(`${a("gray",y)}
35
+ `);let V=0,k=0;_(),h=setInterval(()=>{if(d&&c===$)return;S(),$=c;let D=R(u[V]),z;if(d)z=`${D} ${c}...`;else if(t==="timer")z=`${D} ${c} ${P(b)}`;else{let te=".".repeat(Math.floor(k)).slice(0,3);z=`${D} ${c}${te}`}let Zt=N(z,A,{hard:!0,trim:!1});s.write(Zt),V=V+1<u.length?V+1:0,k=k<4?k+.125:0},n)},K=(w="",V=0,k=!1)=>{if(!p)return;p=!1,clearInterval(h),S();let D=V===0?a("green",rt):V===1?a("red",Ht):a("red",qt);c=w??c,k||(t==="timer"?s.write(`${D} ${c} ${P(b)}
36
36
  `):s.write(`${D} ${c}
37
- `)),I(),g()};return{start:Y,stop:(w="")=>B(w,0),message:(w="")=>{c=x(w??c)},cancel:(w="")=>B(w,1),error:(w="")=>B(w,2),clear:()=>B("",0,!0),get isCancelled(){return m}}},Ds={light:f("\u2500","-"),heavy:f("\u2501","="),block:f("\u2588","#")};var Je=[`${a("dim","\u2191/\u2193")} to navigate`,`${a("dim","Enter:")} confirm`],it=(t,e)=>t.includes(`
37
+ `)),I(),g()};return{start:Y,stop:(w="")=>K(w,0),message:(w="")=>{c=x(w??c)},cancel:(w="")=>K(w,1),error:(w="")=>K(w,2),clear:()=>K("",0,!0),get isCancelled(){return m}}},Ds={light:f("\u2500","-"),heavy:f("\u2501","="),block:f("\u2588","#")};var Je=[`${a("dim","\u2191/\u2193")} to navigate`,`${a("dim","Enter:")} confirm`],it=(t,e)=>t.includes(`
38
38
  `)?t.split(`
39
39
  `).map(s=>e(s)).join(`
40
- `):e(t),yt=t=>{let e=(i,o)=>{if(i===void 0)return"";let u=i.label??String(i.value);switch(o){case"disabled":return`${a("gray",Ut)} ${it(u,n=>a("gray",n))}${i.hint?` ${a("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${it(u,n=>a("dim",n))}`;case"active":return`${a("green",Ve)} ${u}${i.hint?` ${a("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${it(u,n=>a(["strikethrough","dim"],n))}`;default:return`${a("dim",Ut)} ${it(u,n=>a("dim",n))}`}},s=t.showInstructions??!0;return new Wt({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let i=t.withGuide??E.withGuide,o=`${Jt(this.state)} `,u=`${We(this.state)} `,n=st(t.output,t.message,u,o),r=`${i?`${a("gray",y)}
40
+ `):e(t),yt=t=>{let e=(i,o)=>{if(i===void 0)return"";let u=i.label??String(i.value);switch(o){case"disabled":return`${a("gray",Ut)} ${it(u,n=>a("gray",n))}${i.hint?` ${a("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${it(u,n=>a("dim",n))}`;case"active":return`${a("green",Ve)} ${u}${i.hint?` ${a("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${it(u,n=>a(["strikethrough","dim"],n))}`;default:return`${a("dim",Ut)} ${it(u,n=>a("dim",n))}`}},s=t.showInstructions??!0;return new Wt({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let i=t.withGuide??C.withGuide,o=`${Jt(this.state)} `,u=`${We(this.state)} `,n=st(t.output,t.message,u,o),r=`${i?`${a("gray",y)}
41
41
  `:""}${n}
42
42
  `;switch(this.state){case"submit":{let l=i?`${a("gray",y)} `:"",d=st(t.output,e(this.options[this.cursor],"selected"),l);return`${r}${d}`}case"cancel":{let l=i?`${a("gray",y)} `:"",d=st(t.output,e(this.options[this.cursor],"cancelled"),l);return`${r}${d}${i?`
43
43
  ${a("gray",y)}`:""}`}default:{let l=i?`${a("cyan",y)} `:"",d=r.split(`
44
- `).length,g=s?Ue(Je,i):i?[a("cyan",U)]:[],h=g.join(`
44
+ `).length,g=s?Ue(Je,i):i?[a("cyan",B)]:[],h=g.join(`
45
45
  `),p=g.length+1;return`${r}${l}${Be({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:d+p,style:(m,c)=>e(m,m.disabled?"disabled":c?"active":"inactive")}).join(`
46
46
  ${l}`)}
47
47
  ${h}
48
- `}}}}).prompt()};var Gs=`${a("gray",y)} `;var Xt=t=>new et({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??E.withGuide,s=`${`${e?`${a("gray",y)}
48
+ `}}}}).prompt()};var Gs=`${a("gray",y)} `;var Xt=t=>new et({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??C.withGuide,s=`${`${e?`${a("gray",y)}
49
49
  `:""}${Jt(this.state)} `}${t.message}
50
- `,i=t.placeholder&&t.placeholder.length>0?a("inverse",t.placeholder[0])+a("dim",t.placeholder.slice(1)):a(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:i,u=this.value??"";switch(this.state){case"error":{let n=this.error?` ${a("yellow",this.error)}`:"",r=e?`${a("yellow",y)} `:"",l=e?a("yellow",U):"";return`${s.trim()}
50
+ `,i=t.placeholder&&t.placeholder.length>0?a("inverse",t.placeholder[0])+a("dim",t.placeholder.slice(1)):a(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:i,u=this.value??"";switch(this.state){case"error":{let n=this.error?` ${a("yellow",this.error)}`:"",r=e?`${a("yellow",y)} `:"",l=e?a("yellow",B):"";return`${s.trim()}
51
51
  ${r}${o}
52
52
  ${l}${n}
53
53
  `}case"submit":{let n=u?` ${a("dim",u)}`:"",r=e?a("gray",y):"";return`${s}${r}${n}`}case"cancel":{let n=u?` ${a(["strikethrough","dim"],u)}`:"",r=e?a("gray",y):"";return`${s}${r}${n}${u.trim()?`
54
- ${r}`:""}`}default:{let n=e?`${a("cyan",y)} `:"",r=e?a("cyan",U):"";return`${s}${n}${o}
54
+ ${r}`:""}`}default:{let n=e?`${a("cyan",y)} `:"",r=e?a("cyan",B):"";return`${s}${n}${o}
55
55
  ${r}
56
- `}}}}).prompt();var ze=!process.env.NO_COLOR&&!!process.stdout.isTTY,ut=(t,e)=>ze?`\x1B[${t}m${e}\x1B[0m`:e,at=t=>ut("1",t),J=t=>ut("2",t),wt=t=>ut("32",t),Xe=t=>ut("33",t);function Qe(t,e=24){let s=Math.max(0,Math.min(100,Math.round(t))),i=Math.round(s/100*e);return`${"\u2501".repeat(i)}${"\u2500".repeat(e-i)}`}function Ze(t){return[at(t.title),wt(t.detail),...t.action?[J(t.action)]:[]].join(`
57
- `)}function Qt(t){let e=t.confirmed&&t.confirmed>0?J(`${t.confirmed} fixes measured since you applied them \u2014 run caveman learn --all`):void 0;if(t.score===null)return[t.sessions,...t.status?[t.status]:[],...e?[e]:[]].join(`
58
- `);let s=Math.max(0,Math.min(100,Math.round(t.score)));return[`${wt(Qe(s))} ${at(`${s}/100`)}`,...e?[e]:[],J(t.scope),t.sessions,...t.diff?[Xe(t.diff)]:[]].join(`
59
- `)}function Ws(){let t=zt();return{start(e){t.start(e)},update(e){t.message(e)},stop(e){t.stop(e)},fail(e){t.error(e)}}}async function Us(t){let e=await yt({message:"Implement findings with",options:t});return W(e)?(nt("Implementation cancelled"),null):e}async function Bs(t){if(Yt(`${wt(at(" CAVEMAN "))} ${J("LEARN / LOCAL SETUP")}`),t.score!==null?ot(Qt(t),"SETUP SCORE"):ot(Qt(t),"LEARN RESULT"),t.moves.length>0){let i=t.moves.map((o,u)=>`${J(String(u+1).padStart(2,"0"))} ${Ze(o)}`);ot(i.join(`
56
+ `}}}}).prompt();var ze=!process.env.NO_COLOR&&!!process.stdout.isTTY,ut=(t,e)=>ze?`\x1B[${t}m${e}\x1B[0m`:e,at=t=>ut("1",t),W=t=>ut("2",t),wt=t=>ut("32",t),Xe=t=>ut("33",t);function Qe(t,e=24){let s=Math.max(0,Math.min(100,Math.round(t))),i=Math.round(s/100*e);return`${"\u2501".repeat(i)}${"\u2500".repeat(e-i)}`}function Ze(t){return[at(t.title),wt(t.detail),...t.action?[W(t.action)]:[]].join(`
57
+ `)}function Qt(t){let e=t.confirmed&&t.confirmed>0?W(`${t.confirmed} fix${t.confirmed===1?"":"es"} measured since you applied them \u2014 run caveman learn --all`):void 0;if(t.score===null)return[t.sessions,...t.status?[t.status]:[],...(t.trend??[]).map(W),...e?[e]:[]].join(`
58
+ `);let s=Math.max(0,Math.min(100,Math.round(t.score)));return[`${wt(Qe(s))} ${at(`${s}/100`)}`,...e?[e]:[],W(t.scope),t.sessions,...t.diff?[Xe(t.diff)]:[],...(t.trend??[]).map(W)].join(`
59
+ `)}function Ws(){let t=zt();return{start(e){t.start(e)},update(e){t.message(e)},stop(e){t.stop(e)},fail(e){t.error(e)}}}async function Us(t){let e=await yt({message:"Implement findings with",options:t});return U(e)?(nt("Implementation cancelled"),null):e}async function Bs(t){if(Yt(`${wt(at(" CAVEMAN "))} ${W("LEARN / LOCAL SETUP")}`),t.score!==null?ot(Qt(t),"SETUP SCORE"):ot(Qt(t),"LEARN RESULT"),t.moves.length>0){let i=t.moves.map((o,u)=>`${W(String(u+1).padStart(2,"0"))} ${Ze(o)}`);ot(i.join(`
60
60
 
61
- `),"TOP MOVES")}t.protected&&j.warn(`${at("Protected")} ${t.protected}`);let e=[];t.moves.length>0&&e.push({value:"implement",label:"Implement with agent",hint:"Claude Code or Codex \xB7 approval before edits"}),t.findings>0&&e.push({value:"details",label:`Show all ${t.findings} findings`,hint:"full ids, evidence, and suggestions"}),e.push({value:"report",label:"Open visual report",hint:t.report},{value:"done",label:"Done"});let s=await yt({message:"Choose next step",initialValue:t.moves.length>0?"implement":"report",options:e});if(W(s))return nt("Done"),{action:"done"};if(s==="implement"){let i=await Xt({message:"Anything agent should focus on?",placeholder:"Press Enter to work through all top moves",defaultValue:""});return W(i)?(nt("Implementation cancelled"),{action:"done"}):(q("Opening implementation agent"),i.trim()?{action:"implement",focus:i.trim()}:{action:"implement"})}else s==="details"?q("Showing complete findings"):s==="report"?q("Opening local report"):q(`Saved report \xB7 ${t.report}`);return{action:s}}export{Ws as createLearnProgress,Ze as learnMoveBody,Qe as learnScoreBar,Qt as learnScoreBody,Bs as renderLearnTui,Us as selectLearnAgent};
61
+ `),"TOP FINDINGS")}t.protected&&G.warn(`${at("Needed")} ${t.protected}`),t.memory&&G.info(t.memory);let e=[];t.moves.length>0&&e.push({value:"implement",label:"Implement with agent",hint:"Claude Code or Codex \xB7 asks before every edit"}),t.findings>0&&e.push({value:"details",label:`Show all ${t.findings} findings`,hint:"ids, evidence, and suggested fixes"}),e.push({value:"report",label:"Open visual report",hint:t.report},{value:"done",label:"Done"});let s=await yt({message:"Choose next step",initialValue:t.moves.length>0?"implement":"report",options:e});if(U(s))return nt("Done"),{action:"done"};if(s==="implement"){let i=await Xt({message:"Anything the agent should focus on?",placeholder:"Press Enter to work through all top findings",defaultValue:""});return U(i)?(nt("Implementation cancelled"),{action:"done"}):(J("Opening implementation agent"),i.trim()?{action:"implement",focus:i.trim()}:{action:"implement"})}else s==="details"?J("Showing complete findings"):s==="report"?J("Opening local report"):J(`Saved report \xB7 ${t.report}`);return{action:s}}export{Ws as createLearnProgress,Ze as learnMoveBody,Qe as learnScoreBar,Qt as learnScoreBody,Bs as renderLearnTui,Us as selectLearnAgent};
@@ -3,9 +3,10 @@ import { appendFileSync, chmodSync, lstatSync, mkdirSync, readFileSync, realpath
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { connect as netConnect } from "node:net";
6
- import { createHash } from "node:crypto";
6
+ import { createHash, randomUUID } from "node:crypto";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { hardenedGitArgs, hardenedGitEnv } from "./git-safe.js";
9
+ import { confirmLearnNudge, maybeSpawnAutopilot } from "./learn-autopilot.js";
9
10
  const PROFILES = new Set(["record-only", "core", "core-lean-build", "ledger", "ccr-masking", "cache-aware", "full-safe", "full-max"]);
10
11
  const ACTIONS = new Set(["allow", "observe", "block", "ask", "defer"]);
11
12
  const VISIBILITY = new Set(["silent", "advisory", "user"]);
@@ -274,13 +275,18 @@ function gitDir(cwd) {
274
275
  current = parent;
275
276
  }
276
277
  }
278
+ // Go's nativehook.repositoryStatusBudget, for the same reason: 100ms emptied the
279
+ // state under ordinary load. Only search/test/build tool events pay it, never
280
+ // alongside the prompt-time delegate; with the runtime call's 250ms it stays far
281
+ // inside the host's 30s hook timeout.
282
+ const REPOSITORY_STATUS_TIMEOUT_MS = 500;
277
283
  function repositoryState(cwd) {
278
284
  if (!cwd)
279
285
  return undefined;
280
286
  try {
281
287
  const status = execFileSync("git", hardenedGitArgs(cwd, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=all"), {
282
288
  env: hardenedGitEnv(),
283
- timeout: 100, maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"],
289
+ timeout: REPOSITORY_STATUS_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"],
284
290
  });
285
291
  const directory = gitDir(cwd);
286
292
  if (!directory)
@@ -442,10 +448,15 @@ function fallback(entry) {
442
448
  const DELEGATE_TIMEOUT_MS = 3000;
443
449
  function delegateToFullCLI(raw, agent) {
444
450
  const cli = join(dirname(fileURLToPath(import.meta.url)), "index.js");
445
- const result = spawnSync(process.execPath, [cli, "native-hook", agent], { input: raw, maxBuffer: 3 * 1024 * 1024, env: process.env, timeout: DELEGATE_TIMEOUT_MS });
451
+ const nudgeToken = randomUUID();
452
+ const result = spawnSync(process.execPath, [cli, "native-hook", agent], { input: raw, maxBuffer: 3 * 1024 * 1024, env: { ...process.env, CAVEMAN_LEARN_NUDGE_TOKEN: nudgeToken }, timeout: DELEGATE_TIMEOUT_MS });
446
453
  if (!result.error && result.status === 0) {
454
+ // The child left any learn nudge in-flight; it is announced only once it
455
+ // actually reaches the host, so a delegate timeout lets it re-show once.
456
+ const nudged = result.stdout?.includes('"systemMessage"') === true;
447
457
  if (result.stdout?.length)
448
- process.stdout.write(result.stdout);
458
+ process.stdout.write(result.stdout, () => { if (nudged)
459
+ confirmLearnNudge(nudgeToken); });
449
460
  if (result.stderr?.length)
450
461
  process.stderr.write(result.stderr);
451
462
  return true;
@@ -472,6 +483,8 @@ async function main() {
472
483
  const rawName = bounded(event.hook_event_name ?? event.event_name ?? event.event ?? process.argv[4]);
473
484
  const mapped = agent === "gemini" && rawName ? { BeforeAgent: "UserPromptSubmit", BeforeTool: "PreToolUse", AfterTool: "PostToolUse", BeforeModel: "ModelBefore", AfterModel: "ModelAfter", PreCompress: "PreCompact", AfterAgent: "Stop" }[rawName] ?? rawName : rawName;
474
485
  const eventName = mapped && EVENTS.has(mapped) ? mapped : "Unknown";
486
+ if (eventName === "SessionEnd")
487
+ maybeSpawnAutopilot();
475
488
  if (eventName === "SessionStart" || eventName === "PostCompact") {
476
489
  delegateToFullCLI(raw, agent);
477
490
  return;
@@ -498,8 +511,8 @@ async function main() {
498
511
  if (!response) {
499
512
  // A dead loopback gateway PORT at prompt time is the SessionStart revive
500
513
  // signal arriving mid-session: native routing still points this session's
501
- // next request at the local proxy, but a wrap-owned proxy idle-exits after
502
- // its wrap dies and a plain session has no other way to restart it — the
514
+ // next request at the local proxy. Crashes or older proxies that idle-exit
515
+ // can leave a plain session without a way to restart it — the
503
516
  // turn hard-fails with ConnectionRefused. Delegate this one event to the
504
517
  // full CLI, which revives the proxy exactly like SessionStart (and records
505
518
  // the event itself). The port probe — not the dead runtime socket — is the
@@ -5,7 +5,7 @@ export const NATIVE_PACK = {
5
5
  "version": "2.2.0",
6
6
  "protocol": 1,
7
7
  "core": {
8
- "source": "native-core.md",
8
+ "source": "native/native-core.md",
9
9
  "mandatory": true,
10
10
  "prompt_token_budget": 560,
11
11
  "estimated_tokens": 556,
@@ -0,0 +1,111 @@
1
+ // OpenClaw v2026.8.2 (0965053fe6b9341776df147a6934b7485c60b5ca):
2
+ // packages/ai/src/transports/openai-completions-compat.ts
3
+ // packages/ai/src/transports/openai-responses-payload-policy.ts
4
+ // packages/ai/src/providers/anthropic.ts
5
+ // src/agents/provider-attribution.ts, src/config/types.models.ts
6
+ // This is a bounded config-overlay gate, not a copy of OpenClaw's private
7
+ // plugin metadata registry. Unknown host policy must remain in the host.
8
+ function object(value) {
9
+ return value !== null && typeof value === "object" && !Array.isArray(value)
10
+ ? value : undefined;
11
+ }
12
+ function hostname(baseUrl) {
13
+ try {
14
+ return new URL(baseUrl).hostname.toLowerCase();
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ function nativeOpenAIHost(host) {
21
+ return host === "api.openai.com" || host === "chatgpt.com" || [
22
+ ".openai.azure.com", ".cognitiveservices.azure.com", ".services.ai.azure.com", ".api.cognitive.microsoft.com",
23
+ ].some(suffix => host.endsWith(suffix));
24
+ }
25
+ /** Overrides that change the final transport cannot be copied onto localhost. */
26
+ export function openClawRequestCompatibilityIssue(value) {
27
+ if (value === undefined)
28
+ return undefined;
29
+ const request = object(value);
30
+ if (!request)
31
+ return "its request transport overrides could not be resolved";
32
+ const auth = object(request.auth);
33
+ if (request.auth !== undefined && (!auth || auth.mode !== "provider-default")) {
34
+ return "its custom request authentication cannot be preserved through routing";
35
+ }
36
+ if (request.proxy !== undefined || request.tls !== undefined) {
37
+ return "its request proxy or TLS settings belong to the original endpoint";
38
+ }
39
+ if (request.allowPrivateNetwork === false) {
40
+ return "its request policy explicitly disallows the local proxy endpoint";
41
+ }
42
+ if (request.headers !== undefined && !object(request.headers)) {
43
+ return "its request headers could not be resolved";
44
+ }
45
+ return undefined;
46
+ }
47
+ /** Freeze public defaults only when their values do not require private metadata. */
48
+ export function preserveOpenClawProviderCompat(model) {
49
+ const host = hostname(model.baseUrl);
50
+ if (!host)
51
+ return { ok: false, reason: "its original endpoint compatibility could not be resolved" };
52
+ const compat = object(model.compat);
53
+ if (model.compat !== undefined && !compat) {
54
+ return { ok: false, reason: "its explicit model compatibility could not be resolved" };
55
+ }
56
+ if (model.api === "openai-completions") {
57
+ // Even a complete public compat object cannot override the private
58
+ // requiresNonEmptyUserOrAssistantMessage field or the native-route store
59
+ // wrapper. Calling the standalone resolver would guess active metadata.
60
+ return { ok: false, reason: "OpenClaw does not expose the resolved OpenAI Chat provider policy needed to preserve its payload defaults" };
61
+ }
62
+ // OpenClaw normalizes configured provider IDs before matching models and
63
+ // applying transport policy. Keep the config key intact, but compare the
64
+ // same identity its runtime sees (including for public provider defaults).
65
+ const provider = model.provider.trim().toLowerCase();
66
+ // Public model compat cannot freeze xAI's native compact-endpoint decision.
67
+ if (model.api === "openai-responses" && (provider === "xai" || provider === "x-ai") && host === "api.x.ai") {
68
+ return { ok: false, reason: "OpenClaw's native xAI compact-endpoint policy cannot be preserved by public compatibility settings" };
69
+ }
70
+ // These headers are generated after model resolution from endpoint metadata.
71
+ // Static config headers do not recover the installed runtime version, and
72
+ // OpenClaw's attribution defaults take precedence over configured values.
73
+ if ((provider === "openai" && nativeOpenAIHost(host)) ||
74
+ (provider === "openrouter" && (host === "openrouter.ai" || host.endsWith(".openrouter.ai"))) ||
75
+ (provider === "xai" && host === "api.x.ai") ||
76
+ host === "integrate.api.nvidia.com" || host === "generativelanguage.googleapis.com") {
77
+ return { ok: false, reason: "OpenClaw generates endpoint-specific request headers that this config overlay cannot preserve" };
78
+ }
79
+ if (model.api === "openai-responses") {
80
+ if (nativeOpenAIHost(host) || model.baseUrl.includes("api.openai.com")) {
81
+ return { ok: false, reason: "OpenClaw's native Responses cache, replay and service-tier policy cannot be preserved by public compatibility settings" };
82
+ }
83
+ // The bundled Responses payload resolver treats all other routes as
84
+ // non-native. xAI alone additionally defaults to an instructions field.
85
+ // Explicit switches prevent the transport host from re-deriving these
86
+ // public defaults after the endpoint changes to localhost.
87
+ return { ok: true, compat: {
88
+ ...compat,
89
+ supportsStore: compat?.supportsStore ?? true,
90
+ supportsPromptCacheKey: compat?.supportsPromptCacheKey ?? false,
91
+ supportsInstructions: compat?.supportsInstructions ?? host === "api.x.ai",
92
+ } };
93
+ }
94
+ if (model.api === "anthropic-messages") {
95
+ if (provider === "anthropic" && host === "api.anthropic.com") {
96
+ return { ok: false, reason: "OpenClaw's native Anthropic fallback beta, service-tier and stream validation policy cannot be preserved by public compatibility settings" };
97
+ }
98
+ const fireworks = provider === "fireworks";
99
+ return { ok: true, compat: {
100
+ ...compat,
101
+ supportsEagerToolInputStreaming: compat?.supportsEagerToolInputStreaming ?? !fireworks,
102
+ supportsLongCacheRetention: compat?.supportsLongCacheRetention ?? !fireworks,
103
+ sendSessionAffinityHeaders: compat?.sendSessionAffinityHeaders ??
104
+ (fireworks || (provider === "cloudflare-ai-gateway" && model.baseUrl.includes("anthropic"))),
105
+ } };
106
+ }
107
+ if (model.api === "google-generative-ai") {
108
+ return { ok: true, ...(compat ? { compat: { ...compat } } : {}) };
109
+ }
110
+ return { ok: false, reason: `OpenClaw's ${model.api} transport compatibility has not been verified` };
111
+ }
@@ -0,0 +1,147 @@
1
+ export const COMPAT_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
2
+ function endpoint(raw) {
3
+ if (!raw || /[\s?#]/.test(raw))
4
+ return undefined;
5
+ try {
6
+ const url = new URL(raw);
7
+ if (!['http:', 'https:'].includes(url.protocol) || !url.hostname
8
+ || url.username || url.password || url.search || url.hash || url.pathname.includes("//"))
9
+ return undefined;
10
+ // Host SDKs disagree on repeated separators; refuse them rather than
11
+ // normalize a tenant path. Go adapters join decoded path segments.
12
+ // Do not claim equivalence for
13
+ // escaped separators, dot segments, or backslashes normalized by WHATWG URL.
14
+ if (/%|\\/.test(raw) || /(?:^|\/)\.{1,2}(?:\/|$)/.test(raw))
15
+ return undefined;
16
+ return url;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ export function publishedUpstreamsOf(raw) {
23
+ const out = Object.create(null);
24
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
25
+ return out;
26
+ for (const [name, value] of Object.entries(raw)) {
27
+ if (!COMPAT_NAME_RE.test(name))
28
+ continue;
29
+ // Retain an invalid mount as unavailable; it must not fall through to a
30
+ // same-named native provider after its credential-bearing URL is omitted.
31
+ out[name] = typeof value === 'string' && endpoint(value) ? value : '';
32
+ }
33
+ return out;
34
+ }
35
+ /** Linear-time `s.replace(/\/+$/, '')`: that regex backtracks quadratically on a long run of '/'. */
36
+ export function trimTrailingSlashes(s) {
37
+ let end = s.length;
38
+ while (end > 0 && s.charCodeAt(end - 1) === 47)
39
+ end--;
40
+ return s.slice(0, end);
41
+ }
42
+ function append(base, path) {
43
+ return base.origin + base.pathname.replace(/\/+$/, '') + path;
44
+ }
45
+ function compatTarget(base, path) {
46
+ const leftPath = base.pathname.replace(/^\/+|\/+$/g, '');
47
+ const rightPath = path.replace(/^\/+|\/+$/g, '');
48
+ const left = leftPath ? leftPath.split('/') : [];
49
+ const right = rightPath ? rightPath.split('/') : [];
50
+ let overlap = Math.min(left.length, right.length);
51
+ while (overlap > 0 && left.slice(-overlap).join('/') !== right.slice(0, overlap).join('/'))
52
+ overlap--;
53
+ return base.origin + '/' + [...left, ...right.slice(overlap)].join('/');
54
+ }
55
+ export function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, published) {
56
+ const original = endpoint(originalBaseUrl);
57
+ if (!original || !endpoint(gateway))
58
+ return undefined;
59
+ const family = api === 'anthropic-messages' ? 'anthropic'
60
+ : api === 'openai-completions' || api === 'openai-responses' ? 'openai'
61
+ : api === 'google-generative-ai' ? 'gemini' : undefined;
62
+ if (!family)
63
+ return undefined;
64
+ const operation = api === 'anthropic-messages' ? '/v1/messages'
65
+ : api === 'openai-completions' ? '/chat/completions'
66
+ : api === 'openai-responses' ? '/responses' : '/models/caveman-route-proof:streamGenerateContent';
67
+ const expected = append(original, operation);
68
+ const mount = COMPAT_NAME_RE.test(provider) && published?.compat_upstreams
69
+ && Object.hasOwn(published.compat_upstreams, provider) ? published.compat_upstreams[provider] : undefined;
70
+ if (mount !== undefined) {
71
+ const upstream = endpoint(mount);
72
+ if (!upstream || family === 'gemini')
73
+ return undefined;
74
+ const suffix = family === 'openai' ? '/v1' : '';
75
+ if (compatTarget(upstream, suffix + operation) !== expected)
76
+ return undefined;
77
+ return trimTrailingSlashes(gateway) + `/compat/${provider}${suffix}`;
78
+ }
79
+ const upstream = endpoint(published?.provider_upstreams?.[family]);
80
+ if (!upstream)
81
+ return undefined;
82
+ const versions = family === 'gemini' ? ['/v1beta', '/v1'] : [family === 'openai' ? '/v1' : ''];
83
+ for (const version of versions) {
84
+ if (append(upstream, version + operation) === expected) {
85
+ return trimTrailingSlashes(gateway) + `/${family}${version}`;
86
+ }
87
+ }
88
+ return undefined;
89
+ }
90
+ // This is the gateway's ordinary end-to-end header contract for these three
91
+ // wire protocols. Additional mount headers require explicit operator config;
92
+ // preserving them in an overlay alone does not make the proxy forward them.
93
+ const COPIED_HEADERS = ["content-type", "content-encoding", "accept", "accept-encoding", "idempotency-key", "openai-organization", "openai-project", "session_id", "x-session-id", "x-client-request-id", "x-session-affinity", "anthropic-version", "anthropic-beta", "api-version", "user-agent"];
94
+ const COMPAT_HEADERS = {
95
+ openrouter: ["http-referer", "x-openrouter-title", "x-openrouter-categories"],
96
+ nvidia: ["x-billing-invoke-origin"],
97
+ opencode: ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"],
98
+ "opencode-go": ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"],
99
+ };
100
+ export function publishedForwardHeadersOf(raw) {
101
+ const out = Object.create(null);
102
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
103
+ return out;
104
+ for (const [name, values] of Object.entries(raw)) {
105
+ if (COMPAT_NAME_RE.test(name) && Array.isArray(values))
106
+ out[name] = values.filter((v) => typeof v === "string").map(v => v.toLowerCase());
107
+ }
108
+ return out;
109
+ }
110
+ export function unforwardedProviderHeaders(api, provider, headers, published) {
111
+ if (headers == null)
112
+ return [];
113
+ if (typeof headers !== "object" || Array.isArray(headers))
114
+ return ["invalid header configuration"];
115
+ const allowed = new Set(COPIED_HEADERS);
116
+ if (api === "openai-completions" || api === "openai-responses")
117
+ allowed.add("authorization");
118
+ if (api === "anthropic-messages") {
119
+ allowed.add("authorization");
120
+ allowed.add("x-api-key");
121
+ }
122
+ if (api === "google-generative-ai") {
123
+ allowed.add("authorization");
124
+ allowed.add("x-goog-api-key");
125
+ allowed.add("x-goog-user-project");
126
+ }
127
+ if (published?.compat_upstreams && Object.hasOwn(published.compat_upstreams, provider)) {
128
+ for (const name of published.compat_forward_headers?.[provider] ?? [])
129
+ allowed.add(name.toLowerCase());
130
+ if (Object.hasOwn(COMPAT_HEADERS, provider))
131
+ for (const name of COMPAT_HEADERS[provider])
132
+ allowed.add(name);
133
+ }
134
+ return Object.entries(headers).filter(([name, value]) => {
135
+ if (value === undefined)
136
+ return false;
137
+ const lower = name.toLowerCase();
138
+ // SDK custom headers override their generated Authorization verbatim.
139
+ // The proxy's credential mapper supports Bearer on these routes, so Basic,
140
+ // Digest, empty, or explicitly suppressed auth cannot be certified by name.
141
+ if (lower === "authorization")
142
+ return typeof value !== "string" || !/^Bearer +\S+$/i.test(value.trim());
143
+ if (["x-api-key", "x-goog-api-key"].includes(lower) && (typeof value !== "string" || !value.trim()))
144
+ return true;
145
+ return value !== null && !allowed.has(lower);
146
+ }).map(([name]) => name).sort();
147
+ }