@caveman-ai/cli 1.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.
@@ -0,0 +1,61 @@
1
+ // Bundled interactive UI. @clack/prompts remains a build-time dependency only.
2
+ var te=Object.create;var It=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty;var ne=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(s){throw e=0,s}};var oe=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of se(e))!re.call(t,n)&&n!==s&&It(t,n,{get:()=>e[n],enumerable:!(i=ee(e,n))||i.enumerable});return t};var St=(t,e,s)=>(s=t!=null?te(ie(t)):{},oe(e||!t||!t.__esModule?It(s,"default",{value:t,enumerable:!0}):s,t));var dt=ne((as,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"},we={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},Ie={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:we,erase:Ie,beep:"\x07"}});import{styleText as Se}from"node:util";import{stdout as gt,stdin as Dt}from"node:process";import*as G from"node:readline";import be 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 ae=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ue=/[\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,le=/\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"),ce=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,he=new RegExp("\\p{M}+","gu"),pe={limit:1/0,ellipsis:""},Tt=(t,e={},s={})=>{let i=e.limit??1/0,n=e.ellipsis??"",u=e?.ellipsisWidth??(n?Tt(n,pe,s).width:0),o=0,r=s.controlWidth??0,l=s.tabWidth??8,d=s.emojiWidth??2,g=2,h=s.regularWidth??1,p=s.wideWidth??g,m=[[ce,h],[ae,o],[ue,r],[le,l],[Ct,d],[Et,p]],c=0,$=0,b=t.length,A=0,R=!1,V=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(he,"")){let C=P.codePointAt(0)||0;if(_t(C)?S=g:xt(C)?S=p:S=h,I+S>F&&(V=Math.min(V,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,J]=m[x];if(C.lastIndex=$,C.test(t)){if(A=C===Et?bt(t.slice($,C.lastIndex)):C===Ct?1:C.lastIndex-$,S=A*J,I+S>F&&(V=Math.min(V,$+Math.floor((F-I)/J))),I+S>i){R=!0;break t}I+=S,v=c,_=$,$=c=C.lastIndex;continue t}}$+=1}return{width:R?F:I,index:R?V:b,truncated:R,ellipsed:R&&i>=u}},Mt=Tt;var de={limit:1/0,ellipsis:"",ellipsisWidth:0},me=(t,e={})=>Mt(t,de,e).width,T=me;var z="\x1B",Ot="\x9B",ge=39,ct="\x07",Rt="[",fe="]",Pt="m",ht=`${fe}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},Vt=t=>`${z}${Rt}${t}${Pt}`,Lt=t=>`${z}${ht}${t}${ct}`,lt=(t,e,s)=>{let i=e[Symbol.iterator](),n=!1,u=!1,o=t.at(-1),r=o===void 0?0:T(o),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===z||h===Ot)&&(n=!0,u=e.startsWith(ht,g+1)),n?u?h===ct&&(n=!1,u=!1):h===Pt&&(n=!1):(r+=p,r===s&&!d.done&&(t.push(""),r=0)),l=d,d=i.next(),g+=h.length}o=t.at(-1),!r&&o!==void 0&&o.length&&t.length>1&&(t[t.length-2]+=t.pop())},$e=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("")},ve=(t,e,s={})=>{if(s.trim!==!1&&t.trim()==="")return"";let i="",n,u,o=t.split(" "),r=[""],l=0;for(let h=0;h<o.length;h++){let p=o[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=>$e(h)));let d=r.join(`
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===z||p===Ot){At.lastIndex=h+1;let c=At.exec(d)?.groups;if(c?.code!==void 0){let $=Number.parseFloat(c.code);n=$===ge?void 0:$}else c?.uri!==void 0&&(u=c.uri.length===0?void 0:c.uri)}if(d[h+1]===`
4
+ `){u&&(i+=Lt(""));let m=n?Ft(n):void 0;n&&m&&(i+=Vt(m))}else p===`
5
+ `&&(n&&Ft(n)&&(i+=Vt(n)),u&&(i+=Lt(u)))}return i},ye=/\r?\n/;function k(t,e,s){return String(t).normalize().split(ye).map(i=>ve(i,e,s)).join(`
6
+ `)}var M=St(dt(),1);import{ReadStream as Nt}from"node:tty";function Q(t,e,s){if(!s.some(o=>!o.disabled))return t;let i=t+e,n=Math.max(s.length-1,0),u=i<0?n:i>n?0:i;return s[u]?.disabled?Q(u,e<0?-1:1,s):u}var _e=["up","down","left","right","space","enter","cancel"],xe=["January","February","March","April","May","June","July","August","September","October","November","December"],E={actions:new Set(_e),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:[...xe],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 Ee(t,e){if(t===e)return;let s=t.split(`
7
+ `),i=e.split(`
8
+ `),n=Math.max(s.length,i.length),u=[];for(let o=0;o<n;o++)s[o]!==i[o]&&u.push(o);return{lines:u,numLinesBefore:s.length,numLinesAfter:i.length,numLines:n}}var Ce=globalThis.process.platform.startsWith("win"),mt=Symbol("clack:cancel");function W(t){return t===mt}function X(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 n=G.createInterface({input:t,output:e,prompt:"",tabSize:1});G.emitKeypressEvents(t,n),t instanceof Nt&&t.isTTY&&t.setRawMode(!0);let u=(o,{name:r,sequence:l})=>{let d=String(o);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&&!Ce&&t.setRawMode(!1),n.terminal=!1,n.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 et(t,e,s,i=s,n=s,u){let o=K(t??gt);return k(e,o-s.length,{hard:!0,trim:!1}).split(`
9
+ `).map((r,l,d)=>{let g=u?u(r,l):r;return l===0?`${i}${g}`:l===d.length-1?`${n}${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 Z=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:n=gt,render:u,signal:o,...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=o,this.input=i,this.output=n}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)??[],n=[];for(let u of i)u.cb(...s),u.once&&n.push(()=>i.splice(i.indexOf(u),1));for(let u of n)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=be.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),X(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),X(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(M.cursor.show),this.output.off("resize",this.render),X(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
+ `),X(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=Ee(this._prevFrame,e),i=$t(this.output);if(this.restoreCursor(),s){let n=Math.max(0,s.numLinesAfter-i),u=Math.max(0,s.numLinesBefore-i),o=s.lines.find(r=>r>=n);if(o===void 0){this._prevFrame=e;return}if(s.lines.length===1){this.output.write(M.cursor.move(0,o-u)),this.output.write(M.erase.lines(1));let r=e.split(`
13
+ `);this.output.write(r[o]),this._prevFrame=e,this.output.write(M.cursor.move(0,r.length-o-1));return}else if(s.lines.length>1){if(n<u)o=n;else{let l=o-u;l>0&&this.output.write(M.cursor.move(0,l))}this.output.write(M.erase.down());let r=e.split(`
14
+ `).slice(o);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 Z{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:n})=>n===e.initialValue),i=s===-1?0:s;this.cursor=this.options[i]?.disabled?Q(i,1,this.options):i,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=Q(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Q(this.cursor,1,this.options);break}this.changeValue()})}};var tt=class extends Z{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),n=e.slice(this.cursor+1);return`${s}${Se("inverse",i)}${n}`}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 H=St(dt(),1);function Te(){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=Te(),Me=()=>process.env.CI==="true";var f=(t,e)=>vt?t:e,Ae=f("\u25C6","*"),Ht=f("\u25A0","x"),qt=f("\u25B2","x"),it=f("\u25C7","o"),Fe=f("\u250C","T"),y=f("\u2502","|"),U=f("\u2514","\u2014"),As=f("\u2510","T"),Fs=f("\u2518","\u2014"),Ve=f("\u25CF",">"),Ut=f("\u25CB"," "),Vs=f("\u25FB","[\u2022]"),Ls=f("\u25FC","[+]"),Os=f("\u25FB","[ ]"),Rs=f("\u25AA","\u2022"),Bt=f("\u2500","-"),Le=f("\u256E","+"),Oe=f("\u251C","+"),Re=f("\u256F","+"),Pe=f("\u2570","+"),Ps=f("\u256D","+"),ke=f("\u25CF","\u2022"),Ne=f("\u25C6","*"),De=f("\u25B2","!"),Ge=f("\u25A0","x"),Jt=t=>{switch(t){case"initial":case"active":return a("cyan",Ae);case"cancel":return a("red",Ht);case"error":return a("yellow",qt);case"submit":return a("green",it)}},je=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 We(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,n,u=!1)=>{let o=e,r=0;if(u)for(let l=i-1;l>=s;l--){let d=t[l];if(d&&(o-=d.length),r++,o<=n)break}else for(let l=s;l<i;l++){let d=t[l];if(d&&(o-=d.length),r++,o<=n)break}return{lineCount:o,removals:r}},Ue=({cursor:t,options:e,style:s,output:i=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:u=0,rowPadding:o=4})=>{let r=K(i)-u,l=$t(i),d=a("dim","..."),g=Math.max(l-o,0),h=Math.max(Math.min(n,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),V=$-(c?1:0);for(let v=R;v<V;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 ks=[`${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:n=1,withGuide:u}={})=>{let o=[],r=u??E.withGuide,l=r?s:"",d=r?`${e} `:"",g=r?`${s} `:"";for(let p=0;p<n;p++)o.push(l);let h=Array.isArray(t)?t:t.split(`
17
+ `);if(h.length>0){let[p,...m]=h;p.length>0?o.push(`${d}${p}`):o.push(r?e:"");for(let c of m)c.length>0?o.push(`${g}${c}`):o.push(r?s:"")}i.write(`${o.join(`
18
+ `)}
19
+ `)},info:(t,e)=>{j.message(t,{...e,symbol:a("blue",ke)})},success:(t,e)=>{j.message(t,{...e,symbol:a("green",Ne)})},step:(t,e)=>{j.message(t,{...e,symbol:a("green",it)})},warn:(t,e)=>{j.message(t,{...e,symbol:a("yellow",De)})},warning:(t,e)=>{j.warn(t,e)},error:(t,e)=>{j.message(t,{...e,symbol:a("red",Ge)})}},rt=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??E.withGuide?`${a("gray",U)} `:"";s.write(`${i}${a("red",t)}
20
+
21
+ `)},Yt=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??E.withGuide?`${a("gray",Fe)} `:"";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}
24
+
25
+ `)};var Be=t=>t,Ke=(t,e,s)=>{let i={hard:!0,trim:!1},n=k(t,e,i).split(`
26
+ `),u=n.reduce((l,d)=>Math.max(T(d),l),0),o=n.map(s).reduce((l,d)=>Math.max(T(d),l),0),r=e-(o-u);return k(t,r,i)},nt=(t="",e="",s)=>{let i=s?.output??O.stdout,n=s?.withGuide??E.withGuide,u=s?.format??Be,o=["",...Ke(t,K(i)-6,u).split(`
27
+ `).map(u),""],r=T(e),l=Math.max(o.reduce((p,m)=>{let c=T(m);return c>p?c:p},0),r)+2,d=o.map(p=>`${a("gray",y)} ${p}${" ".repeat(l-T(p))}${a("gray",y)}`).join(`
28
+ `),g=n?`${a("gray",y)}
29
+ `:"",h=n?Oe:Pe;i.write(`${g}${a("green",it)} ${a("reset",e)} ${a("gray",Bt.repeat(Math.max(l-r-1,1))+Le)}
30
+ ${d}
31
+ ${a("gray",h+Bt.repeat(l+2)+Re)}
32
+ `)};var He=t=>a("magenta",t),zt=({indicator:t="dots",onCancel:e,output:s=process.stdout,cancelMessage:i,errorMessage:n,frames:u=vt?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=vt?80:120,signal:r,...l}={})=>{let d=Me(),g,h,p=!1,m=!1,c="",$,b=performance.now(),A=K(s),R=l?.styleFrame??He,V=w=>{let L=w>1?n??E.messages.error:i??E.messages.cancel;m=w===1,p&&(B(L,w),m&&typeof e=="function"&&e())},F=()=>V(2),v=()=>V(1),_=()=>{process.on("uncaughtExceptionMonitor",F),process.on("unhandledRejection",F),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",V),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",V),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 L=(performance.now()-w)/1e3,N=Math.floor(L/60),D=Math.floor(L%60);return N>0?`[${N}m ${D}s]`:`[${D}s]`},C=l.withGuide??E.withGuide,J=(w="")=>{p=!0,g=Gt({output:s}),c=x(w),b=performance.now(),C&&s.write(`${a("gray",y)}
35
+ `);let L=0,N=0;_(),h=setInterval(()=>{if(d&&c===$)return;S(),$=c;let D=R(u[L]),Y;if(d)Y=`${D} ${c}...`;else if(t==="timer")Y=`${D} ${c} ${P(b)}`;else{let Zt=".".repeat(Math.floor(N)).slice(0,3);Y=`${D} ${c}${Zt}`}let Qt=k(Y,A,{hard:!0,trim:!1});s.write(Qt),L=L+1<u.length?L+1:0,N=N<4?N+.125:0},o)},B=(w="",L=0,N=!1)=>{if(!p)return;p=!1,clearInterval(h),S();let D=L===0?a("green",it):L===1?a("red",Ht):a("red",qt);c=w??c,N||(t==="timer"?s.write(`${D} ${c} ${P(b)}
36
+ `):s.write(`${D} ${c}
37
+ `)),I(),g()};return{start:J,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}}},Ns={light:f("\u2500","-"),heavy:f("\u2501","="),block:f("\u2588","#")};var qe=[`${a("dim","\u2191/\u2193")} to navigate`,`${a("dim","Enter:")} confirm`],st=(t,e)=>t.includes(`
38
+ `)?t.split(`
39
+ `).map(s=>e(s)).join(`
40
+ `):e(t),yt=t=>{let e=(i,n)=>{if(i===void 0)return"";let u=i.label??String(i.value);switch(n){case"disabled":return`${a("gray",Ut)} ${st(u,o=>a("gray",o))}${i.hint?` ${a("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${st(u,o=>a("dim",o))}`;case"active":return`${a("green",Ve)} ${u}${i.hint?` ${a("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${st(u,o=>a(["strikethrough","dim"],o))}`;default:return`${a("dim",Ut)} ${st(u,o=>a("dim",o))}`}},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,n=`${Jt(this.state)} `,u=`${je(this.state)} `,o=et(t.output,t.message,u,n),r=`${i?`${a("gray",y)}
41
+ `:""}${o}
42
+ `;switch(this.state){case"submit":{let l=i?`${a("gray",y)} `:"",d=et(t.output,e(this.options[this.cursor],"selected"),l);return`${r}${d}`}case"cancel":{let l=i?`${a("gray",y)} `:"",d=et(t.output,e(this.options[this.cursor],"cancelled"),l);return`${r}${d}${i?`
43
+ ${a("gray",y)}`:""}`}default:{let l=i?`${a("cyan",y)} `:"",d=r.split(`
44
+ `).length,g=s?We(qe,i):i?[a("cyan",U)]:[],h=g.join(`
45
+ `),p=g.length+1;return`${r}${l}${Ue({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
+ ${l}`)}
47
+ ${h}
48
+ `}}}}).prompt()};var Ds=`${a("gray",y)} `;var Xt=t=>new tt({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)}
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"],"_"),n=this.userInput?this.userInputWithCursor:i,u=this.value??"";switch(this.state){case"error":{let o=this.error?` ${a("yellow",this.error)}`:"",r=e?`${a("yellow",y)} `:"",l=e?a("yellow",U):"";return`${s.trim()}
51
+ ${r}${n}
52
+ ${l}${o}
53
+ `}case"submit":{let o=u?` ${a("dim",u)}`:"",r=e?a("gray",y):"";return`${s}${r}${o}`}case"cancel":{let o=u?` ${a(["strikethrough","dim"],u)}`:"",r=e?a("gray",y):"";return`${s}${r}${o}${u.trim()?`
54
+ ${r}`:""}`}default:{let o=e?`${a("cyan",y)} `:"",r=e?a("cyan",U):"";return`${s}${o}${n}
55
+ ${r}
56
+ `}}}}).prompt();var Ye=!process.env.NO_COLOR&&!!process.stdout.isTTY,ut=(t,e)=>Ye?`\x1B[${t}m${e}\x1B[0m`:e,ot=t=>ut("1",t),at=t=>ut("2",t),wt=t=>ut("32",t),ze=t=>ut("33",t);function Xe(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 Qe(t){return[ot(t.title),wt(t.detail),...t.action?[at(t.action)]:[]].join(`
57
+ `)}function js(){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 Ws(t){let e=await yt({message:"Implement findings with",options:t});return W(e)?(rt("Implementation cancelled"),null):e}async function Us(t){if(Yt(`${wt(ot(" CAVEMAN "))} ${at("LEARN / LOCAL SETUP")}`),t.score!==null){let i=Math.max(0,Math.min(100,Math.round(t.score))),n=[`${wt(Xe(i))} ${ot(`${i}/100`)}`,at(t.scope),t.sessions,...t.diff?[ze(t.diff)]:[]].join(`
58
+ `);nt(n,"SETUP SCORE")}else nt([t.sessions,...t.status?[t.status]:[]].join(`
59
+ `),"LEARN RESULT");if(t.moves.length>0){let i=t.moves.map((n,u)=>`${at(String(u+1).padStart(2,"0"))} ${Qe(n)}`);nt(i.join(`
60
+
61
+ `),"TOP MOVES")}t.protected&&j.warn(`${ot("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 rt("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)?(rt("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{js as createLearnProgress,Qe as learnMoveBody,Xe as learnScoreBar,Us as renderLearnTui,Ws as selectLearnAgent};
@@ -0,0 +1,456 @@
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { appendFileSync, chmodSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { connect as netConnect } from "node:net";
6
+ import { createHash } from "node:crypto";
7
+ import { fileURLToPath } from "node:url";
8
+ const PROFILES = new Set(["record-only", "core", "core-lean-build", "ledger", "ccr-masking", "cache-aware", "full-safe", "full-max"]);
9
+ const ACTIONS = new Set(["allow", "observe", "block", "ask", "defer"]);
10
+ const VISIBILITY = new Set(["silent", "advisory", "user"]);
11
+ const EVENTS = new Set(["SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PostToolUseFailure", "ModelBefore", "ModelAfter", "PreCompact", "PostCompact", "SubagentStart", "SubagentStop", "Stop", "SessionEnd"]);
12
+ const PROTOCOL_EVENTS = {
13
+ SessionStart: "session.start", UserPromptSubmit: "prompt.submit", PreToolUse: "tool.before", PermissionRequest: "tool.before",
14
+ PostToolUse: "tool.after", PostToolUseFailure: "tool.failure", ModelBefore: "model.before", ModelAfter: "model.after",
15
+ PreCompact: "context.compact.before", PostCompact: "context.compact.after", SubagentStart: "subagent.start",
16
+ SubagentStop: "subagent.stop", Stop: "turn.stop", SessionEnd: "session.end",
17
+ };
18
+ const TASK_STOPWORDS = new Set(["about", "after", "again", "agent", "before", "build", "change", "code", "could", "create", "does", "from", "have", "help", "implement", "into", "make", "please", "project", "repository", "should", "spec", "task", "that", "their", "then", "there", "these", "they", "this", "through", "user", "want", "what", "when", "where", "which", "with", "would", "your"]);
19
+ function caveHome() {
20
+ return process.env.CAVEMAN_HOME ?? join(homedir(), ".caveman");
21
+ }
22
+ function object(value) {
23
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
24
+ }
25
+ function configuredMode() {
26
+ const explicit = process.env.CAVEMAN_WRAP_MODE;
27
+ if (explicit !== undefined)
28
+ return explicit === "compress" || explicit === "pixel" || explicit === "record" ? explicit : "record";
29
+ try {
30
+ const config = object(JSON.parse(readFileSync(join(homedir(), ".caveman-cloud", "config.json"), "utf8")));
31
+ const legacy = object(config.wrap).mode;
32
+ const current = object(config.think).mode;
33
+ const value = current ?? legacy;
34
+ if (value !== undefined)
35
+ return value === "compress" || value === "pixel" || value === "record" ? value : "record";
36
+ }
37
+ catch { /* default below */ }
38
+ return "compress";
39
+ }
40
+ function configuredCore() {
41
+ const parse = (value) => {
42
+ if (typeof value === "boolean")
43
+ return value;
44
+ if (typeof value !== "string")
45
+ return undefined;
46
+ const normalized = value.trim().toLowerCase();
47
+ if (["1", "true", "yes", "on"].includes(normalized))
48
+ return true;
49
+ if (["0", "false", "no", "off"].includes(normalized))
50
+ return false;
51
+ return undefined;
52
+ };
53
+ let configured = true;
54
+ try {
55
+ const config = object(JSON.parse(readFileSync(join(homedir(), ".caveman-cloud", "config.json"), "utf8")));
56
+ configured = parse(object(config.think).core) ?? true;
57
+ }
58
+ catch { /* default above */ }
59
+ const env = process.env.CAVEMAN_CORE;
60
+ return env === undefined ? configured : parse(env) ?? configured;
61
+ }
62
+ function policyMode() {
63
+ const profile = process.env.CAVEMAN_NATIVE_PROFILE?.trim().toLowerCase();
64
+ if (profile && !PROFILES.has(profile))
65
+ return "record";
66
+ if (profile === "record-only")
67
+ return "record";
68
+ const explicit = process.env.CAVEMAN_NATIVE_MODE?.trim().toLowerCase();
69
+ if (explicit !== undefined && explicit !== "")
70
+ return explicit === "safe" || explicit === "max" || explicit === "record" ? explicit : "record";
71
+ const mode = configuredMode();
72
+ return mode === "record" ? "record" : mode === "pixel" ? "max" : "safe";
73
+ }
74
+ function profile() {
75
+ const explicit = process.env.CAVEMAN_NATIVE_PROFILE?.trim().toLowerCase();
76
+ if (explicit)
77
+ return PROFILES.has(explicit) ? explicit : "record-only";
78
+ const mode = policyMode();
79
+ return mode === "record" ? "record-only" : mode === "max" ? "full-max" : "full-safe";
80
+ }
81
+ async function stdin() {
82
+ const chunks = [];
83
+ let bytes = 0;
84
+ for await (const chunk of process.stdin) {
85
+ const value = Buffer.from(chunk);
86
+ bytes += value.length;
87
+ if (bytes > 2 * 1024 * 1024)
88
+ throw new Error("hook payload too large");
89
+ chunks.push(value);
90
+ }
91
+ return Buffer.concat(chunks);
92
+ }
93
+ function bounded(value, max = 160) {
94
+ if (typeof value !== "string")
95
+ return undefined;
96
+ const clean = value.replace(/[\r\n\0]/g, " ").trim();
97
+ return clean ? clean.slice(0, max) : undefined;
98
+ }
99
+ function digestObject(value) {
100
+ if (value && typeof value === "object" && !Array.isArray(value)) {
101
+ const candidate = value;
102
+ if (typeof candidate.bytes === "number" && candidate.bytes >= 0 && typeof candidate.sha256 === "string" && /^sha256:[0-9a-f]{6,64}$/i.test(candidate.sha256)) {
103
+ return { bytes: Math.floor(candidate.bytes), sha256: candidate.sha256.toLowerCase() };
104
+ }
105
+ }
106
+ return undefined;
107
+ }
108
+ function digest(value) {
109
+ const existing = digestObject(value);
110
+ if (existing)
111
+ return existing;
112
+ if (typeof value !== "string")
113
+ return undefined;
114
+ const bytes = Buffer.from(value, "utf8");
115
+ return { bytes: bytes.length, sha256: `sha256:${createHash("sha256").update(bytes).digest("hex")}` };
116
+ }
117
+ function taskType(value) {
118
+ if (typeof value !== "string")
119
+ return "general";
120
+ const text = value.toLowerCase();
121
+ if (/\b(migrat(?:e|ion)|schema change|backfill|rollback)\b/.test(text))
122
+ return "migration";
123
+ if (/\b(bug|fix|broken|regression|crash|error|fails?|incorrect)\b/.test(text))
124
+ return "bugfix";
125
+ if (/\b(investigat(?:e|ion)|diagnos(?:e|is)|root cause|why does|trace)\b/.test(text))
126
+ return "investigation";
127
+ if (/\b(refactor|restructure|reorganize|cleanup|clean up)\b/.test(text))
128
+ return "refactor";
129
+ if (/\b(review|audit|critique|assess)\b/.test(text))
130
+ return "review";
131
+ if (/\b(verif(?:y|ication)|test only|prove|validate|check that)\b/.test(text))
132
+ return "verification";
133
+ if (/\b(build|implement|add|create|ship|feature)\b/.test(text))
134
+ return "feature";
135
+ return "general";
136
+ }
137
+ function taskContinuation(value, claimed) {
138
+ if (typeof value !== "string")
139
+ return claimed === true;
140
+ const prompt = value.trim().toLowerCase();
141
+ if (!prompt || prompt.length > 160 || prompt.split(/\s+/).length > 14)
142
+ return false;
143
+ return /^(?:please\s+)?(?:continue|go ahead|keep going|proceed|do (?:it|that)|fix (?:it|that)|retry|try again|explain (?:it|that)|what do you mean|yes|yep|yeah|why\??|how\??)[.!?\s]*$/.test(prompt);
144
+ }
145
+ function taskTerms(value, claimed) {
146
+ const source = typeof value === "string" ? value.match(/[A-Za-z][A-Za-z0-9_./-]{2,63}/g) ?? [] : Array.isArray(claimed) ? claimed.filter((item) => typeof item === "string") : [];
147
+ const seen = new Set();
148
+ const terms = [];
149
+ for (const raw of source) {
150
+ const term = raw.toLowerCase().replace(/^[-./]+|[-./]+$/g, "");
151
+ if (!term || term.length < 3 || term.length > 64 || term.includes("..") || term.startsWith("/") || TASK_STOPWORDS.has(term) || seen.has(term))
152
+ continue;
153
+ if (/^(?:sk|pk|rk|ghp|github_pat|xox[baprs]|akia)[-_]/i.test(term) || /^[a-z0-9_-]{40,}$/i.test(term))
154
+ continue;
155
+ seen.add(term);
156
+ terms.push(term);
157
+ if (terms.length === 12)
158
+ break;
159
+ }
160
+ return terms;
161
+ }
162
+ function exactOutput(event) {
163
+ const value = event.tool_output ?? event.tool_response ?? event.output ?? event.result;
164
+ if (value === undefined || digestObject(value))
165
+ return undefined;
166
+ if (typeof value === "string")
167
+ return Buffer.from(value, "utf8").toString("base64");
168
+ try {
169
+ return Buffer.from(JSON.stringify(value), "utf8").toString("base64");
170
+ }
171
+ catch {
172
+ return undefined;
173
+ }
174
+ }
175
+ function inputState(input, cwd) {
176
+ if (!input || typeof input !== "object" || Array.isArray(input) || !cwd)
177
+ return undefined;
178
+ const values = input;
179
+ const raw = [values.path, values.file_path, values.file, values.filename].find((value) => typeof value === "string" && value.trim() !== "");
180
+ if (!raw || raw.includes("\0"))
181
+ return undefined;
182
+ try {
183
+ const path = resolve(cwd, raw);
184
+ const stat = statSync(path);
185
+ const identity = JSON.stringify({ path: realpathSync(path), size: stat.size, mtime_ms: stat.mtimeMs, mode: stat.mode });
186
+ return `sha256:${createHash("sha256").update(identity).digest("hex")}`;
187
+ }
188
+ catch {
189
+ return undefined;
190
+ }
191
+ }
192
+ function needsRepositoryState(name, input) {
193
+ const lower = name.toLowerCase();
194
+ if (lower.includes("search") || lower.includes("grep") || lower === "rg" || lower.includes("find"))
195
+ return true;
196
+ if (!input || typeof input !== "object" || Array.isArray(input))
197
+ return false;
198
+ const values = input;
199
+ const command = typeof values.command === "string" ? values.command : typeof values.cmd === "string" ? values.cmd : "";
200
+ return /(?:^|\s)(?:go\s+test|pytest|test|go\s+build|build)(?:\s|$)/.test(command);
201
+ }
202
+ function gitDir(cwd) {
203
+ let current = resolve(cwd);
204
+ for (;;) {
205
+ const candidate = join(current, ".git");
206
+ try {
207
+ const stat = lstatSync(candidate);
208
+ if (stat.isDirectory())
209
+ return candidate;
210
+ if (stat.isFile()) {
211
+ const match = readFileSync(candidate, "utf8").match(/^gitdir:\s*(.+)\s*$/m);
212
+ if (match?.[1])
213
+ return resolve(current, match[1]);
214
+ }
215
+ }
216
+ catch { /* ascend */ }
217
+ const parent = dirname(current);
218
+ if (parent === current)
219
+ return undefined;
220
+ current = parent;
221
+ }
222
+ }
223
+ function repositoryState(cwd) {
224
+ if (!cwd)
225
+ return undefined;
226
+ try {
227
+ const status = execFileSync("git", ["-C", cwd, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=all"], {
228
+ timeout: 100, maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"],
229
+ });
230
+ const directory = gitDir(cwd);
231
+ if (!directory)
232
+ return undefined;
233
+ const hash = createHash("sha256");
234
+ hash.update(realpathSync(cwd));
235
+ hash.update("\0status\0");
236
+ hash.update(status);
237
+ let bytes = 0;
238
+ const include = (label, path) => {
239
+ hash.update(`\0${label}\0${path}\0`);
240
+ try {
241
+ const stat = lstatSync(path);
242
+ if (!stat.isFile()) {
243
+ hash.update(`mode:${stat.mode}:size:${stat.size}`);
244
+ return true;
245
+ }
246
+ if (bytes + stat.size > 8 * 1024 * 1024)
247
+ return false;
248
+ const data = readFileSync(path);
249
+ bytes += data.length;
250
+ hash.update(data);
251
+ return true;
252
+ }
253
+ catch {
254
+ hash.update("missing");
255
+ return true;
256
+ }
257
+ };
258
+ if (!include("index", join(directory, "index")))
259
+ return undefined;
260
+ for (const field of status.toString("utf8").split("\0").filter(Boolean)) {
261
+ if (field.startsWith("## "))
262
+ continue;
263
+ const relative = field.length >= 4 && field[2] === " " ? field.slice(3) : field;
264
+ if (!relative || !include("changed", resolve(cwd, relative)))
265
+ return undefined;
266
+ }
267
+ return `git:sha256:${hash.digest("hex")}`;
268
+ }
269
+ catch {
270
+ return undefined;
271
+ }
272
+ }
273
+ function request(agent, eventName, sessionID, event) {
274
+ const cwd = bounded(event.cwd ?? event.working_directory ?? event.workingDirectory ?? process.cwd(), 4096);
275
+ const claimedRepositoryState = bounded(event.repository_state ?? event.repositoryState, 512);
276
+ const session = {
277
+ caveman_session_id: `${agent}:${sessionID}`,
278
+ host_session_id: sessionID,
279
+ parent_session_id: bounded(event.parent_session_id ?? event.parentSessionId),
280
+ cwd,
281
+ repository_state: claimedRepositoryState,
282
+ };
283
+ const out = {
284
+ protocol_version: 1,
285
+ policy_mode: policyMode(),
286
+ profile: profile(),
287
+ agent: { id: agent, version: bounded(event.agent_version ?? event.version), surface: bounded(event.surface ?? event.platform) },
288
+ session,
289
+ event: { type: PROTOCOL_EVENTS[eventName], timestamp_ms: Date.now() },
290
+ };
291
+ const promptValue = event.prompt ?? event.user_prompt ?? event.userMessage;
292
+ const prompt = digest(promptValue);
293
+ if (prompt) {
294
+ out.prompt = prompt;
295
+ out.task_profile = {
296
+ type: typeof promptValue === "string" ? taskType(promptValue) : bounded(event.task_type ?? event.taskType) ?? "general",
297
+ terms: taskTerms(promptValue, event.task_terms ?? event.taskTerms),
298
+ continuation: taskContinuation(promptValue, event.task_continuation ?? event.taskContinuation),
299
+ };
300
+ }
301
+ const toolName = bounded(event.tool_name ?? event.toolName);
302
+ if (toolName) {
303
+ const tool = { name: toolName };
304
+ const input = event.tool_input ?? event.toolInput ?? event.args;
305
+ if (input !== undefined) {
306
+ tool.input = input;
307
+ const state = inputState(input, cwd);
308
+ if (state)
309
+ tool.input_state = state;
310
+ if (needsRepositoryState(toolName, input))
311
+ session.repository_state = repositoryState(cwd) ?? claimedRepositoryState;
312
+ }
313
+ const output = exactOutput(event);
314
+ if (output)
315
+ tool.output = output;
316
+ out.tool = tool;
317
+ }
318
+ return out;
319
+ }
320
+ function validResponse(value) {
321
+ if (!value || typeof value !== "object" || Array.isArray(value))
322
+ return false;
323
+ const response = value;
324
+ if (response.protocol_version !== 1 || typeof response.action !== "string" || !ACTIONS.has(response.action))
325
+ return false;
326
+ if (typeof response.visibility !== "string" || !VISIBILITY.has(response.visibility) || response.fail_open !== true)
327
+ return false;
328
+ if (response.policy_mode !== undefined && response.policy_mode !== "record" && response.policy_mode !== "safe" && response.policy_mode !== "max")
329
+ return false;
330
+ if (response.profile !== undefined && (typeof response.profile !== "string" || !PROFILES.has(response.profile)))
331
+ return false;
332
+ return [[response.context, 64 * 1024], [response.message, 4096], [response.output_replacement, 2 * 1024 * 1024], [response.recovery_ref, 1024], [response.decision_id, 256]]
333
+ .every(([field, max]) => field === undefined || (typeof field === "string" && Buffer.byteLength(field) <= max));
334
+ }
335
+ function callRuntime(value) {
336
+ return new Promise((settle) => {
337
+ let done = false;
338
+ let bytes = 0;
339
+ const chunks = [];
340
+ const endpoint = process.platform === "win32"
341
+ ? `\\\\.\\pipe\\caveman-native-${createHash("sha256").update(resolve(caveHome()).replaceAll("/", "\\").toLowerCase()).digest("hex").slice(0, 16)}`
342
+ : join(caveHome(), "run", "native.sock");
343
+ const socket = netConnect({ path: endpoint });
344
+ const finish = (response) => {
345
+ if (done)
346
+ return;
347
+ done = true;
348
+ socket.destroy();
349
+ settle(response);
350
+ };
351
+ socket.setTimeout(250);
352
+ socket.on("connect", () => socket.end(`${JSON.stringify(value)}\n`));
353
+ socket.on("data", (chunk) => {
354
+ bytes += chunk.length;
355
+ if (bytes > 2 * 1024 * 1024)
356
+ return finish();
357
+ chunks.push(chunk);
358
+ });
359
+ socket.on("end", () => {
360
+ try {
361
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
362
+ finish(validResponse(parsed) ? parsed : undefined);
363
+ }
364
+ catch {
365
+ finish();
366
+ }
367
+ });
368
+ socket.on("timeout", () => finish());
369
+ socket.on("error", () => finish());
370
+ });
371
+ }
372
+ function fallback(entry) {
373
+ try {
374
+ const path = join(caveHome(), "runtime", "native-events.jsonl");
375
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
376
+ appendFileSync(path, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
377
+ chmodSync(path, 0o600);
378
+ }
379
+ catch { /* host remains fail-open */ }
380
+ }
381
+ function delegateToFullCLI(raw, agent) {
382
+ const cli = join(dirname(fileURLToPath(import.meta.url)), "index.js");
383
+ const result = spawnSync(process.execPath, [cli, "native-hook", agent], { input: raw, maxBuffer: 3 * 1024 * 1024, env: process.env });
384
+ if (!result.error && result.status === 0) {
385
+ if (result.stdout?.length)
386
+ process.stdout.write(result.stdout);
387
+ if (result.stderr?.length)
388
+ process.stderr.write(result.stderr);
389
+ }
390
+ }
391
+ async function main() {
392
+ const agentArg = process.argv[2] === "native-hook" ? process.argv[3] : process.argv[2];
393
+ const agent = agentArg === "claude" || agentArg === "codex" || agentArg === "hermes" || agentArg === "gemini" || agentArg === "opencode" ? agentArg : undefined;
394
+ if (!agent)
395
+ return;
396
+ let raw;
397
+ let event;
398
+ try {
399
+ raw = await stdin();
400
+ const parsed = JSON.parse(raw.toString("utf8") || "{}");
401
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
402
+ return;
403
+ event = parsed;
404
+ }
405
+ catch {
406
+ return;
407
+ }
408
+ const rawName = bounded(event.hook_event_name ?? event.event_name ?? event.event ?? process.argv[4]);
409
+ const mapped = agent === "gemini" && rawName ? { BeforeAgent: "UserPromptSubmit", BeforeTool: "PreToolUse", AfterTool: "PostToolUse", BeforeModel: "ModelBefore", AfterModel: "ModelAfter", PreCompress: "PreCompact", AfterAgent: "Stop" }[rawName] ?? rawName : rawName;
410
+ const eventName = mapped && EVENTS.has(mapped) ? mapped : "Unknown";
411
+ if (eventName === "SessionStart" || eventName === "PostCompact") {
412
+ delegateToFullCLI(raw, agent);
413
+ return;
414
+ }
415
+ const sessionID = bounded(event.session_id ?? event.sessionId);
416
+ const entry = {
417
+ protocol_version: 1,
418
+ recorded_at: new Date().toISOString(),
419
+ agent,
420
+ event: eventName,
421
+ payload_bytes: raw.length,
422
+ payload_sha256: `sha256:${createHash("sha256").update(raw).digest("hex")}`,
423
+ };
424
+ if (sessionID)
425
+ entry.host_session_id = sessionID;
426
+ const toolName = bounded(event.tool_name ?? event.toolName);
427
+ if (toolName)
428
+ entry.tool_name = toolName;
429
+ const cwd = bounded(event.cwd, 4096);
430
+ if (cwd)
431
+ entry.cwd_sha256 = `sha256:${createHash("sha256").update(cwd).digest("hex")}`;
432
+ const runtimeRequest = sessionID && eventName !== "Unknown" ? request(agent, eventName, sessionID, event) : undefined;
433
+ const response = runtimeRequest ? await callRuntime(runtimeRequest) : undefined;
434
+ if (!response)
435
+ fallback(entry);
436
+ if (eventName === "SessionEnd" && response?.message)
437
+ process.stderr.write(`${response.message}\n`);
438
+ const mode = policyMode();
439
+ const context = mode === "record" || !configuredCore() ? undefined : response?.context;
440
+ if (agent === "hermes" && eventName === "UserPromptSubmit" && context) {
441
+ process.stdout.write(JSON.stringify({ context }));
442
+ }
443
+ else if (context && eventName === "UserPromptSubmit") {
444
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: eventName, additionalContext: context } }));
445
+ }
446
+ else if (context && (eventName === "PreToolUse" || eventName === "PermissionRequest")) {
447
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: eventName, additionalContext: context } }));
448
+ }
449
+ else if (mode !== "record" && agent === "claude" && eventName === "PostToolUse" && response?.output_replacement) {
450
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", updatedToolOutput: response.output_replacement } }));
451
+ }
452
+ else if (mode !== "record" && agent === "opencode" && eventName === "PostToolUse" && response) {
453
+ process.stdout.write(JSON.stringify(response));
454
+ }
455
+ }
456
+ await main();