olympus-ai 3.6.1 → 3.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
  // Olympus Hooks Bundle - Generated by esbuild
3
- "use strict";var Su=Object.create;var Gt=Object.defineProperty;var Tu=Object.getOwnPropertyDescriptor;var wu=Object.getOwnPropertyNames;var _u=Object.getPrototypeOf,Ou=Object.prototype.hasOwnProperty;var O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vu=(e,t)=>{for(var n in t)Gt(e,n,{get:t[n],enumerable:!0})},Rr=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of wu(t))!Ou.call(e,r)&&r!==n&&Gt(e,r,{get:()=>t[r],enumerable:!(o=Tu(t,r))||o.enumerable});return e};var H=(e,t,n)=>(n=e!=null?Su(_u(e)):{},Rr(t||!e||!e.__esModule?Gt(n,"default",{value:e,enumerable:!0}):n,e)),Ru=e=>Rr(Gt({},"__esModule",{value:!0}),e);var W=O(to=>{"use strict";to.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,o)=>{t.push((r,i)=>r!=null?o(r):n(i)),e.apply(this,t)})},"name",{value:e.name})};to.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!="function")return e.apply(this,t);t.pop(),e.apply(this,t).then(o=>n(null,o),n)},"name",{value:e.name})}});var Ii=O((_h,Ri)=>{var xe=require("constants"),Zu=process.cwd,Jt=null,ed=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Jt||(Jt=Zu.call(process)),Jt};try{process.cwd()}catch{}typeof process.chdir=="function"&&(no=process.chdir,process.chdir=function(e){Jt=null,no.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,no));var no;Ri.exports=td;function td(e){xe.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=i(e.chown),e.fchown=i(e.fchown),e.lchown=i(e.lchown),e.chmod=o(e.chmod),e.fchmod=o(e.fchmod),e.lchmod=o(e.lchmod),e.chownSync=s(e.chownSync),e.fchownSync=s(e.fchownSync),e.lchownSync=s(e.lchownSync),e.chmodSync=r(e.chmodSync),e.fchmodSync=r(e.fchmodSync),e.lchmodSync=r(e.lchmodSync),e.stat=c(e.stat),e.fstat=c(e.fstat),e.lstat=c(e.lstat),e.statSync=a(e.statSync),e.fstatSync=a(e.fstatSync),e.lstatSync=a(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(u,d,f){f&&process.nextTick(f)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,f,g){g&&process.nextTick(g)},e.lchownSync=function(){}),ed==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(f,g,m){var p=Date.now(),h=0;u(f,g,function y(T){if(T&&(T.code==="EACCES"||T.code==="EPERM"||T.code==="EBUSY")&&Date.now()-p<6e4){setTimeout(function(){e.stat(g,function(k,A){k&&k.code==="ENOENT"?u(f,g,y):m(T)})},h),h<100&&(h+=10);return}m&&m(T)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(f,g,m,p,h,y){var T;if(y&&typeof y=="function"){var k=0;T=function(A,D,R){if(A&&A.code==="EAGAIN"&&k<10)return k++,u.call(e,f,g,m,p,h,T);y.apply(this,arguments)}}return u.call(e,f,g,m,p,h,T)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,f,g,m,p){for(var h=0;;)try{return u.call(e,d,f,g,m,p)}catch(y){if(y.code==="EAGAIN"&&h<10){h++;continue}throw y}}})(e.readSync);function t(u){u.lchmod=function(d,f,g){u.open(d,xe.O_WRONLY|xe.O_SYMLINK,f,function(m,p){if(m){g&&g(m);return}u.fchmod(p,f,function(h){u.close(p,function(y){g&&g(h||y)})})})},u.lchmodSync=function(d,f){var g=u.openSync(d,xe.O_WRONLY|xe.O_SYMLINK,f),m=!0,p;try{p=u.fchmodSync(g,f),m=!1}finally{if(m)try{u.closeSync(g)}catch{}else u.closeSync(g)}return p}}function n(u){xe.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,f,g,m){u.open(d,xe.O_SYMLINK,function(p,h){if(p){m&&m(p);return}u.futimes(h,f,g,function(y){u.close(h,function(T){m&&m(y||T)})})})},u.lutimesSync=function(d,f,g){var m=u.openSync(d,xe.O_SYMLINK),p,h=!0;try{p=u.futimesSync(m,f,g),h=!1}finally{if(h)try{u.closeSync(m)}catch{}else u.closeSync(m)}return p}):u.futimes&&(u.lutimes=function(d,f,g,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function o(u){return u&&function(d,f,g){return u.call(e,d,f,function(m){l(m)&&(m=null),g&&g.apply(this,arguments)})}}function r(u){return u&&function(d,f){try{return u.call(e,d,f)}catch(g){if(!l(g))throw g}}}function i(u){return u&&function(d,f,g,m){return u.call(e,d,f,g,function(p){l(p)&&(p=null),m&&m.apply(this,arguments)})}}function s(u){return u&&function(d,f,g){try{return u.call(e,d,f,g)}catch(m){if(!l(m))throw m}}}function c(u){return u&&function(d,f,g){typeof f=="function"&&(g=f,f=null);function m(p,h){h&&(h.uid<0&&(h.uid+=4294967296),h.gid<0&&(h.gid+=4294967296)),g&&g.apply(this,arguments)}return f?u.call(e,d,f,m):u.call(e,d,m)}}function a(u){return u&&function(d,f){var g=f?u.call(e,d,f):u.call(e,d);return g&&(g.uid<0&&(g.uid+=4294967296),g.gid<0&&(g.gid+=4294967296)),g}}function l(u){if(!u||u.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(u.code==="EINVAL"||u.code==="EPERM"))}}});var Ci=O((Oh,bi)=>{var Ai=require("stream").Stream;bi.exports=nd;function nd(e){return{ReadStream:t,WriteStream:n};function t(o,r){if(!(this instanceof t))return new t(o,r);Ai.call(this);var i=this;this.path=o,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,r=r||{};for(var s=Object.keys(r),c=0,a=s.length;c<a;c++){var l=s[c];this[l]=r[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){i._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){i.emit("error",u),i.readable=!1;return}i.fd=d,i.emit("open",d),i._read()})}function n(o,r){if(!(this instanceof n))return new n(o,r);Ai.call(this),this.path=o,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,r=r||{};for(var i=Object.keys(r),s=0,c=i.length;s<c;s++){var a=i[s];this[a]=r[a]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var Pi=O((vh,Ni)=>{"use strict";Ni.exports=rd;var od=Object.getPrototypeOf||function(e){return e.__proto__};function rd(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:od(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var nt=O((Rh,io)=>{var L=require("fs"),id=Ii(),sd=Ci(),ad=Pi(),zt=require("util"),Y,Qt;typeof Symbol=="function"&&typeof Symbol.for=="function"?(Y=Symbol.for("graceful-fs.queue"),Qt=Symbol.for("graceful-fs.previous")):(Y="___graceful-fs.queue",Qt="___graceful-fs.previous");function cd(){}function Li(e,t){Object.defineProperty(e,Y,{get:function(){return t}})}var Be=cd;zt.debuglog?Be=zt.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Be=function(){var e=zt.format.apply(zt,arguments);e="GFS4: "+e.split(/\n/).join(`
4
- GFS4: `),console.error(e)});L[Y]||(xi=global[Y]||[],Li(L,xi),L.close=(function(e){function t(n,o){return e.call(L,n,function(r){r||Di(),typeof o=="function"&&o.apply(this,arguments)})}return Object.defineProperty(t,Qt,{value:e}),t})(L.close),L.closeSync=(function(e){function t(n){e.apply(L,arguments),Di()}return Object.defineProperty(t,Qt,{value:e}),t})(L.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Be(L[Y]),require("assert").equal(L[Y].length,0)}));var xi;global[Y]||Li(global,L[Y]);io.exports=oo(ad(L));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!L.__patched&&(io.exports=oo(L),L.__patched=!0);function oo(e){id(e),e.gracefulify=oo,e.createReadStream=D,e.createWriteStream=R;var t=e.readFile;e.readFile=n;function n(S,b,I){return typeof b=="function"&&(I=b,b=null),F(S,b,I);function F(M,E,_,P){return t(M,E,function(C){C&&(C.code==="EMFILE"||C.code==="ENFILE")?tt([F,[M,E,_],C,P||Date.now(),Date.now()]):typeof _=="function"&&_.apply(this,arguments)})}}var o=e.writeFile;e.writeFile=r;function r(S,b,I,F){return typeof I=="function"&&(F=I,I=null),M(S,b,I,F);function M(E,_,P,C,B){return o(E,_,P,function(x){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}var i=e.appendFile;i&&(e.appendFile=s);function s(S,b,I,F){return typeof I=="function"&&(F=I,I=null),M(S,b,I,F);function M(E,_,P,C,B){return i(E,_,P,function(x){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}var c=e.copyFile;c&&(e.copyFile=a);function a(S,b,I,F){return typeof I=="function"&&(F=I,I=0),M(S,b,I,F);function M(E,_,P,C,B){return c(E,_,P,function(x){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(S,b,I){typeof b=="function"&&(I=b,b=null);var F=u.test(process.version)?function(_,P,C,B){return l(_,M(_,P,C,B))}:function(_,P,C,B){return l(_,P,M(_,P,C,B))};return F(S,b,I);function M(E,_,P,C){return function(B,x){B&&(B.code==="EMFILE"||B.code==="ENFILE")?tt([F,[E,_,P],B,C||Date.now(),Date.now()]):(x&&x.sort&&x.sort(),typeof P=="function"&&P.call(this,B,x))}}}if(process.version.substr(0,4)==="v0.8"){var f=sd(e);y=f.ReadStream,k=f.WriteStream}var g=e.ReadStream;g&&(y.prototype=Object.create(g.prototype),y.prototype.open=T);var m=e.WriteStream;m&&(k.prototype=Object.create(m.prototype),k.prototype.open=A),Object.defineProperty(e,"ReadStream",{get:function(){return y},set:function(S){y=S},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return k},set:function(S){k=S},enumerable:!0,configurable:!0});var p=y;Object.defineProperty(e,"FileReadStream",{get:function(){return p},set:function(S){p=S},enumerable:!0,configurable:!0});var h=k;Object.defineProperty(e,"FileWriteStream",{get:function(){return h},set:function(S){h=S},enumerable:!0,configurable:!0});function y(S,b){return this instanceof y?(g.apply(this,arguments),this):y.apply(Object.create(y.prototype),arguments)}function T(){var S=this;ke(S.path,S.flags,S.mode,function(b,I){b?(S.autoClose&&S.destroy(),S.emit("error",b)):(S.fd=I,S.emit("open",I),S.read())})}function k(S,b){return this instanceof k?(m.apply(this,arguments),this):k.apply(Object.create(k.prototype),arguments)}function A(){var S=this;ke(S.path,S.flags,S.mode,function(b,I){b?(S.destroy(),S.emit("error",b)):(S.fd=I,S.emit("open",I))})}function D(S,b){return new e.ReadStream(S,b)}function R(S,b){return new e.WriteStream(S,b)}var w=e.open;e.open=ke;function ke(S,b,I,F){return typeof I=="function"&&(F=I,I=null),M(S,b,I,F);function M(E,_,P,C,B){return w(E,_,P,function(x,Ng){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}return e}function tt(e){Be("ENQUEUE",e[0].name,e[1]),L[Y].push(e),ro()}var Xt;function Di(){for(var e=Date.now(),t=0;t<L[Y].length;++t)L[Y][t].length>2&&(L[Y][t][3]=e,L[Y][t][4]=e);ro()}function ro(){if(clearTimeout(Xt),Xt=void 0,L[Y].length!==0){var e=L[Y].shift(),t=e[0],n=e[1],o=e[2],r=e[3],i=e[4];if(r===void 0)Be("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-r>=6e4){Be("TIMEOUT",t.name,n);var s=n.pop();typeof s=="function"&&s.call(null,o)}else{var c=Date.now()-i,a=Math.max(i-r,1),l=Math.min(a*1.2,100);c>=l?(Be("RETRY",t.name,n),t.apply(null,n.concat([r]))):L[Y].push(e)}Xt===void 0&&(Xt=setTimeout(ro,0))}}});var X=O(_e=>{"use strict";var Mi=W().fromCallback,z=nt(),ld=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(e=>typeof z[e]=="function");Object.assign(_e,z);ld.forEach(e=>{_e[e]=Mi(z[e])});_e.exists=function(e,t){return typeof t=="function"?z.exists(e,t):new Promise(n=>z.exists(e,n))};_e.read=function(e,t,n,o,r,i){return typeof i=="function"?z.read(e,t,n,o,r,i):new Promise((s,c)=>{z.read(e,t,n,o,r,(a,l,u)=>{if(a)return c(a);s({bytesRead:l,buffer:u})})})};_e.write=function(e,t,...n){return typeof n[n.length-1]=="function"?z.write(e,t,...n):new Promise((o,r)=>{z.write(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesWritten:s,buffer:c})})})};_e.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?z.readv(e,t,...n):new Promise((o,r)=>{z.readv(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesRead:s,buffers:c})})})};_e.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?z.writev(e,t,...n):new Promise((o,r)=>{z.writev(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesWritten:s,buffers:c})})})};typeof z.realpath.native=="function"?_e.realpath.native=Mi(z.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Fi=O((Ah,$i)=>{"use strict";var ud=require("path");$i.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(ud.parse(t).root,""))){let o=new Error(`Path contains invalid characters: ${t}`);throw o.code="EINVAL",o}}});var Wi=O((bh,so)=>{"use strict";var Ui=X(),{checkPath:ji}=Fi(),Hi=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};so.exports.makeDir=async(e,t)=>(ji(e),Ui.mkdir(e,{mode:Hi(t),recursive:!0}));so.exports.makeDirSync=(e,t)=>(ji(e),Ui.mkdirSync(e,{mode:Hi(t),recursive:!0}))});var pe=O((Ch,Gi)=>{"use strict";var dd=W().fromPromise,{makeDir:fd,makeDirSync:ao}=Wi(),co=dd(fd);Gi.exports={mkdirs:co,mkdirsSync:ao,mkdirp:co,mkdirpSync:ao,ensureDir:co,ensureDirSync:ao}});var De=O((Nh,qi)=>{"use strict";var pd=W().fromPromise,Bi=X();function md(e){return Bi.access(e).then(()=>!0).catch(()=>!1)}qi.exports={pathExists:pd(md),pathExistsSync:Bi.existsSync}});var lo=O((Ph,Yi)=>{"use strict";var ot=X(),gd=W().fromPromise;async function hd(e,t,n){let o=await ot.open(e,"r+"),r=null;try{await ot.futimes(o,t,n)}finally{try{await ot.close(o)}catch(i){r=i}}if(r)throw r}function kd(e,t,n){let o=ot.openSync(e,"r+");return ot.futimesSync(o,t,n),ot.closeSync(o)}Yi.exports={utimesMillis:gd(hd),utimesMillisSync:kd}});var qe=O((xh,zi)=>{"use strict";var rt=X(),G=require("path"),Vi=W().fromPromise;function yd(e,t,n){let o=n.dereference?r=>rt.stat(r,{bigint:!0}):r=>rt.lstat(r,{bigint:!0});return Promise.all([o(e),o(t).catch(r=>{if(r.code==="ENOENT")return null;throw r})]).then(([r,i])=>({srcStat:r,destStat:i}))}function Ed(e,t,n){let o,r=n.dereference?s=>rt.statSync(s,{bigint:!0}):s=>rt.lstatSync(s,{bigint:!0}),i=r(e);try{o=r(t)}catch(s){if(s.code==="ENOENT")return{srcStat:i,destStat:null};throw s}return{srcStat:i,destStat:o}}async function Sd(e,t,n,o){let{srcStat:r,destStat:i}=await yd(e,t,o);if(i){if(Et(r,i)){let s=G.basename(e),c=G.basename(t);if(n==="move"&&s!==c&&s.toLowerCase()===c.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&uo(e,t))throw new Error(Zt(e,t,n));return{srcStat:r,destStat:i}}function Td(e,t,n,o){let{srcStat:r,destStat:i}=Ed(e,t,o);if(i){if(Et(r,i)){let s=G.basename(e),c=G.basename(t);if(n==="move"&&s!==c&&s.toLowerCase()===c.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&uo(e,t))throw new Error(Zt(e,t,n));return{srcStat:r,destStat:i}}async function Ki(e,t,n,o){let r=G.resolve(G.dirname(e)),i=G.resolve(G.dirname(n));if(i===r||i===G.parse(i).root)return;let s;try{s=await rt.stat(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(Et(t,s))throw new Error(Zt(e,n,o));return Ki(e,t,i,o)}function Ji(e,t,n,o){let r=G.resolve(G.dirname(e)),i=G.resolve(G.dirname(n));if(i===r||i===G.parse(i).root)return;let s;try{s=rt.statSync(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(Et(t,s))throw new Error(Zt(e,n,o));return Ji(e,t,i,o)}function Et(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function uo(e,t){let n=G.resolve(e).split(G.sep).filter(r=>r),o=G.resolve(t).split(G.sep).filter(r=>r);return n.every((r,i)=>o[i]===r)}function Zt(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}zi.exports={checkPaths:Vi(Sd),checkPathsSync:Td,checkParentPaths:Vi(Ki),checkParentPathsSync:Ji,isSrcSubdir:uo,areIdentical:Et}});var Qi=O((Dh,Xi)=>{"use strict";async function wd(e,t){let n=[];for await(let o of e)n.push(t(o).then(()=>null,r=>r??new Error("unknown error")));await Promise.all(n.map(o=>o.then(r=>{if(r!==null)throw r})))}Xi.exports={asyncIteratorConcurrentProcess:wd}});var os=O((Lh,ns)=>{"use strict";var K=X(),St=require("path"),{mkdirs:_d}=pe(),{pathExists:Od}=De(),{utimesMillis:vd}=lo(),Tt=qe(),{asyncIteratorConcurrentProcess:Rd}=Qi();async function Id(e,t,n={}){typeof n=="function"&&(n={filter:n}),n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
3
+ "use strict";var Iu=Object.create;var qt=Object.defineProperty;var bu=Object.getOwnPropertyDescriptor;var Cu=Object.getOwnPropertyNames;var Au=Object.getPrototypeOf,Nu=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Pu=(e,t)=>{for(var n in t)qt(e,n,{get:t[n],enumerable:!0})},Ar=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Cu(t))!Nu.call(e,r)&&r!==n&&qt(e,r,{get:()=>t[r],enumerable:!(o=bu(t,r))||o.enumerable});return e};var F=(e,t,n)=>(n=e!=null?Iu(Au(e)):{},Ar(t||!e||!e.__esModule?qt(n,"default",{value:e,enumerable:!0}):n,e)),xu=e=>Ar(qt({},"__esModule",{value:!0}),e);var G=v(ro=>{"use strict";ro.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,o)=>{t.push((r,i)=>r!=null?o(r):n(i)),e.apply(this,t)})},"name",{value:e.name})};ro.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!="function")return e.apply(this,t);t.pop(),e.apply(this,t).then(o=>n(null,o),n)},"name",{value:e.name})}});var Ni=v((Ah,Ai)=>{var De=require("constants"),sd=process.cwd,Xt=null,ad=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Xt||(Xt=sd.call(process)),Xt};try{process.cwd()}catch{}typeof process.chdir=="function"&&(io=process.chdir,process.chdir=function(e){Xt=null,io.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,io));var io;Ai.exports=cd;function cd(e){De.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=i(e.chown),e.fchown=i(e.fchown),e.lchown=i(e.lchown),e.chmod=o(e.chmod),e.fchmod=o(e.fchmod),e.lchmod=o(e.lchmod),e.chownSync=s(e.chownSync),e.fchownSync=s(e.fchownSync),e.lchownSync=s(e.lchownSync),e.chmodSync=r(e.chmodSync),e.fchmodSync=r(e.fchmodSync),e.lchmodSync=r(e.lchmodSync),e.stat=c(e.stat),e.fstat=c(e.fstat),e.lstat=c(e.lstat),e.statSync=a(e.statSync),e.fstatSync=a(e.fstatSync),e.lstatSync=a(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(u,d,f){f&&process.nextTick(f)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,f,g){g&&process.nextTick(g)},e.lchownSync=function(){}),ad==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(f,g,m){var p=Date.now(),h=0;u(f,g,function y(w){if(w&&(w.code==="EACCES"||w.code==="EPERM"||w.code==="EBUSY")&&Date.now()-p<6e4){setTimeout(function(){e.stat(g,function(k,C){k&&k.code==="ENOENT"?u(f,g,y):m(w)})},h),h<100&&(h+=10);return}m&&m(w)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(f,g,m,p,h,y){var w;if(y&&typeof y=="function"){var k=0;w=function(C,L,I){if(C&&C.code==="EAGAIN"&&k<10)return k++,u.call(e,f,g,m,p,h,w);y.apply(this,arguments)}}return u.call(e,f,g,m,p,h,w)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,f,g,m,p){for(var h=0;;)try{return u.call(e,d,f,g,m,p)}catch(y){if(y.code==="EAGAIN"&&h<10){h++;continue}throw y}}})(e.readSync);function t(u){u.lchmod=function(d,f,g){u.open(d,De.O_WRONLY|De.O_SYMLINK,f,function(m,p){if(m){g&&g(m);return}u.fchmod(p,f,function(h){u.close(p,function(y){g&&g(h||y)})})})},u.lchmodSync=function(d,f){var g=u.openSync(d,De.O_WRONLY|De.O_SYMLINK,f),m=!0,p;try{p=u.fchmodSync(g,f),m=!1}finally{if(m)try{u.closeSync(g)}catch{}else u.closeSync(g)}return p}}function n(u){De.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,f,g,m){u.open(d,De.O_SYMLINK,function(p,h){if(p){m&&m(p);return}u.futimes(h,f,g,function(y){u.close(h,function(w){m&&m(y||w)})})})},u.lutimesSync=function(d,f,g){var m=u.openSync(d,De.O_SYMLINK),p,h=!0;try{p=u.futimesSync(m,f,g),h=!1}finally{if(h)try{u.closeSync(m)}catch{}else u.closeSync(m)}return p}):u.futimes&&(u.lutimes=function(d,f,g,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function o(u){return u&&function(d,f,g){return u.call(e,d,f,function(m){l(m)&&(m=null),g&&g.apply(this,arguments)})}}function r(u){return u&&function(d,f){try{return u.call(e,d,f)}catch(g){if(!l(g))throw g}}}function i(u){return u&&function(d,f,g,m){return u.call(e,d,f,g,function(p){l(p)&&(p=null),m&&m.apply(this,arguments)})}}function s(u){return u&&function(d,f,g){try{return u.call(e,d,f,g)}catch(m){if(!l(m))throw m}}}function c(u){return u&&function(d,f,g){typeof f=="function"&&(g=f,f=null);function m(p,h){h&&(h.uid<0&&(h.uid+=4294967296),h.gid<0&&(h.gid+=4294967296)),g&&g.apply(this,arguments)}return f?u.call(e,d,f,m):u.call(e,d,m)}}function a(u){return u&&function(d,f){var g=f?u.call(e,d,f):u.call(e,d);return g&&(g.uid<0&&(g.uid+=4294967296),g.gid<0&&(g.gid+=4294967296)),g}}function l(u){if(!u||u.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(u.code==="EINVAL"||u.code==="EPERM"))}}});var Di=v((Nh,xi)=>{var Pi=require("stream").Stream;xi.exports=ld;function ld(e){return{ReadStream:t,WriteStream:n};function t(o,r){if(!(this instanceof t))return new t(o,r);Pi.call(this);var i=this;this.path=o,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,r=r||{};for(var s=Object.keys(r),c=0,a=s.length;c<a;c++){var l=s[c];this[l]=r[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){i._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){i.emit("error",u),i.readable=!1;return}i.fd=d,i.emit("open",d),i._read()})}function n(o,r){if(!(this instanceof n))return new n(o,r);Pi.call(this),this.path=o,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,r=r||{};for(var i=Object.keys(r),s=0,c=i.length;s<c;s++){var a=i[s];this[a]=r[a]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var Mi=v((Ph,Li)=>{"use strict";Li.exports=dd;var ud=Object.getPrototypeOf||function(e){return e.__proto__};function dd(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:ud(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var ot=v((xh,co)=>{var M=require("fs"),fd=Ni(),pd=Di(),md=Mi(),Qt=require("util"),V,en;typeof Symbol=="function"&&typeof Symbol.for=="function"?(V=Symbol.for("graceful-fs.queue"),en=Symbol.for("graceful-fs.previous")):(V="___graceful-fs.queue",en="___graceful-fs.previous");function gd(){}function Ui(e,t){Object.defineProperty(e,V,{get:function(){return t}})}var qe=gd;Qt.debuglog?qe=Qt.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(qe=function(){var e=Qt.format.apply(Qt,arguments);e="GFS4: "+e.split(/\n/).join(`
4
+ GFS4: `),console.error(e)});M[V]||($i=global[V]||[],Ui(M,$i),M.close=(function(e){function t(n,o){return e.call(M,n,function(r){r||Fi(),typeof o=="function"&&o.apply(this,arguments)})}return Object.defineProperty(t,en,{value:e}),t})(M.close),M.closeSync=(function(e){function t(n){e.apply(M,arguments),Fi()}return Object.defineProperty(t,en,{value:e}),t})(M.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){qe(M[V]),require("assert").equal(M[V].length,0)}));var $i;global[V]||Ui(global,M[V]);co.exports=so(md(M));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!M.__patched&&(co.exports=so(M),M.__patched=!0);function so(e){fd(e),e.gracefulify=so,e.createReadStream=L,e.createWriteStream=I;var t=e.readFile;e.readFile=n;function n(T,A,b){return typeof A=="function"&&(b=A,A=null),j(T,A,b);function j($,S,O,x){return t($,S,function(N){N&&(N.code==="EMFILE"||N.code==="ENFILE")?nt([j,[$,S,O],N,x||Date.now(),Date.now()]):typeof O=="function"&&O.apply(this,arguments)})}}var o=e.writeFile;e.writeFile=r;function r(T,A,b,j){return typeof b=="function"&&(j=b,b=null),$(T,A,b,j);function $(S,O,x,N,q){return o(S,O,x,function(D){D&&(D.code==="EMFILE"||D.code==="ENFILE")?nt([$,[S,O,x,N],D,q||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var i=e.appendFile;i&&(e.appendFile=s);function s(T,A,b,j){return typeof b=="function"&&(j=b,b=null),$(T,A,b,j);function $(S,O,x,N,q){return i(S,O,x,function(D){D&&(D.code==="EMFILE"||D.code==="ENFILE")?nt([$,[S,O,x,N],D,q||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var c=e.copyFile;c&&(e.copyFile=a);function a(T,A,b,j){return typeof b=="function"&&(j=b,b=0),$(T,A,b,j);function $(S,O,x,N,q){return c(S,O,x,function(D){D&&(D.code==="EMFILE"||D.code==="ENFILE")?nt([$,[S,O,x,N],D,q||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(T,A,b){typeof A=="function"&&(b=A,A=null);var j=u.test(process.version)?function(O,x,N,q){return l(O,$(O,x,N,q))}:function(O,x,N,q){return l(O,x,$(O,x,N,q))};return j(T,A,b);function $(S,O,x,N){return function(q,D){q&&(q.code==="EMFILE"||q.code==="ENFILE")?nt([j,[S,O,x],q,N||Date.now(),Date.now()]):(D&&D.sort&&D.sort(),typeof x=="function"&&x.call(this,q,D))}}}if(process.version.substr(0,4)==="v0.8"){var f=pd(e);y=f.ReadStream,k=f.WriteStream}var g=e.ReadStream;g&&(y.prototype=Object.create(g.prototype),y.prototype.open=w);var m=e.WriteStream;m&&(k.prototype=Object.create(m.prototype),k.prototype.open=C),Object.defineProperty(e,"ReadStream",{get:function(){return y},set:function(T){y=T},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return k},set:function(T){k=T},enumerable:!0,configurable:!0});var p=y;Object.defineProperty(e,"FileReadStream",{get:function(){return p},set:function(T){p=T},enumerable:!0,configurable:!0});var h=k;Object.defineProperty(e,"FileWriteStream",{get:function(){return h},set:function(T){h=T},enumerable:!0,configurable:!0});function y(T,A){return this instanceof y?(g.apply(this,arguments),this):y.apply(Object.create(y.prototype),arguments)}function w(){var T=this;ye(T.path,T.flags,T.mode,function(A,b){A?(T.autoClose&&T.destroy(),T.emit("error",A)):(T.fd=b,T.emit("open",b),T.read())})}function k(T,A){return this instanceof k?(m.apply(this,arguments),this):k.apply(Object.create(k.prototype),arguments)}function C(){var T=this;ye(T.path,T.flags,T.mode,function(A,b){A?(T.destroy(),T.emit("error",A)):(T.fd=b,T.emit("open",b))})}function L(T,A){return new e.ReadStream(T,A)}function I(T,A){return new e.WriteStream(T,A)}var _=e.open;e.open=ye;function ye(T,A,b,j){return typeof b=="function"&&(j=b,b=null),$(T,A,b,j);function $(S,O,x,N,q){return _(S,O,x,function(D,Fg){D&&(D.code==="EMFILE"||D.code==="ENFILE")?nt([$,[S,O,x,N],D,q||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}return e}function nt(e){qe("ENQUEUE",e[0].name,e[1]),M[V].push(e),ao()}var Zt;function Fi(){for(var e=Date.now(),t=0;t<M[V].length;++t)M[V][t].length>2&&(M[V][t][3]=e,M[V][t][4]=e);ao()}function ao(){if(clearTimeout(Zt),Zt=void 0,M[V].length!==0){var e=M[V].shift(),t=e[0],n=e[1],o=e[2],r=e[3],i=e[4];if(r===void 0)qe("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-r>=6e4){qe("TIMEOUT",t.name,n);var s=n.pop();typeof s=="function"&&s.call(null,o)}else{var c=Date.now()-i,a=Math.max(i-r,1),l=Math.min(a*1.2,100);c>=l?(qe("RETRY",t.name,n),t.apply(null,n.concat([r]))):M[V].push(e)}Zt===void 0&&(Zt=setTimeout(ao,0))}}});var Q=v(Oe=>{"use strict";var ji=G().fromCallback,X=ot(),hd=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(e=>typeof X[e]=="function");Object.assign(Oe,X);hd.forEach(e=>{Oe[e]=ji(X[e])});Oe.exists=function(e,t){return typeof t=="function"?X.exists(e,t):new Promise(n=>X.exists(e,n))};Oe.read=function(e,t,n,o,r,i){return typeof i=="function"?X.read(e,t,n,o,r,i):new Promise((s,c)=>{X.read(e,t,n,o,r,(a,l,u)=>{if(a)return c(a);s({bytesRead:l,buffer:u})})})};Oe.write=function(e,t,...n){return typeof n[n.length-1]=="function"?X.write(e,t,...n):new Promise((o,r)=>{X.write(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesWritten:s,buffer:c})})})};Oe.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?X.readv(e,t,...n):new Promise((o,r)=>{X.readv(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesRead:s,buffers:c})})})};Oe.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?X.writev(e,t,...n):new Promise((o,r)=>{X.writev(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesWritten:s,buffers:c})})})};typeof X.realpath.native=="function"?Oe.realpath.native=ji(X.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Wi=v((Lh,Hi)=>{"use strict";var kd=require("path");Hi.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(kd.parse(t).root,""))){let o=new Error(`Path contains invalid characters: ${t}`);throw o.code="EINVAL",o}}});var Yi=v((Mh,lo)=>{"use strict";var Gi=Q(),{checkPath:Bi}=Wi(),qi=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};lo.exports.makeDir=async(e,t)=>(Bi(e),Gi.mkdir(e,{mode:qi(t),recursive:!0}));lo.exports.makeDirSync=(e,t)=>(Bi(e),Gi.mkdirSync(e,{mode:qi(t),recursive:!0}))});var me=v(($h,Vi)=>{"use strict";var yd=G().fromPromise,{makeDir:Ed,makeDirSync:uo}=Yi(),fo=yd(Ed);Vi.exports={mkdirs:fo,mkdirsSync:uo,mkdirp:fo,mkdirpSync:uo,ensureDir:fo,ensureDirSync:uo}});var Le=v((Fh,Ji)=>{"use strict";var Sd=G().fromPromise,Ki=Q();function Td(e){return Ki.access(e).then(()=>!0).catch(()=>!1)}Ji.exports={pathExists:Sd(Td),pathExistsSync:Ki.existsSync}});var po=v((Uh,zi)=>{"use strict";var rt=Q(),wd=G().fromPromise;async function _d(e,t,n){let o=await rt.open(e,"r+"),r=null;try{await rt.futimes(o,t,n)}finally{try{await rt.close(o)}catch(i){r=i}}if(r)throw r}function Od(e,t,n){let o=rt.openSync(e,"r+");return rt.futimesSync(o,t,n),rt.closeSync(o)}zi.exports={utimesMillis:wd(_d),utimesMillisSync:Od}});var Ye=v((jh,es)=>{"use strict";var it=Q(),B=require("path"),Xi=G().fromPromise;function vd(e,t,n){let o=n.dereference?r=>it.stat(r,{bigint:!0}):r=>it.lstat(r,{bigint:!0});return Promise.all([o(e),o(t).catch(r=>{if(r.code==="ENOENT")return null;throw r})]).then(([r,i])=>({srcStat:r,destStat:i}))}function Rd(e,t,n){let o,r=n.dereference?s=>it.statSync(s,{bigint:!0}):s=>it.lstatSync(s,{bigint:!0}),i=r(e);try{o=r(t)}catch(s){if(s.code==="ENOENT")return{srcStat:i,destStat:null};throw s}return{srcStat:i,destStat:o}}async function Id(e,t,n,o){let{srcStat:r,destStat:i}=await vd(e,t,o);if(i){if(Tt(r,i)){let s=B.basename(e),c=B.basename(t);if(n==="move"&&s!==c&&s.toLowerCase()===c.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&mo(e,t))throw new Error(tn(e,t,n));return{srcStat:r,destStat:i}}function bd(e,t,n,o){let{srcStat:r,destStat:i}=Rd(e,t,o);if(i){if(Tt(r,i)){let s=B.basename(e),c=B.basename(t);if(n==="move"&&s!==c&&s.toLowerCase()===c.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&mo(e,t))throw new Error(tn(e,t,n));return{srcStat:r,destStat:i}}async function Qi(e,t,n,o){let r=B.resolve(B.dirname(e)),i=B.resolve(B.dirname(n));if(i===r||i===B.parse(i).root)return;let s;try{s=await it.stat(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(Tt(t,s))throw new Error(tn(e,n,o));return Qi(e,t,i,o)}function Zi(e,t,n,o){let r=B.resolve(B.dirname(e)),i=B.resolve(B.dirname(n));if(i===r||i===B.parse(i).root)return;let s;try{s=it.statSync(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(Tt(t,s))throw new Error(tn(e,n,o));return Zi(e,t,i,o)}function Tt(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function mo(e,t){let n=B.resolve(e).split(B.sep).filter(r=>r),o=B.resolve(t).split(B.sep).filter(r=>r);return n.every((r,i)=>o[i]===r)}function tn(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}es.exports={checkPaths:Xi(Id),checkPathsSync:bd,checkParentPaths:Xi(Qi),checkParentPathsSync:Zi,isSrcSubdir:mo,areIdentical:Tt}});var ns=v((Hh,ts)=>{"use strict";async function Cd(e,t){let n=[];for await(let o of e)n.push(t(o).then(()=>null,r=>r??new Error("unknown error")));await Promise.all(n.map(o=>o.then(r=>{if(r!==null)throw r})))}ts.exports={asyncIteratorConcurrentProcess:Cd}});var as=v((Wh,ss)=>{"use strict";var J=Q(),wt=require("path"),{mkdirs:Ad}=me(),{pathExists:Nd}=Le(),{utimesMillis:Pd}=po(),_t=Ye(),{asyncIteratorConcurrentProcess:xd}=ns();async function Dd(e,t,n={}){typeof n=="function"&&(n={filter:n}),n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
5
5
 
6
- see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:o,destStat:r}=await Tt.checkPaths(e,t,"copy",n);if(await Tt.checkParentPaths(e,o,t,"copy"),!await es(e,t,n))return;let s=St.dirname(t);await Od(s)||await _d(s),await ts(r,e,t,n)}async function es(e,t,n){return n.filter?n.filter(e,t):!0}async function ts(e,t,n,o){let i=await(o.dereference?K.stat:K.lstat)(t);if(i.isDirectory())return Nd(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Ad(i,e,t,n,o);if(i.isSymbolicLink())return Pd(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function Ad(e,t,n,o,r){if(!t)return Zi(e,n,o,r);if(r.overwrite)return await K.unlink(o),Zi(e,n,o,r);if(r.errorOnExist)throw new Error(`'${o}' already exists`)}async function Zi(e,t,n,o){if(await K.copyFile(t,n),o.preserveTimestamps){bd(e.mode)&&await Cd(n,e.mode);let r=await K.stat(t);await vd(n,r.atime,r.mtime)}return K.chmod(n,e.mode)}function bd(e){return(e&128)===0}function Cd(e,t){return K.chmod(e,t|128)}async function Nd(e,t,n,o,r){t||await K.mkdir(o),await Rd(await K.opendir(n),async i=>{let s=St.join(n,i.name),c=St.join(o,i.name);if(await es(s,c,r)){let{destStat:l}=await Tt.checkPaths(s,c,"copy",r);await ts(l,s,c,r)}}),t||await K.chmod(o,e.mode)}async function Pd(e,t,n,o){let r=await K.readlink(t);if(o.dereference&&(r=St.resolve(process.cwd(),r)),!e)return K.symlink(r,n);let i=null;try{i=await K.readlink(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return K.symlink(r,n);throw s}if(o.dereference&&(i=St.resolve(process.cwd(),i)),r!==i){if(Tt.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(Tt.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return await K.unlink(n),K.symlink(r,n)}ns.exports=Id});var cs=O((Mh,as)=>{"use strict";var Q=nt(),wt=require("path"),xd=pe().mkdirsSync,Dd=lo().utimesMillisSync,_t=qe();function Ld(e,t,n){typeof n=="function"&&(n={filter:n}),n=n||{},n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
6
+ see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:o,destStat:r}=await _t.checkPaths(e,t,"copy",n);if(await _t.checkParentPaths(e,o,t,"copy"),!await rs(e,t,n))return;let s=wt.dirname(t);await Nd(s)||await Ad(s),await is(r,e,t,n)}async function rs(e,t,n){return n.filter?n.filter(e,t):!0}async function is(e,t,n,o){let i=await(o.dereference?J.stat:J.lstat)(t);if(i.isDirectory())return Fd(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Ld(i,e,t,n,o);if(i.isSymbolicLink())return Ud(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function Ld(e,t,n,o,r){if(!t)return os(e,n,o,r);if(r.overwrite)return await J.unlink(o),os(e,n,o,r);if(r.errorOnExist)throw new Error(`'${o}' already exists`)}async function os(e,t,n,o){if(await J.copyFile(t,n),o.preserveTimestamps){Md(e.mode)&&await $d(n,e.mode);let r=await J.stat(t);await Pd(n,r.atime,r.mtime)}return J.chmod(n,e.mode)}function Md(e){return(e&128)===0}function $d(e,t){return J.chmod(e,t|128)}async function Fd(e,t,n,o,r){t||await J.mkdir(o),await xd(await J.opendir(n),async i=>{let s=wt.join(n,i.name),c=wt.join(o,i.name);if(await rs(s,c,r)){let{destStat:l}=await _t.checkPaths(s,c,"copy",r);await is(l,s,c,r)}}),t||await J.chmod(o,e.mode)}async function Ud(e,t,n,o){let r=await J.readlink(t);if(o.dereference&&(r=wt.resolve(process.cwd(),r)),!e)return J.symlink(r,n);let i=null;try{i=await J.readlink(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return J.symlink(r,n);throw s}if(o.dereference&&(i=wt.resolve(process.cwd(),i)),r!==i){if(_t.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(_t.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return await J.unlink(n),J.symlink(r,n)}ss.exports=Dd});var fs=v((Gh,ds)=>{"use strict";var Z=ot(),Ot=require("path"),jd=me().mkdirsSync,Hd=po().utimesMillisSync,vt=Ye();function Wd(e,t,n){typeof n=="function"&&(n={filter:n}),n=n||{},n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
7
7
 
8
- see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:o,destStat:r}=_t.checkPathsSync(e,t,"copy",n);if(_t.checkParentPathsSync(e,o,t,"copy"),n.filter&&!n.filter(e,t))return;let i=wt.dirname(t);return Q.existsSync(i)||xd(i),rs(r,e,t,n)}function rs(e,t,n,o){let i=(o.dereference?Q.statSync:Q.lstatSync)(t);if(i.isDirectory())return Wd(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Md(i,e,t,n,o);if(i.isSymbolicLink())return qd(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function Md(e,t,n,o,r){return t?$d(e,n,o,r):is(e,n,o,r)}function $d(e,t,n,o){if(o.overwrite)return Q.unlinkSync(n),is(e,t,n,o);if(o.errorOnExist)throw new Error(`'${n}' already exists`)}function is(e,t,n,o){return Q.copyFileSync(t,n),o.preserveTimestamps&&Fd(e.mode,t,n),fo(n,e.mode)}function Fd(e,t,n){return Ud(e)&&jd(n,e),Hd(t,n)}function Ud(e){return(e&128)===0}function jd(e,t){return fo(e,t|128)}function fo(e,t){return Q.chmodSync(e,t)}function Hd(e,t){let n=Q.statSync(e);return Dd(t,n.atime,n.mtime)}function Wd(e,t,n,o,r){return t?ss(n,o,r):Gd(e.mode,n,o,r)}function Gd(e,t,n,o){return Q.mkdirSync(n),ss(t,n,o),fo(n,e)}function ss(e,t,n){let o=Q.opendirSync(e);try{let r;for(;(r=o.readSync())!==null;)Bd(r.name,e,t,n)}finally{o.closeSync()}}function Bd(e,t,n,o){let r=wt.join(t,e),i=wt.join(n,e);if(o.filter&&!o.filter(r,i))return;let{destStat:s}=_t.checkPathsSync(r,i,"copy",o);return rs(s,r,i,o)}function qd(e,t,n,o){let r=Q.readlinkSync(t);if(o.dereference&&(r=wt.resolve(process.cwd(),r)),e){let i;try{i=Q.readlinkSync(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return Q.symlinkSync(r,n);throw s}if(o.dereference&&(i=wt.resolve(process.cwd(),i)),r!==i){if(_t.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(_t.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return Yd(r,n)}else return Q.symlinkSync(r,n)}function Yd(e,t){return Q.unlinkSync(t),Q.symlinkSync(e,t)}as.exports=Ld});var en=O(($h,ls)=>{"use strict";var Vd=W().fromPromise;ls.exports={copy:Vd(os()),copySync:cs()}});var Ot=O((Fh,ds)=>{"use strict";var us=nt(),Kd=W().fromCallback;function Jd(e,t){us.rm(e,{recursive:!0,force:!0},t)}function zd(e){us.rmSync(e,{recursive:!0,force:!0})}ds.exports={remove:Kd(Jd),removeSync:zd}});var Es=O((Uh,ys)=>{"use strict";var Xd=W().fromPromise,ms=X(),gs=require("path"),hs=pe(),ks=Ot(),fs=Xd(async function(t){let n;try{n=await ms.readdir(t)}catch{return hs.mkdirs(t)}return Promise.all(n.map(o=>ks.remove(gs.join(t,o))))});function ps(e){let t;try{t=ms.readdirSync(e)}catch{return hs.mkdirsSync(e)}t.forEach(n=>{n=gs.join(e,n),ks.removeSync(n)})}ys.exports={emptyDirSync:ps,emptydirSync:ps,emptyDir:fs,emptydir:fs}});var _s=O((jh,ws)=>{"use strict";var Qd=W().fromPromise,Ss=require("path"),Oe=X(),Ts=pe();async function Zd(e){let t;try{t=await Oe.stat(e)}catch{}if(t&&t.isFile())return;let n=Ss.dirname(e),o=null;try{o=await Oe.stat(n)}catch(r){if(r.code==="ENOENT"){await Ts.mkdirs(n),await Oe.writeFile(e,"");return}else throw r}o.isDirectory()?await Oe.writeFile(e,""):await Oe.readdir(n)}function ef(e){let t;try{t=Oe.statSync(e)}catch{}if(t&&t.isFile())return;let n=Ss.dirname(e);try{Oe.statSync(n).isDirectory()||Oe.readdirSync(n)}catch(o){if(o&&o.code==="ENOENT")Ts.mkdirsSync(n);else throw o}Oe.writeFileSync(e,"")}ws.exports={createFile:Qd(Zd),createFileSync:ef}});var As=O((Hh,Is)=>{"use strict";var tf=W().fromPromise,Os=require("path"),Le=X(),vs=pe(),{pathExists:nf}=De(),{areIdentical:Rs}=qe();async function of(e,t){let n;try{n=await Le.lstat(t)}catch{}let o;try{o=await Le.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}if(n&&Rs(o,n))return;let r=Os.dirname(t);await nf(r)||await vs.mkdirs(r),await Le.link(e,t)}function rf(e,t){let n;try{n=Le.lstatSync(t)}catch{}try{let i=Le.lstatSync(e);if(n&&Rs(i,n))return}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}let o=Os.dirname(t);return Le.existsSync(o)||vs.mkdirsSync(o),Le.linkSync(e,t)}Is.exports={createLink:tf(of),createLinkSync:rf}});var Cs=O((Wh,bs)=>{"use strict";var Me=require("path"),vt=X(),{pathExists:sf}=De(),af=W().fromPromise;async function cf(e,t){if(Me.isAbsolute(e)){try{await vt.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:e}}let n=Me.dirname(t),o=Me.join(n,e);if(await sf(o))return{toCwd:o,toDst:e};try{await vt.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:Me.relative(n,e)}}function lf(e,t){if(Me.isAbsolute(e)){if(!vt.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=Me.dirname(t),o=Me.join(n,e);if(vt.existsSync(o))return{toCwd:o,toDst:e};if(!vt.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:Me.relative(n,e)}}bs.exports={symlinkPaths:af(cf),symlinkPathsSync:lf}});var xs=O((Gh,Ps)=>{"use strict";var Ns=X(),uf=W().fromPromise;async function df(e,t){if(t)return t;let n;try{n=await Ns.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function ff(e,t){if(t)return t;let n;try{n=Ns.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Ps.exports={symlinkType:uf(df),symlinkTypeSync:ff}});var $s=O((Bh,Ms)=>{"use strict";var pf=W().fromPromise,Ds=require("path"),Se=X(),{mkdirs:mf,mkdirsSync:gf}=pe(),{symlinkPaths:hf,symlinkPathsSync:kf}=Cs(),{symlinkType:yf,symlinkTypeSync:Ef}=xs(),{pathExists:Sf}=De(),{areIdentical:Ls}=qe();async function Tf(e,t,n){let o;try{o=await Se.lstat(t)}catch{}if(o&&o.isSymbolicLink()){let[c,a]=await Promise.all([Se.stat(e),Se.stat(t)]);if(Ls(c,a))return}let r=await hf(e,t);e=r.toDst;let i=await yf(r.toCwd,n),s=Ds.dirname(t);return await Sf(s)||await mf(s),Se.symlink(e,t,i)}function wf(e,t,n){let o;try{o=Se.lstatSync(t)}catch{}if(o&&o.isSymbolicLink()){let c=Se.statSync(e),a=Se.statSync(t);if(Ls(c,a))return}let r=kf(e,t);e=r.toDst,n=Ef(r.toCwd,n);let i=Ds.dirname(t);return Se.existsSync(i)||gf(i),Se.symlinkSync(e,t,n)}Ms.exports={createSymlink:pf(Tf),createSymlinkSync:wf}});var qs=O((qh,Bs)=>{"use strict";var{createFile:Fs,createFileSync:Us}=_s(),{createLink:js,createLinkSync:Hs}=As(),{createSymlink:Ws,createSymlinkSync:Gs}=$s();Bs.exports={createFile:Fs,createFileSync:Us,ensureFile:Fs,ensureFileSync:Us,createLink:js,createLinkSync:Hs,ensureLink:js,ensureLinkSync:Hs,createSymlink:Ws,createSymlinkSync:Gs,ensureSymlink:Ws,ensureSymlinkSync:Gs}});var tn=O((Yh,Ys)=>{function _f(e,{EOL:t=`
9
- `,finalEOL:n=!0,replacer:o=null,spaces:r}={}){let i=n?t:"";return JSON.stringify(e,o,r).replace(/\n/g,t)+i}function Of(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}Ys.exports={stringify:_f,stripBom:Of}});var zs=O((Vh,Js)=>{var it;try{it=nt()}catch{it=require("fs")}var nn=W(),{stringify:Vs,stripBom:Ks}=tn();async function vf(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||it,o="throws"in t?t.throws:!0,r=await nn.fromCallback(n.readFile)(e,t);r=Ks(r);let i;try{i=JSON.parse(r,t?t.reviver:null)}catch(s){if(o)throw s.message=`${e}: ${s.message}`,s;return null}return i}var Rf=nn.fromPromise(vf);function If(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||it,o="throws"in t?t.throws:!0;try{let r=n.readFileSync(e,t);return r=Ks(r),JSON.parse(r,t.reviver)}catch(r){if(o)throw r.message=`${e}: ${r.message}`,r;return null}}async function Af(e,t,n={}){let o=n.fs||it,r=Vs(t,n);await nn.fromCallback(o.writeFile)(e,r,n)}var bf=nn.fromPromise(Af);function Cf(e,t,n={}){let o=n.fs||it,r=Vs(t,n);return o.writeFileSync(e,r,n)}Js.exports={readFile:Rf,readFileSync:If,writeFile:bf,writeFileSync:Cf}});var Qs=O((Kh,Xs)=>{"use strict";var on=zs();Xs.exports={readJson:on.readFile,readJsonSync:on.readFileSync,writeJson:on.writeFile,writeJsonSync:on.writeFileSync}});var rn=O((Jh,ta)=>{"use strict";var Nf=W().fromPromise,po=X(),Zs=require("path"),ea=pe(),Pf=De().pathExists;async function xf(e,t,n="utf-8"){let o=Zs.dirname(e);return await Pf(o)||await ea.mkdirs(o),po.writeFile(e,t,n)}function Df(e,...t){let n=Zs.dirname(e);po.existsSync(n)||ea.mkdirsSync(n),po.writeFileSync(e,...t)}ta.exports={outputFile:Nf(xf),outputFileSync:Df}});var oa=O((zh,na)=>{"use strict";var{stringify:Lf}=tn(),{outputFile:Mf}=rn();async function $f(e,t,n={}){let o=Lf(t,n);await Mf(e,o,n)}na.exports=$f});var ia=O((Xh,ra)=>{"use strict";var{stringify:Ff}=tn(),{outputFileSync:Uf}=rn();function jf(e,t,n){let o=Ff(t,n);Uf(e,o,n)}ra.exports=jf});var aa=O((Qh,sa)=>{"use strict";var Hf=W().fromPromise,Z=Qs();Z.outputJson=Hf(oa());Z.outputJsonSync=ia();Z.outputJSON=Z.outputJson;Z.outputJSONSync=Z.outputJsonSync;Z.writeJSON=Z.writeJson;Z.writeJSONSync=Z.writeJsonSync;Z.readJSON=Z.readJson;Z.readJSONSync=Z.readJsonSync;sa.exports=Z});var fa=O((Zh,da)=>{"use strict";var Wf=X(),ca=require("path"),{copy:Gf}=en(),{remove:ua}=Ot(),{mkdirp:Bf}=pe(),{pathExists:qf}=De(),la=qe();async function Yf(e,t,n={}){let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=await la.checkPaths(e,t,"move",n);await la.checkParentPaths(e,r,t,"move");let s=ca.dirname(t);return ca.parse(s).root!==s&&await Bf(s),Vf(e,t,o,i)}async function Vf(e,t,n,o){if(!o){if(n)await ua(t);else if(await qf(t))throw new Error("dest already exists.")}try{await Wf.rename(e,t)}catch(r){if(r.code!=="EXDEV")throw r;await Kf(e,t,n)}}async function Kf(e,t,n){return await Gf(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ua(e)}da.exports=Yf});var ka=O((ek,ha)=>{"use strict";var ma=nt(),go=require("path"),Jf=en().copySync,ga=Ot().removeSync,zf=pe().mkdirpSync,pa=qe();function Xf(e,t,n){n=n||{};let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=pa.checkPathsSync(e,t,"move",n);return pa.checkParentPathsSync(e,r,t,"move"),Qf(t)||zf(go.dirname(t)),Zf(e,t,o,i)}function Qf(e){let t=go.dirname(e);return go.parse(t).root===t}function Zf(e,t,n,o){if(o)return mo(e,t,n);if(n)return ga(t),mo(e,t,n);if(ma.existsSync(t))throw new Error("dest already exists.");return mo(e,t,n)}function mo(e,t,n){try{ma.renameSync(e,t)}catch(o){if(o.code!=="EXDEV")throw o;return ep(e,t,n)}}function ep(e,t,n){return Jf(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ga(e)}ha.exports=Xf});var Ea=O((tk,ya)=>{"use strict";var tp=W().fromPromise;ya.exports={move:tp(fa()),moveSync:ka()}});var sn=O((nk,Sa)=>{"use strict";Sa.exports={...X(),...en(),...Es(),...qs(),...aa(),...pe(),...Ea(),...rn(),...De(),...Ot()}});var Cg={};vu(Cg,{main:()=>Eu});module.exports=Ru(Cg);var Hn=new Map;function v(e){let t=Hn.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),Hn.set(e.event,t)}function Ir(e){return Hn.get(e)||[]}var Iu={ultrawork:/\b(ultrawork|ulw)\b/i,ultrathink:/\b(ultrathink|think)\b/i,olympus:/\b(olympus|orchestrate|coordinate|multi-?agent|conductor)\b/i,search:/\b(search|find|locate|lookup|explore|discover|scan|grep|query|browse|detect|trace|seek|track|pinpoint|hunt)\b|where\s+is|show\s+me|list\s+all/i,analyze:/\b(analyze|analyse|investigate|examine|research|study|deep.?dive|inspect|audit|evaluate|assess|review|diagnose|scrutinize|dissect|debug|comprehend|interpret|breakdown|understand)\b|why\s+is|how\s+does|how\s+to/i},Au=["ultrawork","ultrathink","olympus","search","analyze"];function Ar(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function br(e,t){let n=[];for(let o of Au){let r=Iu[o],i=e.match(r);i&&i.index!==void 0&&n.push({type:o,keyword:i[0],position:i.index})}return n}var Cr="auto-slash-command",Bt="<auto-slash-command>",qt="</auto-slash-command>",Nr=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Pr=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var bu=/```[\s\S]*?```/g;function xr(e){return e.replace(bu,"")}function Dr(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Nr);if(!n)return null;let[o,r,i]=n;return{command:r.toLowerCase(),args:i.trim(),raw:o}}function Lr(e){return Pr.has(e.toLowerCase())}function Wn(e){let n=xr(e).trim();if(!n.startsWith("/"))return null;let o=Dr(n);return!o||Lr(o.command)?null:o}function Gn(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var ye=require("fs"),we=require("path"),Fr=require("os"),Mr=(0,we.join)((0,Fr.homedir)(),".claude");function Ur(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,o,r]=n,i={};for(let s of o.split(`
10
- `)){let c=s.indexOf(":");if(c===-1)continue;let a=s.slice(0,c).trim(),l=s.slice(c+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i[a]=l}return{data:i,body:r}}function $r(e,t){if(!(0,ye.existsSync)(e))return[];let n;try{n=(0,ye.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let i=(0,we.join)(e,r.name),s=(0,we.basename)(r.name,".md");try{let c=(0,ye.readFileSync)(i,"utf-8"),{data:a,body:l}=Ur(c),u={name:s,description:a.description||"",argumentHint:a["argument-hint"],model:a.model,agent:a.agent};o.push({name:s,path:i,metadata:u,content:l,scope:t})}catch{continue}}return o}function Bn(){let e=(0,we.join)(Mr,"commands"),t=(0,we.join)(process.cwd(),".claude","commands"),n=(0,we.join)(Mr,"skills"),o=$r(e,"user"),r=$r(t,"project"),i=[];if((0,ye.existsSync)(n))try{let s=(0,ye.readdirSync)(n,{withFileTypes:!0});for(let c of s){if(!c.isDirectory())continue;let a=(0,we.join)(n,c.name,"SKILL.md");if((0,ye.existsSync)(a))try{let l=(0,ye.readFileSync)(a,"utf-8"),{data:u,body:d}=Ur(l),f={name:u.name||c.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};i.push({name:u.name||c.name,path:a,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...i]}function Yt(e){return Bn().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function Cu(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function Nu(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
8
+ see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:o,destStat:r}=vt.checkPathsSync(e,t,"copy",n);if(vt.checkParentPathsSync(e,o,t,"copy"),n.filter&&!n.filter(e,t))return;let i=Ot.dirname(t);return Z.existsSync(i)||jd(i),cs(r,e,t,n)}function cs(e,t,n,o){let i=(o.dereference?Z.statSync:Z.lstatSync)(t);if(i.isDirectory())return Jd(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Gd(i,e,t,n,o);if(i.isSymbolicLink())return Qd(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function Gd(e,t,n,o,r){return t?Bd(e,n,o,r):ls(e,n,o,r)}function Bd(e,t,n,o){if(o.overwrite)return Z.unlinkSync(n),ls(e,t,n,o);if(o.errorOnExist)throw new Error(`'${n}' already exists`)}function ls(e,t,n,o){return Z.copyFileSync(t,n),o.preserveTimestamps&&qd(e.mode,t,n),go(n,e.mode)}function qd(e,t,n){return Yd(e)&&Vd(n,e),Kd(t,n)}function Yd(e){return(e&128)===0}function Vd(e,t){return go(e,t|128)}function go(e,t){return Z.chmodSync(e,t)}function Kd(e,t){let n=Z.statSync(e);return Hd(t,n.atime,n.mtime)}function Jd(e,t,n,o,r){return t?us(n,o,r):zd(e.mode,n,o,r)}function zd(e,t,n,o){return Z.mkdirSync(n),us(t,n,o),go(n,e)}function us(e,t,n){let o=Z.opendirSync(e);try{let r;for(;(r=o.readSync())!==null;)Xd(r.name,e,t,n)}finally{o.closeSync()}}function Xd(e,t,n,o){let r=Ot.join(t,e),i=Ot.join(n,e);if(o.filter&&!o.filter(r,i))return;let{destStat:s}=vt.checkPathsSync(r,i,"copy",o);return cs(s,r,i,o)}function Qd(e,t,n,o){let r=Z.readlinkSync(t);if(o.dereference&&(r=Ot.resolve(process.cwd(),r)),e){let i;try{i=Z.readlinkSync(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return Z.symlinkSync(r,n);throw s}if(o.dereference&&(i=Ot.resolve(process.cwd(),i)),r!==i){if(vt.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(vt.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return Zd(r,n)}else return Z.symlinkSync(r,n)}function Zd(e,t){return Z.unlinkSync(t),Z.symlinkSync(e,t)}ds.exports=Wd});var nn=v((Bh,ps)=>{"use strict";var ef=G().fromPromise;ps.exports={copy:ef(as()),copySync:fs()}});var Rt=v((qh,gs)=>{"use strict";var ms=ot(),tf=G().fromCallback;function nf(e,t){ms.rm(e,{recursive:!0,force:!0},t)}function of(e){ms.rmSync(e,{recursive:!0,force:!0})}gs.exports={remove:tf(nf),removeSync:of}});var _s=v((Yh,ws)=>{"use strict";var rf=G().fromPromise,ys=Q(),Es=require("path"),Ss=me(),Ts=Rt(),hs=rf(async function(t){let n;try{n=await ys.readdir(t)}catch{return Ss.mkdirs(t)}return Promise.all(n.map(o=>Ts.remove(Es.join(t,o))))});function ks(e){let t;try{t=ys.readdirSync(e)}catch{return Ss.mkdirsSync(e)}t.forEach(n=>{n=Es.join(e,n),Ts.removeSync(n)})}ws.exports={emptyDirSync:ks,emptydirSync:ks,emptyDir:hs,emptydir:hs}});var Is=v((Vh,Rs)=>{"use strict";var sf=G().fromPromise,Os=require("path"),ve=Q(),vs=me();async function af(e){let t;try{t=await ve.stat(e)}catch{}if(t&&t.isFile())return;let n=Os.dirname(e),o=null;try{o=await ve.stat(n)}catch(r){if(r.code==="ENOENT"){await vs.mkdirs(n),await ve.writeFile(e,"");return}else throw r}o.isDirectory()?await ve.writeFile(e,""):await ve.readdir(n)}function cf(e){let t;try{t=ve.statSync(e)}catch{}if(t&&t.isFile())return;let n=Os.dirname(e);try{ve.statSync(n).isDirectory()||ve.readdirSync(n)}catch(o){if(o&&o.code==="ENOENT")vs.mkdirsSync(n);else throw o}ve.writeFileSync(e,"")}Rs.exports={createFile:sf(af),createFileSync:cf}});var Ps=v((Kh,Ns)=>{"use strict";var lf=G().fromPromise,bs=require("path"),Me=Q(),Cs=me(),{pathExists:uf}=Le(),{areIdentical:As}=Ye();async function df(e,t){let n;try{n=await Me.lstat(t)}catch{}let o;try{o=await Me.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}if(n&&As(o,n))return;let r=bs.dirname(t);await uf(r)||await Cs.mkdirs(r),await Me.link(e,t)}function ff(e,t){let n;try{n=Me.lstatSync(t)}catch{}try{let i=Me.lstatSync(e);if(n&&As(i,n))return}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}let o=bs.dirname(t);return Me.existsSync(o)||Cs.mkdirsSync(o),Me.linkSync(e,t)}Ns.exports={createLink:lf(df),createLinkSync:ff}});var Ds=v((Jh,xs)=>{"use strict";var $e=require("path"),It=Q(),{pathExists:pf}=Le(),mf=G().fromPromise;async function gf(e,t){if($e.isAbsolute(e)){try{await It.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:e}}let n=$e.dirname(t),o=$e.join(n,e);if(await pf(o))return{toCwd:o,toDst:e};try{await It.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:$e.relative(n,e)}}function hf(e,t){if($e.isAbsolute(e)){if(!It.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=$e.dirname(t),o=$e.join(n,e);if(It.existsSync(o))return{toCwd:o,toDst:e};if(!It.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:$e.relative(n,e)}}xs.exports={symlinkPaths:mf(gf),symlinkPathsSync:hf}});var $s=v((zh,Ms)=>{"use strict";var Ls=Q(),kf=G().fromPromise;async function yf(e,t){if(t)return t;let n;try{n=await Ls.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function Ef(e,t){if(t)return t;let n;try{n=Ls.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Ms.exports={symlinkType:kf(yf),symlinkTypeSync:Ef}});var Hs=v((Xh,js)=>{"use strict";var Sf=G().fromPromise,Fs=require("path"),Te=Q(),{mkdirs:Tf,mkdirsSync:wf}=me(),{symlinkPaths:_f,symlinkPathsSync:Of}=Ds(),{symlinkType:vf,symlinkTypeSync:Rf}=$s(),{pathExists:If}=Le(),{areIdentical:Us}=Ye();async function bf(e,t,n){let o;try{o=await Te.lstat(t)}catch{}if(o&&o.isSymbolicLink()){let[c,a]=await Promise.all([Te.stat(e),Te.stat(t)]);if(Us(c,a))return}let r=await _f(e,t);e=r.toDst;let i=await vf(r.toCwd,n),s=Fs.dirname(t);return await If(s)||await Tf(s),Te.symlink(e,t,i)}function Cf(e,t,n){let o;try{o=Te.lstatSync(t)}catch{}if(o&&o.isSymbolicLink()){let c=Te.statSync(e),a=Te.statSync(t);if(Us(c,a))return}let r=Of(e,t);e=r.toDst,n=Rf(r.toCwd,n);let i=Fs.dirname(t);return Te.existsSync(i)||wf(i),Te.symlinkSync(e,t,n)}js.exports={createSymlink:Sf(bf),createSymlinkSync:Cf}});var Js=v((Qh,Ks)=>{"use strict";var{createFile:Ws,createFileSync:Gs}=Is(),{createLink:Bs,createLinkSync:qs}=Ps(),{createSymlink:Ys,createSymlinkSync:Vs}=Hs();Ks.exports={createFile:Ws,createFileSync:Gs,ensureFile:Ws,ensureFileSync:Gs,createLink:Bs,createLinkSync:qs,ensureLink:Bs,ensureLinkSync:qs,createSymlink:Ys,createSymlinkSync:Vs,ensureSymlink:Ys,ensureSymlinkSync:Vs}});var on=v((Zh,zs)=>{function Af(e,{EOL:t=`
9
+ `,finalEOL:n=!0,replacer:o=null,spaces:r}={}){let i=n?t:"";return JSON.stringify(e,o,r).replace(/\n/g,t)+i}function Nf(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}zs.exports={stringify:Af,stripBom:Nf}});var ea=v((ek,Zs)=>{var st;try{st=ot()}catch{st=require("fs")}var rn=G(),{stringify:Xs,stripBom:Qs}=on();async function Pf(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||st,o="throws"in t?t.throws:!0,r=await rn.fromCallback(n.readFile)(e,t);r=Qs(r);let i;try{i=JSON.parse(r,t?t.reviver:null)}catch(s){if(o)throw s.message=`${e}: ${s.message}`,s;return null}return i}var xf=rn.fromPromise(Pf);function Df(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||st,o="throws"in t?t.throws:!0;try{let r=n.readFileSync(e,t);return r=Qs(r),JSON.parse(r,t.reviver)}catch(r){if(o)throw r.message=`${e}: ${r.message}`,r;return null}}async function Lf(e,t,n={}){let o=n.fs||st,r=Xs(t,n);await rn.fromCallback(o.writeFile)(e,r,n)}var Mf=rn.fromPromise(Lf);function $f(e,t,n={}){let o=n.fs||st,r=Xs(t,n);return o.writeFileSync(e,r,n)}Zs.exports={readFile:xf,readFileSync:Df,writeFile:Mf,writeFileSync:$f}});var na=v((tk,ta)=>{"use strict";var sn=ea();ta.exports={readJson:sn.readFile,readJsonSync:sn.readFileSync,writeJson:sn.writeFile,writeJsonSync:sn.writeFileSync}});var an=v((nk,ia)=>{"use strict";var Ff=G().fromPromise,ho=Q(),oa=require("path"),ra=me(),Uf=Le().pathExists;async function jf(e,t,n="utf-8"){let o=oa.dirname(e);return await Uf(o)||await ra.mkdirs(o),ho.writeFile(e,t,n)}function Hf(e,...t){let n=oa.dirname(e);ho.existsSync(n)||ra.mkdirsSync(n),ho.writeFileSync(e,...t)}ia.exports={outputFile:Ff(jf),outputFileSync:Hf}});var aa=v((ok,sa)=>{"use strict";var{stringify:Wf}=on(),{outputFile:Gf}=an();async function Bf(e,t,n={}){let o=Wf(t,n);await Gf(e,o,n)}sa.exports=Bf});var la=v((rk,ca)=>{"use strict";var{stringify:qf}=on(),{outputFileSync:Yf}=an();function Vf(e,t,n){let o=qf(t,n);Yf(e,o,n)}ca.exports=Vf});var da=v((ik,ua)=>{"use strict";var Kf=G().fromPromise,ee=na();ee.outputJson=Kf(aa());ee.outputJsonSync=la();ee.outputJSON=ee.outputJson;ee.outputJSONSync=ee.outputJsonSync;ee.writeJSON=ee.writeJson;ee.writeJSONSync=ee.writeJsonSync;ee.readJSON=ee.readJson;ee.readJSONSync=ee.readJsonSync;ua.exports=ee});var ha=v((sk,ga)=>{"use strict";var Jf=Q(),fa=require("path"),{copy:zf}=nn(),{remove:ma}=Rt(),{mkdirp:Xf}=me(),{pathExists:Qf}=Le(),pa=Ye();async function Zf(e,t,n={}){let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=await pa.checkPaths(e,t,"move",n);await pa.checkParentPaths(e,r,t,"move");let s=fa.dirname(t);return fa.parse(s).root!==s&&await Xf(s),ep(e,t,o,i)}async function ep(e,t,n,o){if(!o){if(n)await ma(t);else if(await Qf(t))throw new Error("dest already exists.")}try{await Jf.rename(e,t)}catch(r){if(r.code!=="EXDEV")throw r;await tp(e,t,n)}}async function tp(e,t,n){return await zf(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ma(e)}ga.exports=Zf});var Ta=v((ak,Sa)=>{"use strict";var ya=ot(),yo=require("path"),np=nn().copySync,Ea=Rt().removeSync,op=me().mkdirpSync,ka=Ye();function rp(e,t,n){n=n||{};let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=ka.checkPathsSync(e,t,"move",n);return ka.checkParentPathsSync(e,r,t,"move"),ip(t)||op(yo.dirname(t)),sp(e,t,o,i)}function ip(e){let t=yo.dirname(e);return yo.parse(t).root===t}function sp(e,t,n,o){if(o)return ko(e,t,n);if(n)return Ea(t),ko(e,t,n);if(ya.existsSync(t))throw new Error("dest already exists.");return ko(e,t,n)}function ko(e,t,n){try{ya.renameSync(e,t)}catch(o){if(o.code!=="EXDEV")throw o;return ap(e,t,n)}}function ap(e,t,n){return np(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),Ea(e)}Sa.exports=rp});var _a=v((ck,wa)=>{"use strict";var cp=G().fromPromise;wa.exports={move:cp(ha()),moveSync:Ta()}});var cn=v((lk,Oa)=>{"use strict";Oa.exports={...Q(),...nn(),..._s(),...Js(),...da(),...me(),..._a(),...an(),...Le(),...Rt()}});var $g={};Pu($g,{main:()=>Ru});module.exports=xu($g);var Bn=new Map;function R(e){let t=Bn.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),Bn.set(e.event,t)}function Nr(e){return Bn.get(e)||[]}var Du={ultrawork:/\b(ultrawork|ulw)\b/i,ultrathink:/\b(ultrathink|think)\b/i,olympus:/\b(olympus|orchestrate|coordinate|multi-?agent|conductor)\b/i,search:/\b(search|find|locate|lookup|explore|discover|scan|grep|query|browse|detect|trace|seek|track|pinpoint|hunt)\b|where\s+is|show\s+me|list\s+all/i,analyze:/\b(analyze|analyse|investigate|examine|research|study|deep.?dive|inspect|audit|evaluate|assess|review|diagnose|scrutinize|dissect|debug|comprehend|interpret|breakdown|understand)\b|why\s+is|how\s+does|how\s+to/i},Lu=["ultrawork","ultrathink","olympus","search","analyze"];function Pr(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function xr(e,t){let n=[];for(let o of Lu){let r=Du[o],i=e.match(r);i&&i.index!==void 0&&n.push({type:o,keyword:i[0],position:i.index})}return n}var Dr="auto-slash-command",Yt="<auto-slash-command>",Vt="</auto-slash-command>",Lr=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Mr=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Mu=/```[\s\S]*?```/g;function $r(e){return e.replace(Mu,"")}function Fr(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Lr);if(!n)return null;let[o,r,i]=n;return{command:r.toLowerCase(),args:i.trim(),raw:o}}function Ur(e){return Mr.has(e.toLowerCase())}function qn(e){let n=$r(e).trim();if(!n.startsWith("/"))return null;let o=Fr(n);return!o||Ur(o.command)?null:o}function Yn(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var Ee=require("fs"),_e=require("path"),Wr=require("os"),jr=(0,_e.join)((0,Wr.homedir)(),".claude");function Gr(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,o,r]=n,i={};for(let s of o.split(`
10
+ `)){let c=s.indexOf(":");if(c===-1)continue;let a=s.slice(0,c).trim(),l=s.slice(c+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i[a]=l}return{data:i,body:r}}function Hr(e,t){if(!(0,Ee.existsSync)(e))return[];let n;try{n=(0,Ee.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let i=(0,_e.join)(e,r.name),s=(0,_e.basename)(r.name,".md");try{let c=(0,Ee.readFileSync)(i,"utf-8"),{data:a,body:l}=Gr(c),u={name:s,description:a.description||"",argumentHint:a["argument-hint"],model:a.model,agent:a.agent};o.push({name:s,path:i,metadata:u,content:l,scope:t})}catch{continue}}return o}function Vn(){let e=(0,_e.join)(jr,"commands"),t=(0,_e.join)(process.cwd(),".claude","commands"),n=(0,_e.join)(jr,"skills"),o=Hr(e,"user"),r=Hr(t,"project"),i=[];if((0,Ee.existsSync)(n))try{let s=(0,Ee.readdirSync)(n,{withFileTypes:!0});for(let c of s){if(!c.isDirectory())continue;let a=(0,_e.join)(n,c.name,"SKILL.md");if((0,Ee.existsSync)(a))try{let l=(0,Ee.readFileSync)(a,"utf-8"),{data:u,body:d}=Gr(l),f={name:u.name||c.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};i.push({name:u.name||c.name,path:a,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...i]}function Kt(e){return Vn().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function $u(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function Fu(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
11
11
  `),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
12
12
  `),t&&n.push(`**Arguments**: ${t}
13
13
  `),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
14
14
  `),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
15
15
  `),n.push(`**Scope**: ${e.scope}
16
16
  `),n.push(`---
17
- `);let o=Cu(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
17
+ `);let o=$u(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
18
18
 
19
19
  ---
20
20
  `),n.push(`## User Request
21
21
  `),n.push(t)),n.join(`
22
- `)}function qn(e){let t=Yt(e.command);if(!t)return{success:!1,error:`Command "/${e.command}" not found. Available commands are in ~/.claude/commands/ or .claude/commands/`};try{return{success:!0,replacementText:Nu(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function Yn(){return Bn().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var Vt=new Set;function jr(){return{name:Cr,processMessage:(e,t)=>{let n=Gn(t);if(n.includes(Bt)||n.includes(qt))return{detected:!1};let o=Wn(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(Vt.has(r))return{detected:!1};Vt.add(r);let i=qn(o);if(i.success&&i.replacementText){let c=`${Bt}
22
+ `)}function Kn(e){let t=Kt(e.command);if(!t)return{success:!1,error:`Command "/${e.command}" not found. Available commands are in ~/.claude/commands/ or .claude/commands/`};try{return{success:!0,replacementText:Fu(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function Jn(){return Vn().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var Jt=new Set;function Br(){return{name:Dr,processMessage:(e,t)=>{let n=Yn(t);if(n.includes(Yt)||n.includes(Vt))return{detected:!1};let o=qn(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(Jt.has(r))return{detected:!1};Jt.add(r);let i=Kn(o);if(i.success&&i.replacementText){let c=`${Yt}
23
23
  ${i.replacementText}
24
- ${qt}`;return{detected:!0,parsedCommand:o,injectedMessage:c}}let s=`${Bt}
24
+ ${Vt}`;return{detected:!0,parsedCommand:o,injectedMessage:c}}let s=`${Yt}
25
25
  [AUTO-SLASH-COMMAND ERROR]
26
26
  ${i.error}
27
27
 
28
28
  Original input: ${o.raw}
29
- ${qt}`;return{detected:!0,parsedCommand:o,injectedMessage:s}},listCommands:()=>Yn(),findCommand:e=>Yt(e),clearSession:e=>{let t=[];for(let n of Vt)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)Vt.delete(n)}}}var Pu=[/\bultrathink\b/i,/\bthink\b/i],xu=["\uC0DD\uAC01","\uACE0\uBBFC","\uAC80\uD1A0","\uC81C\uB300\uB85C","\u601D\u8003","\u8003\u8651","\u8003\u616E","\u8003\u3048","\u719F\u8003","\u0938\u094B\u091A","\u0935\u093F\u091A\u093E\u0930","\u062A\u0641\u0643\u064A\u0631","\u062A\u0623\u0645\u0644","\u099A\u09BF\u09A8\u09CD\u09A4\u09BE","\u09AD\u09BE\u09AC\u09A8\u09BE","\u0434\u0443\u043C\u0430\u0442\u044C","\u0434\u0443\u043C\u0430\u0439","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0442\u044C","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0439","pensar","pense","refletir","reflita","piensa","reflexionar","reflexiona","penser","r\xE9fl\xE9chir","r\xE9fl\xE9chis","denken","denk","nachdenken","suy ngh\u0129","c\xE2n nh\u1EAFc","d\xFC\u015F\xFCn","d\xFC\u015F\xFCnmek","pensare","pensa","riflettere","rifletti","\u0E04\u0E34\u0E14","\u0E1E\u0E34\u0E08\u0E32\u0E23\u0E13\u0E32","my\u015Bl","my\u015Ble\u0107","zastan\xF3w","nadenken","berpikir","pikir","pertimbangkan","\u0434\u0443\u043C\u0430\u0442\u0438","\u0440\u043E\u0437\u0434\u0443\u043C\u0443\u0432\u0430\u0442\u0438","\u03C3\u03BA\u03AD\u03C8\u03BF\u03C5","\u03C3\u03BA\u03AD\u03C6\u03C4\u03BF\u03BC\u03B1\u03B9","myslet","mysli","p\u0159em\xFD\u0161let","g\xE2nde\u0219te","g\xE2ndi","reflect\u0103","t\xE4nka","t\xE4nk","fundera","gondolkodj","gondolkodni","ajattele","ajatella","pohdi","t\xE6nk","t\xE6nke","overvej","tenk","tenke","gruble","\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D4\u05E8\u05D4\u05E8"],Du=xu.map(e=>new RegExp(e,"i")),Lu=[...Pu,...Du],Mu=/```[\s\S]*?```/g,$u=/`[^`]+`/g;function Fu(e){return e.replace(Mu,"").replace($u,"")}function Hr(e){let t=Fu(e);return Lu.some(n=>n.test(t))}function Wr(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function Vn(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function Kn(e){return e.replace(/\.(\d+)/g,"-$1")}var Gr={"claude-sonnet-4-5":"claude-sonnet-4-5-high","claude-opus-4-5":"claude-opus-4-5-high","claude-3-5-sonnet":"claude-3-5-sonnet-high","claude-3-opus":"claude-3-opus-high","gpt-4":"gpt-4-high","gpt-4-turbo":"gpt-4-turbo-high","gpt-4o":"gpt-4o-high","gpt-5":"gpt-5-high","gpt-5-mini":"gpt-5-mini-high","gemini-2-pro":"gemini-2-pro-high","gemini-3-pro":"gemini-3-pro-high","gemini-3-flash":"gemini-3-flash-high"},Br=new Set(Object.values(Gr)),qr={anthropic:{thinking:{type:"enabled",budgetTokens:64e3},maxTokens:128e3},"amazon-bedrock":{reasoningConfig:{type:"enabled",budgetTokens:32e3},maxTokens:64e3},google:{providerOptions:{google:{thinkingConfig:{thinkingLevel:"HIGH"}}}},openai:{reasoning_effort:"high"}},Uu={anthropic:["claude-sonnet-4","claude-opus-4","claude-3"],"amazon-bedrock":["claude","anthropic"],google:["gemini-2","gemini-3"],openai:["gpt-4","gpt-5","o1","o3"]};function Yr(e){let t=Kn(e),{prefix:n,base:o}=Vn(t);if(Br.has(o)||o.endsWith("-high"))return null;let r=Gr[o];return r?n+r:null}function Jn(e){let t=Kn(e),{base:n}=Vn(t);return Br.has(n)||n.endsWith("-high")}function ju(e,t){if(e==="github-copilot"){let n=t.toLowerCase();if(n.includes("claude"))return"anthropic";if(n.includes("gemini"))return"google";if(n.includes("gpt")||n.includes("o1")||n.includes("o3"))return"openai"}return e}function Hu(e){return e in qr}function Vr(e,t){let n=Kn(t),{base:o}=Vn(n);if(Jn(n))return null;let r=ju(e,t);if(!Hu(r))return null;let i=qr[r],s=Uu[r];if(!s)return null;let c=o.toLowerCase();return s.some(l=>c.includes(l.toLowerCase()))?i:null}var be=new Map;function Wu(e){be.delete(e)}function Kr(){return{processChatParams:(e,t)=>{let n=Wr(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!Hr(n))return be.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,Jn(r.modelId)))return be.set(e,o),o;let i=Yr(r.modelId),s=Vr(r.providerId,r.modelId);return i&&(t.message.model={providerId:r.providerId,modelId:i},o.modelSwitched=!0),s&&(Object.assign(t.message,s),o.thinkingConfigInjected=!0),be.set(e,o),o},onSessionDeleted:e=>{be.delete(e)},isRequested:e=>be.get(e)?.requested??!1,getState:e=>be.get(e),clear:Wu}}var U=require("fs"),Qe=require("path"),zn=require("os");function Xn(e){let t=e||process.cwd(),n=(0,Qe.join)(t,".olympus");return(0,Qe.join)(n,"ultrawork-state.json")}function Qn(){return(0,Qe.join)((0,zn.homedir)(),".claude","ultrawork-state.json")}function Gu(e){let t=e||process.cwd(),n=(0,Qe.join)(t,".olympus");(0,U.existsSync)(n)||(0,U.mkdirSync)(n,{recursive:!0})}function Bu(){let e=(0,Qe.join)((0,zn.homedir)(),".claude");(0,U.existsSync)(e)||(0,U.mkdirSync)(e,{recursive:!0})}function We(e){let t=Xn(e);if((0,U.existsSync)(t))try{let o=(0,U.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Qn();if((0,U.existsSync)(n))try{let o=(0,U.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Jr(e,t){try{Gu(t);let n=Xn(t);(0,U.writeFileSync)(n,JSON.stringify(e,null,2)),Bu();let o=Qn();return(0,U.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function zr(e,t,n){let o={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return Jr(o,n)}function Xr(e){let t=Xn(e);if((0,U.existsSync)(t))try{(0,U.unlinkSync)(t)}catch{}let n=Qn();if((0,U.existsSync)(n))try{return(0,U.unlinkSync)(n),!0}catch{return!1}return!0}function Qr(e){let t=We(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Jr(t,e)?t:null)}function Zr(e){return`<ultrawork-persistence>
29
+ ${Vt}`;return{detected:!0,parsedCommand:o,injectedMessage:s}},listCommands:()=>Jn(),findCommand:e=>Kt(e),clearSession:e=>{let t=[];for(let n of Jt)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)Jt.delete(n)}}}var Uu=[/\bultrathink\b/i,/\bthink\b/i],ju=["\uC0DD\uAC01","\uACE0\uBBFC","\uAC80\uD1A0","\uC81C\uB300\uB85C","\u601D\u8003","\u8003\u8651","\u8003\u616E","\u8003\u3048","\u719F\u8003","\u0938\u094B\u091A","\u0935\u093F\u091A\u093E\u0930","\u062A\u0641\u0643\u064A\u0631","\u062A\u0623\u0645\u0644","\u099A\u09BF\u09A8\u09CD\u09A4\u09BE","\u09AD\u09BE\u09AC\u09A8\u09BE","\u0434\u0443\u043C\u0430\u0442\u044C","\u0434\u0443\u043C\u0430\u0439","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0442\u044C","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0439","pensar","pense","refletir","reflita","piensa","reflexionar","reflexiona","penser","r\xE9fl\xE9chir","r\xE9fl\xE9chis","denken","denk","nachdenken","suy ngh\u0129","c\xE2n nh\u1EAFc","d\xFC\u015F\xFCn","d\xFC\u015F\xFCnmek","pensare","pensa","riflettere","rifletti","\u0E04\u0E34\u0E14","\u0E1E\u0E34\u0E08\u0E32\u0E23\u0E13\u0E32","my\u015Bl","my\u015Ble\u0107","zastan\xF3w","nadenken","berpikir","pikir","pertimbangkan","\u0434\u0443\u043C\u0430\u0442\u0438","\u0440\u043E\u0437\u0434\u0443\u043C\u0443\u0432\u0430\u0442\u0438","\u03C3\u03BA\u03AD\u03C8\u03BF\u03C5","\u03C3\u03BA\u03AD\u03C6\u03C4\u03BF\u03BC\u03B1\u03B9","myslet","mysli","p\u0159em\xFD\u0161let","g\xE2nde\u0219te","g\xE2ndi","reflect\u0103","t\xE4nka","t\xE4nk","fundera","gondolkodj","gondolkodni","ajattele","ajatella","pohdi","t\xE6nk","t\xE6nke","overvej","tenk","tenke","gruble","\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D4\u05E8\u05D4\u05E8"],Hu=ju.map(e=>new RegExp(e,"i")),Wu=[...Uu,...Hu],Gu=/```[\s\S]*?```/g,Bu=/`[^`]+`/g;function qu(e){return e.replace(Gu,"").replace(Bu,"")}function qr(e){let t=qu(e);return Wu.some(n=>n.test(t))}function Yr(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function zn(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function Xn(e){return e.replace(/\.(\d+)/g,"-$1")}var Vr={"claude-sonnet-4-5":"claude-sonnet-4-5-high","claude-opus-4-5":"claude-opus-4-5-high","claude-3-5-sonnet":"claude-3-5-sonnet-high","claude-3-opus":"claude-3-opus-high","gpt-4":"gpt-4-high","gpt-4-turbo":"gpt-4-turbo-high","gpt-4o":"gpt-4o-high","gpt-5":"gpt-5-high","gpt-5-mini":"gpt-5-mini-high","gemini-2-pro":"gemini-2-pro-high","gemini-3-pro":"gemini-3-pro-high","gemini-3-flash":"gemini-3-flash-high"},Kr=new Set(Object.values(Vr)),Jr={anthropic:{thinking:{type:"enabled",budgetTokens:64e3},maxTokens:128e3},"amazon-bedrock":{reasoningConfig:{type:"enabled",budgetTokens:32e3},maxTokens:64e3},google:{providerOptions:{google:{thinkingConfig:{thinkingLevel:"HIGH"}}}},openai:{reasoning_effort:"high"}},Yu={anthropic:["claude-sonnet-4","claude-opus-4","claude-3"],"amazon-bedrock":["claude","anthropic"],google:["gemini-2","gemini-3"],openai:["gpt-4","gpt-5","o1","o3"]};function zr(e){let t=Xn(e),{prefix:n,base:o}=zn(t);if(Kr.has(o)||o.endsWith("-high"))return null;let r=Vr[o];return r?n+r:null}function Qn(e){let t=Xn(e),{base:n}=zn(t);return Kr.has(n)||n.endsWith("-high")}function Vu(e,t){if(e==="github-copilot"){let n=t.toLowerCase();if(n.includes("claude"))return"anthropic";if(n.includes("gemini"))return"google";if(n.includes("gpt")||n.includes("o1")||n.includes("o3"))return"openai"}return e}function Ku(e){return e in Jr}function Xr(e,t){let n=Xn(t),{base:o}=zn(n);if(Qn(n))return null;let r=Vu(e,t);if(!Ku(r))return null;let i=Jr[r],s=Yu[r];if(!s)return null;let c=o.toLowerCase();return s.some(l=>c.includes(l.toLowerCase()))?i:null}var Ae=new Map;function Ju(e){Ae.delete(e)}function Qr(){return{processChatParams:(e,t)=>{let n=Yr(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!qr(n))return Ae.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,Qn(r.modelId)))return Ae.set(e,o),o;let i=zr(r.modelId),s=Xr(r.providerId,r.modelId);return i&&(t.message.model={providerId:r.providerId,modelId:i},o.modelSwitched=!0),s&&(Object.assign(t.message,s),o.thinkingConfigInjected=!0),Ae.set(e,o),o},onSessionDeleted:e=>{Ae.delete(e)},isRequested:e=>Ae.get(e)?.requested??!1,getState:e=>Ae.get(e),clear:Ju}}var H=require("fs"),Ze=require("path"),Zn=require("os");function eo(e){let t=e||process.cwd(),n=(0,Ze.join)(t,".olympus");return(0,Ze.join)(n,"ultrawork-state.json")}function to(){return(0,Ze.join)((0,Zn.homedir)(),".claude","ultrawork-state.json")}function zu(e){let t=e||process.cwd(),n=(0,Ze.join)(t,".olympus");(0,H.existsSync)(n)||(0,H.mkdirSync)(n,{recursive:!0})}function Xu(){let e=(0,Ze.join)((0,Zn.homedir)(),".claude");(0,H.existsSync)(e)||(0,H.mkdirSync)(e,{recursive:!0})}function Ge(e){let t=eo(e);if((0,H.existsSync)(t))try{let o=(0,H.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=to();if((0,H.existsSync)(n))try{let o=(0,H.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Zr(e,t){try{zu(t);let n=eo(t);(0,H.writeFileSync)(n,JSON.stringify(e,null,2)),Xu();let o=to();return(0,H.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function ei(e,t,n){let o={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return Zr(o,n)}function ti(e){let t=eo(e);if((0,H.existsSync)(t))try{(0,H.unlinkSync)(t)}catch{}let n=to();if((0,H.existsSync)(n))try{return(0,H.unlinkSync)(n),!0}catch{return!1}return!0}function ni(e){let t=Ge(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Zr(t,e)?t:null)}function oi(e){return`<ultrawork-persistence>
30
30
 
31
31
  [ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
32
32
 
@@ -47,7 +47,7 @@ Original task: ${e.original_prompt}
47
47
 
48
48
  ---
49
49
 
50
- `}var ei=require("os"),q=require("path");function Ee(){return process.platform==="win32"}function qu(){return(0,q.join)((0,ei.homedir)(),".claude")}function ee(){return(0,q.join)(qu(),"hooks")}var ti=`<ultrawork-mode>
50
+ `}var ri=require("os"),Y=require("path");function Se(){return process.platform==="win32"}function Qu(){return(0,Y.join)((0,ri.homedir)(),".claude")}function te(){return(0,Y.join)(Qu(),"hooks")}var ii=`<ultrawork-mode>
51
51
 
52
52
  **MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
53
53
 
@@ -138,7 +138,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
138
138
 
139
139
  ---
140
140
 
141
- `,ni=`<think-mode>
141
+ `,si=`<think-mode>
142
142
 
143
143
  **ULTRATHINK MODE ENABLED** - Extended reasoning activated.
144
144
 
@@ -154,7 +154,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
154
154
 
155
155
  ---
156
156
 
157
- `;var oi=`<search-mode>
157
+ `;var ai=`<search-mode>
158
158
  MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
159
159
  - explore agents (codebase patterns, file structures)
160
160
  - librarian agents (remote repos, official docs, GitHub examples)
@@ -164,7 +164,7 @@ NEVER stop at first result - be exhaustive.
164
164
 
165
165
  ---
166
166
 
167
- `,ri=`<analyze-mode>
167
+ `,ci=`<analyze-mode>
168
168
  ANALYSIS MODE. Gather context before diving deep:
169
169
 
170
170
  CONTEXT GATHERING (parallel):
@@ -180,25 +180,25 @@ SYNTHESIZE findings before proceeding.
180
180
 
181
181
  ---
182
182
 
183
- `,ii=`[SYSTEM REMINDER - TODO CONTINUATION]
183
+ `,li=`[SYSTEM REMINDER - TODO CONTINUATION]
184
184
 
185
185
  Incomplete tasks remain in your todo list. Continue working on the next pending task.
186
186
 
187
187
  - Proceed without asking for permission
188
188
  - Mark each task complete when finished
189
- - Do not stop until all tasks are done`;var rh={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Ee()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:Ee()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:Ee()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},ih={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};var pi=require("path");var si=require("os"),Ce=require("path"),$=require("fs"),Yu=require("crypto");function Zn(e){if(!e.token_usage)return null;let{token_usage:t}=e;return typeof t.input_tokens!="number"||typeof t.output_tokens!="number"||typeof t.total_tokens!="number"||typeof t.estimated!="boolean"?null:t}function Ze(e){return Zn(e)?.total_tokens||0}var Vu=1e4;function Ne(){return(0,Ce.join)((0,si.homedir)(),".claude","olympus","learning")}function yt(e){return(0,Ce.join)(e,".olympus","learning")}function ai(e){let t=Ne();if((0,$.existsSync)(t)||(0,$.mkdirSync)(t,{recursive:!0}),e){let n=yt(e);(0,$.existsSync)(n)||(0,$.mkdirSync)(n,{recursive:!0})}}function ci(e,t=Vu){if((0,$.existsSync)(e))try{let o=(0,$.readFileSync)(e,"utf-8").split(`
190
- `).filter(r=>r.trim()).length;if(o>=t){let r=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${r}.old.jsonl`);(0,$.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${o} entries to ${i}`)}}catch(n){console.error(`[Olympus Learning] Failed to rotate ${e}:`,n)}}function Pe(e){ai();let t=(0,Ce.join)(Ne(),"feedback-log.jsonl");ci(t),(0,$.appendFileSync)(t,JSON.stringify(e)+`
191
- `,"utf-8")}function Ku(){let e=(0,Ce.join)(Ne(),"feedback-log.jsonl");return(0,$.existsSync)(e)?(0,$.readFileSync)(e,"utf-8").split(`
192
- `).filter(n=>n.trim()).map(n=>JSON.parse(n)):[]}function li(){return Ku()}function ui(e,t){let n=t.filter(u=>u.agent_used===e);if(n.length===0)return null;let o=n.length,r=n.filter(u=>u.event_type==="success").length,i=n.filter(u=>u.event_type==="revision").length,s=n.filter(u=>u.event_type==="cancellation").length,c=o>0?r/o:0,a,l=n.filter(u=>Zn(u)!==null);if(l.length>0){let u=l.filter(y=>y.event_type==="success"),d=l.filter(y=>y.event_type==="revision"||y.event_type==="cancellation"),f=l.reduce((y,T)=>y+Ze(T),0),g=u.reduce((y,T)=>y+Ze(T),0),m=d.reduce((y,T)=>y+Ze(T),0),p=u.length>0?g/u.length:0,h=d.length>0?m/d.length:0;if(a={avg_tokens_per_success:p,avg_tokens_per_failure:h,total_tokens:f,invocation_count:l.length,efficiency_score:p,trend:"insufficient_data"},l.length>=10){let y=Math.floor(l.length/2),T=l.slice(0,y),k=l.slice(y),A=T.reduce((ke,S)=>ke+Ze(S),0)/T.length,R=k.reduce((ke,S)=>ke+Ze(S),0)/k.length-A,w=A*.1;Math.abs(R)<w?a.trend="stable":R<0?a.trend="improving":a.trend="declining"}}return{agent_name:e,total_invocations:o,success_count:r,revision_count:i,cancellation_count:s,success_rate:c,failure_patterns:[],strong_areas:[],weak_areas:[],last_updated:new Date().toISOString(),token_efficiency:a}}function et(e,t){if(!(0,$.existsSync)(e))return t;try{return JSON.parse((0,$.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function di(e,t){try{let n=(0,Ce.dirname)(e);n&&!(0,$.existsSync)(n)&&(0,$.mkdirSync)(n,{recursive:!0}),(0,$.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}var mi=require("crypto");function Ge(e,t,n){return!n||n.sample_count<5?1e4:e&&n.by_project[e]!==void 0?n.by_project[e]:t&&n.by_task_type[t]!==void 0?n.by_task_type[t]:n.overall_avg}var Ju=10,zu=1800*1e3;function gi(e){return(0,pi.join)(e,".olympus","session-state.json")}function fi(e,t){let n=Ge(t);return{session_id:e||(0,mi.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null,token_budget:{session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}}}function te(e,t){let n=gi(e),o=et(n,null);if(!o)return fi(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>zu)return fi(t,e);if(o.token_budget)o.token_budget.input_tokens===void 0&&(o.token_budget.input_tokens=0),o.token_budget.output_tokens===void 0&&(o.token_budget.output_tokens=0);else{let s=Ge(e);o.token_budget={session_baseline:s,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o}function J(e,t){let n=gi(e);t.last_updated=new Date().toISOString(),di(n,t)}function hi(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,Ju),e.last_updated=new Date().toISOString(),e}function ki(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Kt(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}function yi(e,t){let n=Ge(t);return e.token_budget={session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function Ei(e,t){return e.token_budget||(e.token_budget={session_baseline:Ge(),current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e.token_budget.current_usage+=t,e.last_updated=new Date().toISOString(),e}function Si(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function Ti(e){if(!e.token_budget||e.token_budget.warning_issued)return!1;let t=e.token_budget.session_baseline*e.token_budget.warning_threshold;return e.token_budget.current_usage>=t}var wi=require("crypto"),Xu={correction:[{regex:/no[,.]?\s*(that's|thats)?\s*(not|wrong)/i,confidence:.9},{regex:/that's\s*(incorrect|not right|not what)/i,confidence:.9},{regex:/you\s*(misunderstood|got it wrong)/i,confidence:.85},{regex:/actually,?\s*(I|it|the)/i,confidence:.6}],rejection:[{regex:/\b(stop|cancel|abort|halt)\b/i,confidence:.95},{regex:/don't\s*(do|want|need)\s*(that|this)/i,confidence:.85},{regex:/never\s*mind/i,confidence:.9},{regex:/forget\s*(it|that|about)/i,confidence:.8}],clarification:[{regex:/I\s*(meant|wanted|asked for)/i,confidence:.85},{regex:/what I\s*(mean|want|need)/i,confidence:.8},{regex:/to clarify/i,confidence:.9},{regex:/let me\s*(rephrase|explain|be clearer)/i,confidence:.85}],explicit_preference:[{regex:/always\s+(use|do|include|add|prefer)/i,confidence:.95},{regex:/never\s+(use|do|include|add)/i,confidence:.95},{regex:/I\s*(prefer|like|want)\s*(you to)?/i,confidence:.7},{regex:/from now on/i,confidence:.9},{regex:/in the future,?\s*(please|always)/i,confidence:.85}],praise:[{regex:/\bperfect\b/i,confidence:.9},{regex:/exactly(\s+what I (wanted|needed))?/i,confidence:.85},{regex:/great(\s+job)?/i,confidence:.7},{regex:/\bthanks?\b/i,confidence:.5},{regex:/looks?\s+good/i,confidence:.75}],enhancement:[{regex:/also\s+(add|include|do)/i,confidence:.7},{regex:/can you (also|additionally)/i,confidence:.7},{regex:/one more thing/i,confidence:.75}]};function eo(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Xu))for(let{regex:i,confidence:s}of r)i.test(t)&&(!n||s>n.confidence)&&(n={category:o,confidence:s});return n}async function _i(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=te(n,o),i=eo(t),s=hi(r,t,i?.category);if(i&&Kt(r)){let c={id:(0,wi.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:i.category==="explicit_preference"?"explicit_preference":"revision",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:i.category,confidence:i.confidence};Pe(c)}J(n,s)}var Oi=require("crypto");async function vi(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=te(n,o);if(!Kt(r))return;let i=eo(t),s=i?.category==="praise"&&i.confidence>.7,c=Qu(t,r.pending_completion?.task_description||"");if(s||c){let a={id:(0,Oi.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:"success",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:s?"praise":"enhancement",confidence:s?i.confidence:.6};Pe(a);let l=ki(r);J(n,l)}}function Qu(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(l=>l.length>3)),o=n(e),r=n(t),i=new Set([...o].filter(a=>r.has(a))),s=new Set([...o,...r]);return(s.size>0?i.size/s.size:0)<.2}var re=H(sn(),1),Rt=require("path"),ko=".olympus/workflow",Ta="checkpoint.json",ho=new Map,np=5e3;function wa(e,t){return`${e}:${t}`}function op(e){return Date.now()-e.timestamp<np}async function $e(e,t){let n=(0,Rt.join)(e,ko,t.workflow_id),o=(0,Rt.join)(n,Ta);try{if(t.updated_at=new Date().toISOString(),await re.ensureDir(n),JSON.stringify(t).length>1e4){let c=JSON.stringify(t);await re.writeFile(o,c,"utf-8")}else await re.writeJson(o,t,{spaces:2});let s=wa(e,t.workflow_id);ho.set(s,{checkpoint:{...t},timestamp:Date.now(),dirty:!1})}catch(r){let i=r;throw i.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${o}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):i.code==="EACCES"||i.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint: Permission denied for ${o}`)):i.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${o}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",i.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${i.message}`))}}async function me(e,t){let n=wa(e,t),o=ho.get(n);if(o&&op(o))return{...o.checkpoint};let r=(0,Rt.join)(e,ko,t,Ta);try{let i=await re.readFile(r,"utf-8"),s=JSON.parse(i);return s.schema_version?(ho.set(n,{checkpoint:{...s},timestamp:Date.now(),dirty:!1}),s):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${r}`),null)}catch(i){let s=i,c=s;return c.code==="ENOENT"?null:s.name==="SyntaxError"||s.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${r}`),console.warn(`[Checkpoint] Error: ${s.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):c.code==="EACCES"||c.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${r}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${s.message}`),console.warn(`[Checkpoint] Path: ${r}`),null)}}async function _a(e){let t=(0,Rt.join)(e,ko);try{return await re.pathExists(t)?(await re.readdir(t,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name):[]}catch(n){let o=n;return o.code==="EACCES"||o.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied listing workflows in ${t}`),[]):(console.warn(`[Checkpoint] Failed to list workflows: ${o.message}`),console.warn(`[Checkpoint] Directory: ${t}`),[])}}var ve=H(require("path"),1),se=H(sn(),1);async function Oa(e,t){let n=ve.join(e,".olympus","workflow",t),o=ve.join(n,"intents"),r=ve.join(n,"validation"),i=ve.join(n,"checkpoint.json");try{await se.ensureDir(n),await se.ensureDir(o),await se.ensureDir(r),await se.pathExists(i)||await se.writeJson(i,{workflow_id:t,current_stage:"idea",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(s){let c=s;throw c.code==="ENOSPC"?(console.error("[Artifacts] Failed to create workflow directory: Disk full"),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Attempted path: ${n}`),new Error("Failed to create workflow directory: Disk is full. Please free up space and retry.")):c.code==="EACCES"||c.code==="EPERM"?(console.error("[Artifacts] Failed to create workflow directory: Permission denied"),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory: Permission denied for ${n}`)):c.code==="EROFS"?(console.error("[Artifacts] Failed to create workflow directory: Read-only filesystem"),console.error(`[Artifacts] Path: ${n}`),new Error("Failed to create workflow directory: Filesystem is read-only")):(console.error(`[Artifacts] Failed to create workflow directory: ${c.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${c.message}`))}}function Fe(e,t,n){if(n==="complete")throw new Error("No artifact file for complete stage");if(n==="intents")throw new Error("Intents is a directory, not a single file. Use getIntentsDir() instead.");let o=ve.join(e,".olympus","workflow",t),i={idea:"idea.md",prd:"prd.md",spec:"spec.md"}[n];return ve.join(o,i)}async function an(e,t,n,o){if(n==="intents")throw new Error("Cannot write single artifact for intents stage. Use writeIntentFile() instead.");let r=Fe(e,t,n);try{await se.ensureDir(ve.dirname(r)),await se.writeFile(r,o,"utf-8")}catch(i){let s=i;throw s.code==="ENOSPC"?(console.error(`[Artifacts] Failed to write ${n} artifact: Disk full`),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):s.code==="EACCES"||s.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Permission denied for ${r}`)):s.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${s.message}`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: ${s.message}`))}}var Ye=require("fs"),va=new Map,rp=1e4;function ip(e){let t=va.get(e);if(t&&Date.now()-t.timestamp<rp)return t.content;let n=(0,Ye.readFileSync)(e,"utf-8");return va.set(e,{content:n,timestamp:Date.now()}),n}var sp=["Problem Statement","Business Context","Success Metrics","Constraints","Solution Approach"];async function Ra(e){let t=new Date().toISOString(),n=[],o;try{o=ip(e)}catch(d){let f=d;return f.code==="ENOENT"?(console.error(`[Validation] IDEA artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):f.code==="EACCES"||f.code==="EPERM"?(console.error(`[Validation] Permission denied reading IDEA artifact: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Permission denied reading artifact file"],timestamp:t}):(console.error(`[Validation] Failed to read IDEA artifact: ${f.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${f.message}`],timestamp:t})}let r=ap(o);(!r||!r.risk_tier)&&n.push("Risk tier not specified in frontmatter");let i=st(o),s=It(i),c=[()=>{let d=s.get("Problem Statement");return!d||d.trim().length===0?"Missing problem statement section":null},()=>{let d=s.get("Business Context");return!d||d.trim().length===0?"Business context section is empty":null},()=>{let d=s.get("Success Metrics");if(d){let f=Ia(d);if(f<2)return`Only ${f} success metric found, need at least 2`}else return"Missing success metrics section";return null},()=>{let d=s.get("Constraints");return!d||d.trim().length===0?"Constraints section missing":null},()=>{let d=[];for(let f of sp)s.has(f)||d.push(`Missing required section: ${f}`);return d.length>0?d.join("; "):null}];for(let d of c){let f=d();f&&n.push(f)}let a=6,l=a-n.length,u=Math.round(l/a*100);return{passed:n.length===0,coverage_percentage:u,blocking_issues:n,timestamp:t}}function ap(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
193
- `);for(let i of r){let s=i.match(/^(\w+):\s*(.+)$/);if(s){let[,c,a]=s;o[c]=a.trim()}}return o}catch{return null}}function st(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function It(e){let t=new Map,n=e.split(`
189
+ - Do not stop until all tasks are done`;var dh={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Se()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:Se()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:Se()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},fh={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Se()?`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:Se()?`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:Se()?`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:Se()?`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:Se()?`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:Se()?`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:Se()?`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,Y.join)(te(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};var ki=require("path");var ui=require("os"),Ne=require("path"),U=require("fs"),Zu=require("crypto");function no(e){if(!e.token_usage)return null;let{token_usage:t}=e;return typeof t.input_tokens!="number"||typeof t.output_tokens!="number"||typeof t.total_tokens!="number"||typeof t.estimated!="boolean"?null:t}function et(e){return no(e)?.total_tokens||0}var ed=1e4;function Pe(){return(0,Ne.join)((0,ui.homedir)(),".claude","olympus","learning")}function St(e){return(0,Ne.join)(e,".olympus","learning")}function di(e){let t=Pe();if((0,U.existsSync)(t)||(0,U.mkdirSync)(t,{recursive:!0}),e){let n=St(e);(0,U.existsSync)(n)||(0,U.mkdirSync)(n,{recursive:!0})}}function fi(e,t=ed){if((0,U.existsSync)(e))try{let o=(0,U.readFileSync)(e,"utf-8").split(`
190
+ `).filter(r=>r.trim()).length;if(o>=t){let r=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${r}.old.jsonl`);(0,U.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${o} entries to ${i}`)}}catch(n){console.error(`[Olympus Learning] Failed to rotate ${e}:`,n)}}function xe(e){di();let t=(0,Ne.join)(Pe(),"feedback-log.jsonl");fi(t),(0,U.appendFileSync)(t,JSON.stringify(e)+`
191
+ `,"utf-8")}function td(){let e=(0,Ne.join)(Pe(),"feedback-log.jsonl");return(0,U.existsSync)(e)?(0,U.readFileSync)(e,"utf-8").split(`
192
+ `).filter(n=>n.trim()).map(n=>JSON.parse(n)):[]}function pi(){return td()}function mi(e,t){let n=t.filter(u=>u.agent_used===e);if(n.length===0)return null;let o=n.length,r=n.filter(u=>u.event_type==="success").length,i=n.filter(u=>u.event_type==="revision").length,s=n.filter(u=>u.event_type==="cancellation").length,c=o>0?r/o:0,a,l=n.filter(u=>no(u)!==null);if(l.length>0){let u=l.filter(y=>y.event_type==="success"),d=l.filter(y=>y.event_type==="revision"||y.event_type==="cancellation"),f=l.reduce((y,w)=>y+et(w),0),g=u.reduce((y,w)=>y+et(w),0),m=d.reduce((y,w)=>y+et(w),0),p=u.length>0?g/u.length:0,h=d.length>0?m/d.length:0;if(a={avg_tokens_per_success:p,avg_tokens_per_failure:h,total_tokens:f,invocation_count:l.length,efficiency_score:p,trend:"insufficient_data"},l.length>=10){let y=Math.floor(l.length/2),w=l.slice(0,y),k=l.slice(y),C=w.reduce((ye,T)=>ye+et(T),0)/w.length,I=k.reduce((ye,T)=>ye+et(T),0)/k.length-C,_=C*.1;Math.abs(I)<_?a.trend="stable":I<0?a.trend="improving":a.trend="declining"}}return{agent_name:e,total_invocations:o,success_count:r,revision_count:i,cancellation_count:s,success_rate:c,failure_patterns:[],strong_areas:[],weak_areas:[],last_updated:new Date().toISOString(),token_efficiency:a}}function tt(e,t){if(!(0,U.existsSync)(e))return t;try{return JSON.parse((0,U.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function gi(e,t){try{let n=(0,Ne.dirname)(e);n&&!(0,U.existsSync)(n)&&(0,U.mkdirSync)(n,{recursive:!0}),(0,U.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}var yi=require("crypto");function Be(e,t,n){return!n||n.sample_count<5?1e4:e&&n.by_project[e]!==void 0?n.by_project[e]:t&&n.by_task_type[t]!==void 0?n.by_task_type[t]:n.overall_avg}var nd=10,od=1800*1e3;function Ei(e){return(0,ki.join)(e,".olympus","session-state.json")}function hi(e,t){let n=Be(t);return{session_id:e||(0,yi.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null,token_budget:{session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}}}function ne(e,t){let n=Ei(e),o=tt(n,null);if(!o)return hi(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>od)return hi(t,e);if(t&&o.session_id!==t&&(o.session_id=t),o.token_budget)o.token_budget.input_tokens===void 0&&(o.token_budget.input_tokens=0),o.token_budget.output_tokens===void 0&&(o.token_budget.output_tokens=0);else{let s=Be(e);o.token_budget={session_baseline:s,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o}function z(e,t){let n=Ei(e);t.last_updated=new Date().toISOString(),gi(n,t)}function Si(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,nd),e.last_updated=new Date().toISOString(),e}function Ti(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function zt(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}function wi(e,t){let n=Be(t);return e.token_budget={session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function _i(e,t){return e.token_budget||(e.token_budget={session_baseline:Be(),current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e.token_budget.current_usage+=t,e.last_updated=new Date().toISOString(),e}function Oi(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function vi(e){if(!e.token_budget||e.token_budget.warning_issued)return!1;let t=e.token_budget.session_baseline*e.token_budget.warning_threshold;return e.token_budget.current_usage>=t}var Ri=require("crypto"),rd={correction:[{regex:/no[,.]?\s*(that's|thats)?\s*(not|wrong)/i,confidence:.9},{regex:/that's\s*(incorrect|not right|not what)/i,confidence:.9},{regex:/you\s*(misunderstood|got it wrong)/i,confidence:.85},{regex:/actually,?\s*(I|it|the)/i,confidence:.6}],rejection:[{regex:/\b(stop|cancel|abort|halt)\b/i,confidence:.95},{regex:/don't\s*(do|want|need)\s*(that|this)/i,confidence:.85},{regex:/never\s*mind/i,confidence:.9},{regex:/forget\s*(it|that|about)/i,confidence:.8}],clarification:[{regex:/I\s*(meant|wanted|asked for)/i,confidence:.85},{regex:/what I\s*(mean|want|need)/i,confidence:.8},{regex:/to clarify/i,confidence:.9},{regex:/let me\s*(rephrase|explain|be clearer)/i,confidence:.85}],explicit_preference:[{regex:/always\s+(use|do|include|add|prefer)/i,confidence:.95},{regex:/never\s+(use|do|include|add)/i,confidence:.95},{regex:/I\s*(prefer|like|want)\s*(you to)?/i,confidence:.7},{regex:/from now on/i,confidence:.9},{regex:/in the future,?\s*(please|always)/i,confidence:.85}],praise:[{regex:/\bperfect\b/i,confidence:.9},{regex:/exactly(\s+what I (wanted|needed))?/i,confidence:.85},{regex:/great(\s+job)?/i,confidence:.7},{regex:/\bthanks?\b/i,confidence:.5},{regex:/looks?\s+good/i,confidence:.75}],enhancement:[{regex:/also\s+(add|include|do)/i,confidence:.7},{regex:/can you (also|additionally)/i,confidence:.7},{regex:/one more thing/i,confidence:.75}]};function oo(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(rd))for(let{regex:i,confidence:s}of r)i.test(t)&&(!n||s>n.confidence)&&(n={category:o,confidence:s});return n}async function Ii(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=ne(n,o),i=oo(t),s=Si(r,t,i?.category);if(i&&zt(r)){let c={id:(0,Ri.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:i.category==="explicit_preference"?"explicit_preference":"revision",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:i.category,confidence:i.confidence};xe(c)}z(n,s)}var bi=require("crypto");async function Ci(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=ne(n,o);if(!zt(r))return;let i=oo(t),s=i?.category==="praise"&&i.confidence>.7,c=id(t,r.pending_completion?.task_description||"");if(s||c){let a={id:(0,bi.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:"success",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:s?"praise":"enhancement",confidence:s?i.confidence:.6};xe(a);let l=Ti(r);z(n,l)}}function id(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(l=>l.length>3)),o=n(e),r=n(t),i=new Set([...o].filter(a=>r.has(a))),s=new Set([...o,...r]);return(s.size>0?i.size/s.size:0)<.2}var ie=F(cn(),1),bt=require("path"),So=".olympus/workflow",va="checkpoint.json",Eo=new Map,lp=5e3;function Ra(e,t){return`${e}:${t}`}function up(e){return Date.now()-e.timestamp<lp}async function Fe(e,t){let n=(0,bt.join)(e,So,t.workflow_id),o=(0,bt.join)(n,va);try{if(t.updated_at=new Date().toISOString(),await ie.ensureDir(n),JSON.stringify(t).length>1e4){let c=JSON.stringify(t);await ie.writeFile(o,c,"utf-8")}else await ie.writeJson(o,t,{spaces:2});let s=Ra(e,t.workflow_id);Eo.set(s,{checkpoint:{...t},timestamp:Date.now(),dirty:!1})}catch(r){let i=r;throw i.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${o}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):i.code==="EACCES"||i.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint: Permission denied for ${o}`)):i.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${o}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",i.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${i.message}`))}}async function ge(e,t){let n=Ra(e,t),o=Eo.get(n);if(o&&up(o))return{...o.checkpoint};let r=(0,bt.join)(e,So,t,va);try{let i=await ie.readFile(r,"utf-8"),s=JSON.parse(i);return s.schema_version?(Eo.set(n,{checkpoint:{...s},timestamp:Date.now(),dirty:!1}),s):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${r}`),null)}catch(i){let s=i,c=s;return c.code==="ENOENT"?null:s.name==="SyntaxError"||s.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${r}`),console.warn(`[Checkpoint] Error: ${s.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):c.code==="EACCES"||c.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${r}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${s.message}`),console.warn(`[Checkpoint] Path: ${r}`),null)}}async function Ia(e){let t=(0,bt.join)(e,So);try{return await ie.pathExists(t)?(await ie.readdir(t,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name):[]}catch(n){let o=n;return o.code==="EACCES"||o.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied listing workflows in ${t}`),[]):(console.warn(`[Checkpoint] Failed to list workflows: ${o.message}`),console.warn(`[Checkpoint] Directory: ${t}`),[])}}var Re=F(require("path"),1),ae=F(cn(),1);async function ba(e,t){let n=Re.join(e,".olympus","workflow",t),o=Re.join(n,"intents"),r=Re.join(n,"validation"),i=Re.join(n,"checkpoint.json");try{await ae.ensureDir(n),await ae.ensureDir(o),await ae.ensureDir(r),await ae.pathExists(i)||await ae.writeJson(i,{workflow_id:t,current_stage:"idea",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(s){let c=s;throw c.code==="ENOSPC"?(console.error("[Artifacts] Failed to create workflow directory: Disk full"),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Attempted path: ${n}`),new Error("Failed to create workflow directory: Disk is full. Please free up space and retry.")):c.code==="EACCES"||c.code==="EPERM"?(console.error("[Artifacts] Failed to create workflow directory: Permission denied"),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory: Permission denied for ${n}`)):c.code==="EROFS"?(console.error("[Artifacts] Failed to create workflow directory: Read-only filesystem"),console.error(`[Artifacts] Path: ${n}`),new Error("Failed to create workflow directory: Filesystem is read-only")):(console.error(`[Artifacts] Failed to create workflow directory: ${c.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${c.message}`))}}function Ue(e,t,n){if(n==="complete")throw new Error("No artifact file for complete stage");if(n==="intents")throw new Error("Intents is a directory, not a single file. Use getIntentsDir() instead.");let o=Re.join(e,".olympus","workflow",t),i={idea:"idea.md",prd:"prd.md",spec:"spec.md"}[n];return Re.join(o,i)}async function ln(e,t,n,o){if(n==="intents")throw new Error("Cannot write single artifact for intents stage. Use writeIntentFile() instead.");let r=Ue(e,t,n);try{await ae.ensureDir(Re.dirname(r)),await ae.writeFile(r,o,"utf-8")}catch(i){let s=i;throw s.code==="ENOSPC"?(console.error(`[Artifacts] Failed to write ${n} artifact: Disk full`),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):s.code==="EACCES"||s.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Permission denied for ${r}`)):s.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${s.message}`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: ${s.message}`))}}var Ve=require("fs"),Ca=new Map,dp=1e4;function fp(e){let t=Ca.get(e);if(t&&Date.now()-t.timestamp<dp)return t.content;let n=(0,Ve.readFileSync)(e,"utf-8");return Ca.set(e,{content:n,timestamp:Date.now()}),n}var pp=["Problem Statement","Business Context","Success Metrics","Constraints","Solution Approach"];async function Aa(e){let t=new Date().toISOString(),n=[],o;try{o=fp(e)}catch(d){let f=d;return f.code==="ENOENT"?(console.error(`[Validation] IDEA artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):f.code==="EACCES"||f.code==="EPERM"?(console.error(`[Validation] Permission denied reading IDEA artifact: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Permission denied reading artifact file"],timestamp:t}):(console.error(`[Validation] Failed to read IDEA artifact: ${f.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${f.message}`],timestamp:t})}let r=mp(o);(!r||!r.risk_tier)&&n.push("Risk tier not specified in frontmatter");let i=at(o),s=Ct(i),c=[()=>{let d=s.get("Problem Statement");return!d||d.trim().length===0?"Missing problem statement section":null},()=>{let d=s.get("Business Context");return!d||d.trim().length===0?"Business context section is empty":null},()=>{let d=s.get("Success Metrics");if(d){let f=Na(d);if(f<2)return`Only ${f} success metric found, need at least 2`}else return"Missing success metrics section";return null},()=>{let d=s.get("Constraints");return!d||d.trim().length===0?"Constraints section missing":null},()=>{let d=[];for(let f of pp)s.has(f)||d.push(`Missing required section: ${f}`);return d.length>0?d.join("; "):null}];for(let d of c){let f=d();f&&n.push(f)}let a=6,l=a-n.length,u=Math.round(l/a*100);return{passed:n.length===0,coverage_percentage:u,blocking_issues:n,timestamp:t}}function mp(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
193
+ `);for(let i of r){let s=i.match(/^(\w+):\s*(.+)$/);if(s){let[,c,a]=s;o[c]=a.trim()}}return o}catch{return null}}function at(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Ct(e){let t=new Map,n=e.split(`
194
194
  `),o=null,r=[];for(let i of n){let s=i.match(/^##\s+(.+)$/);s?(o&&t.set(o,r.join(`
195
195
  `)),o=s[1].trim(),r=[]):o&&r.push(i)}return o&&t.set(o,r.join(`
196
- `)),t}function Ia(e){let t=e.split(`
197
- `),n=0;for(let o of t)o.trim().match(/^[-*+]\s+/)&&n++;return n}async function Aa(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ye.readFileSync)(e,"utf-8")}catch(p){let h=p;return console.error(`[Validation] Failed to read PRD artifact: ${h.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[h.code==="ENOENT"?"PRD artifact file not found":h.code==="EACCES"||h.code==="EPERM"?"Permission denied reading PRD artifact":`Failed to read PRD artifact: ${h.message}`],reviewer:"momus",timestamp:n}}let i;try{i=(0,Ye.readFileSync)(t,"utf-8")}catch(p){let h=p;return console.error(`[Validation] Failed to read IDEA artifact for PRD validation: ${h.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[h.code==="ENOENT"?"IDEA artifact file not found for reference":h.code==="EACCES"||h.code==="EPERM"?"Permission denied reading IDEA artifact":`Failed to read IDEA artifact: ${h.message}`],reviewer:"momus",timestamp:n}}let s=st(i),a=It(s).get("Constraints"),l=a?Ia(a):0,u=st(r),d=It(u),f=0;for(let p of u.split(`
198
- `))p.match(/^###?\s+US-\d+/)&&f++;let g=d.has("Requirement Coverage"),m=l>0?Math.round(Math.min(f,l)/l*100):100;return f===0&&o.push("No user stories found in PRD"),g||o.push("Missing Requirement Coverage section"),m<90&&o.push(`Coverage only ${m}%, need at least 90% (${f}/${l} constraints addressed)`),{passed:o.length===0&&m>=90,coverage_percentage:m,blocking_issues:o,reviewer:"momus",timestamp:n}}async function ba(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ye.readFileSync)(e,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read SPEC artifact: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"SPEC artifact file not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading SPEC artifact":`Failed to read SPEC artifact: ${p.message}`],reviewer:"metis",timestamp:n}}let i;try{i=(0,Ye.readFileSync)(t,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read PRD artifact for SPEC validation: ${p.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"PRD artifact file not found for reference":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading PRD artifact":`Failed to read PRD artifact: ${p.message}`],reviewer:"metis",timestamp:n}}let s=st(i),c=[];for(let m of s.split(`
199
- `)){let p=m.match(/^###?\s+(US-\d+)/);p&&c.push(p[1])}let a=st(r),l=It(a),u=l.get("Requirement Coverage")||l.get("PRD Coverage")||"",d=0;for(let m of c)a.includes(m)&&d++;let f=c.length>0?Math.round(d/c.length*100):0;return c.length===0&&o.push("No user stories found in PRD for validation"),(!u||u.trim().length===0)&&o.push("Missing Requirement Coverage section in SPEC"),f<95&&o.push(`Coverage only ${f}%, need at least 95% (${d}/${c.length} user stories addressed)`),l.has("Components")||l.has("Architecture")||o.push("Missing Components or Architecture section"),{passed:o.length===0&&f>=95,coverage_percentage:f,blocking_issues:o,reviewer:"metis",timestamp:n}}async function Ca(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ye.readFileSync)(t,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read SPEC artifact for task validation: ${p.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"SPEC artifact file not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading SPEC artifact":`Failed to read SPEC artifact: ${p.message}`],timestamp:n}}let i=st(r),s=It(i),c=s.get("Components")||s.get("Architecture")||"",a=[];if(c)for(let m of c.split(`
200
- `)){let p=m.match(/^###\s+(.+)$/);p&&a.push(p[1].trim())}let l=[];try{l=(await import("fs")).readdirSync(e).filter(h=>h.endsWith(".md")||h.includes("INTENT"))}catch(m){let p=m;return console.error(`[Validation] Failed to read tasks directory: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"Tasks directory not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading tasks directory":`Failed to read tasks directory: ${p.message}`],timestamp:n}}let u=new Set,d=[];for(let m of l)try{let p=await import("fs"),y=(await import("path")).join(e,m),T=p.readFileSync(y,"utf-8");for(let A of a)T.includes(A)&&u.add(A);let k=T.match(/estimated_effort:\s*(\d+)/i);k&&d.push(parseInt(k[1],10))}catch{}let f=a.length>0?Math.round(u.size/a.length*100):100;if(a.length===0)o.push("No components found in SPEC for validation");else if(f<100){let m=a.filter(p=>!u.has(p));o.push(`Incomplete coverage: ${f}% (missing: ${m.join(", ")})`)}let g=[1,2,4,8,16];for(let m of d)g.includes(m)||o.push(`Invalid effort estimate: ${m} hours (must be 1, 2, 4, 8, or 16)`);if(l.length>0&&d.length===0&&o.push("No effort estimates found in task files"),d.length>1){let m=d.reduce((h,y)=>h+y,0)/d.length,p=m*.3;for(let h of d)Math.abs(h-m)>p&&Math.abs(h-m)>m*.5&&o.push(`High variance in effort estimates: ${h}h vs avg ${Math.round(m)}h`)}try{let m=await import("fs"),h=(await import("path")).join(e,"dependency-graph.json"),y=m.readFileSync(h,"utf-8"),T=JSON.parse(y);cp(T)&&o.push("Circular dependencies detected in dependency graph");let A=new Set(Object.keys(T));for(let[D,R]of Object.entries(T))if(Array.isArray(R))for(let w of R)A.has(w)||o.push(`Task ${D} references non-existent dependency: ${w}`)}catch{}return{passed:o.length===0&&f===100,coverage_percentage:f,blocking_issues:o,timestamp:n}}function cp(e){let t=new Set,n=new Set;function o(r){t.add(r),n.add(r);let i=e[r]||[];for(let s of i)if(t.has(s)){if(n.has(s))return!0}else if(o(s))return!0;return n.delete(r),!1}for(let r of Object.keys(e))if(!t.has(r)&&o(r))return!0;return!1}var cn=["idea","prd","spec","intents","complete"];function lp(e){let t=cn.indexOf(e);return t===-1||t>=cn.length-1?"complete":cn[t+1]}var ln=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n,this.workflowId=n.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}async start(t){let n={schema_version:"1.0.0",workflow_id:this.workflowId,feature_name:this.featureName,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_stage:"idea",status:"in_progress",artifacts:{idea:null,prd:null,spec:null,intents:null,complete:null},validation_results:{idea:null,prd:null,spec:null,intents:null,complete:null},resume_context:{initial_prompt:t}};try{await Oa(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${r.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${r.message}`)}try{await $e(this.projectPath,n)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${r.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${r.message}`)}this.setupInterruptHandler();try{await this.executeStage("idea")}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute IDEA stage: ${r.message}`);try{let i=await me(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:"idea"},await $e(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Resume with `/plan continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute IDEA stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}}async resume(){let t;try{t=await me(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${r.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),console.error("[WorkflowEngine] Available workflows: Run 'olympus workflow list' to see workflows"),new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(t.status==="complete")return"Workflow already complete";if(t.status==="paused"){t.status="in_progress";try{await $e(this.projectPath,t)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${r.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${r.message}`)}}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${r.message}`);try{let i=await me(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:n},await $e(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/plan continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute ${n} stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await me(this.projectPath,this.workflowId)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${o.message}`),new Error(`Failed to pause workflow: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);t.status="paused";try{await $e(this.projectPath,t)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${o.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${o.message}`)}return`.olympus/workflow/${this.workflowId}/checkpoint.json`}async executeStage(t){if(t==="complete")throw new Error("No execution for complete stage");let n=await me(this.projectPath,this.workflowId);if(!n)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);switch(t){case"idea":await this.executeIdeaStage(n);break;case"prd":await this.executePrdStage(n);break;case"spec":await this.executeSpecStage(n);break;case"intents":await this.executeIntentsStage(n);break}let o=`${t.toUpperCase()}-001`,r=t==="intents"?`.olympus/workflow/${this.workflowId}/intents/`:`.olympus/workflow/${this.workflowId}/${t}.md`;n.artifacts[t]={id:o,path:r,created_at:new Date().toISOString(),validation_passed:n.validation_results[t]?.passed??!1};let i=lp(t);n.current_stage=i,i==="complete"&&(n.status="complete"),await $e(this.projectPath,n)}async getStatus(){let t;try{t=await me(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${r.message}`),new Error(`Failed to get workflow status: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);let n=[];for(let o of cn){let r=t.artifacts[o];r&&n.push(r)}return{workflow_id:t.workflow_id,feature_name:t.feature_name,current_stage:t.current_stage,status:t.status,artifacts:n,updated_at:t.updated_at}}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
201
- [WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await me(this.projectPath,this.workflowId);t&&(t.status="paused",t.updated_at=new Date().toISOString(),t.resume_context={...t.resume_context,interrupted_at:new Date().toISOString(),current_stage:t.current_stage,message:`Workflow interrupted during ${t.current_stage} stage`},await $e(this.projectPath,t),console.log("[WorkflowEngine] Checkpoint saved. Resume with `/plan continue`"))}catch(t){console.error("[WorkflowEngine] Failed to save checkpoint on interrupt:",t)}process.exit(0)},process.on("SIGINT",this.interruptHandler)}cleanupInterruptHandler(){this.interruptHandler&&(process.off("SIGINT",this.interruptHandler),this.interruptHandler=null)}async executeIdeaStage(t){let n=t.resume_context?.initial_prompt||"No initial prompt provided";console.log(`[WorkflowEngine] Executing IDEA stage for feature: ${this.featureName}`),console.log(`[WorkflowEngine] Initial prompt: ${n}`),console.log("[WorkflowEngine] Generating IDEA artifact with structured format");let o="IDEA-001",r=new Date().toISOString(),i=`---
196
+ `)),t}function Na(e){let t=e.split(`
197
+ `),n=0;for(let o of t)o.trim().match(/^[-*+]\s+/)&&n++;return n}async function Pa(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ve.readFileSync)(e,"utf-8")}catch(p){let h=p;return console.error(`[Validation] Failed to read PRD artifact: ${h.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[h.code==="ENOENT"?"PRD artifact file not found":h.code==="EACCES"||h.code==="EPERM"?"Permission denied reading PRD artifact":`Failed to read PRD artifact: ${h.message}`],reviewer:"momus",timestamp:n}}let i;try{i=(0,Ve.readFileSync)(t,"utf-8")}catch(p){let h=p;return console.error(`[Validation] Failed to read IDEA artifact for PRD validation: ${h.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[h.code==="ENOENT"?"IDEA artifact file not found for reference":h.code==="EACCES"||h.code==="EPERM"?"Permission denied reading IDEA artifact":`Failed to read IDEA artifact: ${h.message}`],reviewer:"momus",timestamp:n}}let s=at(i),a=Ct(s).get("Constraints"),l=a?Na(a):0,u=at(r),d=Ct(u),f=0;for(let p of u.split(`
198
+ `))p.match(/^###?\s+US-\d+/)&&f++;let g=d.has("Requirement Coverage"),m=l>0?Math.round(Math.min(f,l)/l*100):100;return f===0&&o.push("No user stories found in PRD"),g||o.push("Missing Requirement Coverage section"),m<90&&o.push(`Coverage only ${m}%, need at least 90% (${f}/${l} constraints addressed)`),{passed:o.length===0&&m>=90,coverage_percentage:m,blocking_issues:o,reviewer:"momus",timestamp:n}}async function xa(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ve.readFileSync)(e,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read SPEC artifact: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"SPEC artifact file not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading SPEC artifact":`Failed to read SPEC artifact: ${p.message}`],reviewer:"metis",timestamp:n}}let i;try{i=(0,Ve.readFileSync)(t,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read PRD artifact for SPEC validation: ${p.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"PRD artifact file not found for reference":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading PRD artifact":`Failed to read PRD artifact: ${p.message}`],reviewer:"metis",timestamp:n}}let s=at(i),c=[];for(let m of s.split(`
199
+ `)){let p=m.match(/^###?\s+(US-\d+)/);p&&c.push(p[1])}let a=at(r),l=Ct(a),u=l.get("Requirement Coverage")||l.get("PRD Coverage")||"",d=0;for(let m of c)a.includes(m)&&d++;let f=c.length>0?Math.round(d/c.length*100):0;return c.length===0&&o.push("No user stories found in PRD for validation"),(!u||u.trim().length===0)&&o.push("Missing Requirement Coverage section in SPEC"),f<95&&o.push(`Coverage only ${f}%, need at least 95% (${d}/${c.length} user stories addressed)`),l.has("Components")||l.has("Architecture")||o.push("Missing Components or Architecture section"),{passed:o.length===0&&f>=95,coverage_percentage:f,blocking_issues:o,reviewer:"metis",timestamp:n}}async function Da(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ve.readFileSync)(t,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read SPEC artifact for task validation: ${p.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"SPEC artifact file not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading SPEC artifact":`Failed to read SPEC artifact: ${p.message}`],timestamp:n}}let i=at(r),s=Ct(i),c=s.get("Components")||s.get("Architecture")||"",a=[];if(c)for(let m of c.split(`
200
+ `)){let p=m.match(/^###\s+(.+)$/);p&&a.push(p[1].trim())}let l=[];try{l=(await import("fs")).readdirSync(e).filter(h=>h.endsWith(".md")||h.includes("INTENT"))}catch(m){let p=m;return console.error(`[Validation] Failed to read tasks directory: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"Tasks directory not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading tasks directory":`Failed to read tasks directory: ${p.message}`],timestamp:n}}let u=new Set,d=[];for(let m of l)try{let p=await import("fs"),y=(await import("path")).join(e,m),w=p.readFileSync(y,"utf-8");for(let C of a)w.includes(C)&&u.add(C);let k=w.match(/estimated_effort:\s*(\d+)/i);k&&d.push(parseInt(k[1],10))}catch{}let f=a.length>0?Math.round(u.size/a.length*100):100;if(a.length===0)o.push("No components found in SPEC for validation");else if(f<100){let m=a.filter(p=>!u.has(p));o.push(`Incomplete coverage: ${f}% (missing: ${m.join(", ")})`)}let g=[1,2,4,8,16];for(let m of d)g.includes(m)||o.push(`Invalid effort estimate: ${m} hours (must be 1, 2, 4, 8, or 16)`);if(l.length>0&&d.length===0&&o.push("No effort estimates found in task files"),d.length>1){let m=d.reduce((h,y)=>h+y,0)/d.length,p=m*.3;for(let h of d)Math.abs(h-m)>p&&Math.abs(h-m)>m*.5&&o.push(`High variance in effort estimates: ${h}h vs avg ${Math.round(m)}h`)}try{let m=await import("fs"),h=(await import("path")).join(e,"dependency-graph.json"),y=m.readFileSync(h,"utf-8"),w=JSON.parse(y);gp(w)&&o.push("Circular dependencies detected in dependency graph");let C=new Set(Object.keys(w));for(let[L,I]of Object.entries(w))if(Array.isArray(I))for(let _ of I)C.has(_)||o.push(`Task ${L} references non-existent dependency: ${_}`)}catch{}return{passed:o.length===0&&f===100,coverage_percentage:f,blocking_issues:o,timestamp:n}}function gp(e){let t=new Set,n=new Set;function o(r){t.add(r),n.add(r);let i=e[r]||[];for(let s of i)if(t.has(s)){if(n.has(s))return!0}else if(o(s))return!0;return n.delete(r),!1}for(let r of Object.keys(e))if(!t.has(r)&&o(r))return!0;return!1}var un=["idea","prd","spec","intents","complete"];function hp(e){let t=un.indexOf(e);return t===-1||t>=un.length-1?"complete":un[t+1]}var dn=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n,this.workflowId=n.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}async start(t){let n={schema_version:"1.0.0",workflow_id:this.workflowId,feature_name:this.featureName,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_stage:"idea",status:"in_progress",artifacts:{idea:null,prd:null,spec:null,intents:null,complete:null},validation_results:{idea:null,prd:null,spec:null,intents:null,complete:null},resume_context:{initial_prompt:t}};try{await ba(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${r.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${r.message}`)}try{await Fe(this.projectPath,n)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${r.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${r.message}`)}this.setupInterruptHandler();try{await this.executeStage("idea")}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute IDEA stage: ${r.message}`);try{let i=await ge(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:"idea"},await Fe(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Resume with `/plan continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute IDEA stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}}async resume(){let t;try{t=await ge(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${r.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),console.error("[WorkflowEngine] Available workflows: Run 'olympus workflow list' to see workflows"),new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(t.status==="complete")return"Workflow already complete";if(t.status==="paused"){t.status="in_progress";try{await Fe(this.projectPath,t)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${r.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${r.message}`)}}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${r.message}`);try{let i=await ge(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:n},await Fe(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/plan continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute ${n} stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await ge(this.projectPath,this.workflowId)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${o.message}`),new Error(`Failed to pause workflow: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);t.status="paused";try{await Fe(this.projectPath,t)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${o.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${o.message}`)}return`.olympus/workflow/${this.workflowId}/checkpoint.json`}async executeStage(t){if(t==="complete")throw new Error("No execution for complete stage");let n=await ge(this.projectPath,this.workflowId);if(!n)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);switch(t){case"idea":await this.executeIdeaStage(n);break;case"prd":await this.executePrdStage(n);break;case"spec":await this.executeSpecStage(n);break;case"intents":await this.executeIntentsStage(n);break}let o=`${t.toUpperCase()}-001`,r=t==="intents"?`.olympus/workflow/${this.workflowId}/intents/`:`.olympus/workflow/${this.workflowId}/${t}.md`;n.artifacts[t]={id:o,path:r,created_at:new Date().toISOString(),validation_passed:n.validation_results[t]?.passed??!1};let i=hp(t);n.current_stage=i,i==="complete"&&(n.status="complete"),await Fe(this.projectPath,n)}async getStatus(){let t;try{t=await ge(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${r.message}`),new Error(`Failed to get workflow status: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);let n=[];for(let o of un){let r=t.artifacts[o];r&&n.push(r)}return{workflow_id:t.workflow_id,feature_name:t.feature_name,current_stage:t.current_stage,status:t.status,artifacts:n,updated_at:t.updated_at}}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
201
+ [WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await ge(this.projectPath,this.workflowId);t&&(t.status="paused",t.updated_at=new Date().toISOString(),t.resume_context={...t.resume_context,interrupted_at:new Date().toISOString(),current_stage:t.current_stage,message:`Workflow interrupted during ${t.current_stage} stage`},await Fe(this.projectPath,t),console.log("[WorkflowEngine] Checkpoint saved. Resume with `/plan continue`"))}catch(t){console.error("[WorkflowEngine] Failed to save checkpoint on interrupt:",t)}process.exit(0)},process.on("SIGINT",this.interruptHandler)}cleanupInterruptHandler(){this.interruptHandler&&(process.off("SIGINT",this.interruptHandler),this.interruptHandler=null)}async executeIdeaStage(t){let n=t.resume_context?.initial_prompt||"No initial prompt provided";console.log(`[WorkflowEngine] Executing IDEA stage for feature: ${this.featureName}`),console.log(`[WorkflowEngine] Initial prompt: ${n}`),console.log("[WorkflowEngine] Generating IDEA artifact with structured format");let o="IDEA-001",r=new Date().toISOString(),i=`---
202
202
  id: ${o}
203
203
  feature: ${this.workflowId}
204
204
  feature_name: ${this.featureName}
@@ -271,7 +271,7 @@ The proposed solution will follow a phased implementation approach:
271
271
 
272
272
  ---
273
273
  *Generated by WorkflowEngine*
274
- `;await an(this.projectPath,this.workflowId,"idea",i);let s=Fe(this.projectPath,this.workflowId,"idea");console.log(`[WorkflowEngine] Validating IDEA artifact at: ${s}`);let c=await Ra(s);t.validation_results.idea=c,c.passed?console.log("[WorkflowEngine] IDEA validation passed"):(console.log("[WorkflowEngine] IDEA validation failed:",c.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`))}async executePrdStage(t){console.log(`[WorkflowEngine] Executing PRD stage for feature: ${this.featureName}`);let n=Fe(this.projectPath,this.workflowId,"idea");console.log(`[WorkflowEngine] Reading IDEA artifact from: ${n}`),console.log("[WorkflowEngine] Generating PRD artifact with user stories");let o="PRD-001",r=new Date().toISOString(),i=`---
274
+ `;await ln(this.projectPath,this.workflowId,"idea",i);let s=Ue(this.projectPath,this.workflowId,"idea");console.log(`[WorkflowEngine] Validating IDEA artifact at: ${s}`);let c=await Aa(s);t.validation_results.idea=c,c.passed?console.log("[WorkflowEngine] IDEA validation passed"):(console.log("[WorkflowEngine] IDEA validation failed:",c.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`))}async executePrdStage(t){console.log(`[WorkflowEngine] Executing PRD stage for feature: ${this.featureName}`);let n=Ue(this.projectPath,this.workflowId,"idea");console.log(`[WorkflowEngine] Reading IDEA artifact from: ${n}`),console.log("[WorkflowEngine] Generating PRD artifact with user stories");let o="PRD-001",r=new Date().toISOString(),i=`---
275
275
  id: ${o}
276
276
  feature: ${this.workflowId}
277
277
  created: ${r}
@@ -425,7 +425,7 @@ Success will be measured using the following criteria from the IDEA artifact:
425
425
 
426
426
  ---
427
427
  *Generated by WorkflowEngine based on IDEA-001*
428
- `;await an(this.projectPath,this.workflowId,"prd",i);let s=Fe(this.projectPath,this.workflowId,"prd");console.log(`[WorkflowEngine] Validating PRD artifact at: ${s}`);let c=await Aa(s,n);t.validation_results.prd=c,c.passed?(console.log("[WorkflowEngine] PRD validation passed"),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`)):(console.log("[WorkflowEngine] PRD validation failed:",c.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`))}async executeSpecStage(t){console.log(`[WorkflowEngine] Executing SPEC stage for feature: ${this.featureName}`);let n=Fe(this.projectPath,this.workflowId,"prd");console.log(`[WorkflowEngine] Reading PRD artifact from: ${n}`),console.log("[WorkflowEngine] Generating SPEC artifact with technical design");let r=(await import("fs")).readFileSync(n,"utf-8"),i=[],s=r.split(`
428
+ `;await ln(this.projectPath,this.workflowId,"prd",i);let s=Ue(this.projectPath,this.workflowId,"prd");console.log(`[WorkflowEngine] Validating PRD artifact at: ${s}`);let c=await Pa(s,n);t.validation_results.prd=c,c.passed?(console.log("[WorkflowEngine] PRD validation passed"),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`)):(console.log("[WorkflowEngine] PRD validation failed:",c.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`))}async executeSpecStage(t){console.log(`[WorkflowEngine] Executing SPEC stage for feature: ${this.featureName}`);let n=Ue(this.projectPath,this.workflowId,"prd");console.log(`[WorkflowEngine] Reading PRD artifact from: ${n}`),console.log("[WorkflowEngine] Generating SPEC artifact with technical design");let r=(await import("fs")).readFileSync(n,"utf-8"),i=[],s=r.split(`
429
429
  `);for(let f of s){let g=f.match(/^###?\s+(US-\d+)/);g&&i.push(g[1])}let c="SPEC-001",a=new Date().toISOString(),l=`---
430
430
  id: ${c}
431
431
  feature: ${this.workflowId}
@@ -781,7 +781,7 @@ This specification addresses all user stories from PRD-001:
781
781
 
782
782
  ---
783
783
  *Generated by WorkflowEngine based on PRD-001*
784
- `;await an(this.projectPath,this.workflowId,"spec",l);let u=Fe(this.projectPath,this.workflowId,"spec");console.log(`[WorkflowEngine] Validating SPEC artifact at: ${u}`);let d=await ba(u,n);t.validation_results.spec=d,d.passed?(console.log("[WorkflowEngine] SPEC validation passed"),console.log(`[WorkflowEngine] Coverage: ${d.coverage_percentage}%`)):(console.log("[WorkflowEngine] SPEC validation failed:",d.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${d.coverage_percentage}%`))}async executeIntentsStage(t){console.log(`[WorkflowEngine] Executing INTENTS stage for feature: ${this.featureName}`);let n=Fe(this.projectPath,this.workflowId,"spec");console.log(`[WorkflowEngine] Reading SPEC artifact from: ${n}`),console.log("[WorkflowEngine] Generating INTENT artifacts with implementation tasks");let o=await Promise.resolve().then(()=>H(sn(),1)),r=await import("path"),i=await o.readFile(n,"utf-8"),s=[],c=i.split(`
784
+ `;await ln(this.projectPath,this.workflowId,"spec",l);let u=Ue(this.projectPath,this.workflowId,"spec");console.log(`[WorkflowEngine] Validating SPEC artifact at: ${u}`);let d=await xa(u,n);t.validation_results.spec=d,d.passed?(console.log("[WorkflowEngine] SPEC validation passed"),console.log(`[WorkflowEngine] Coverage: ${d.coverage_percentage}%`)):(console.log("[WorkflowEngine] SPEC validation failed:",d.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${d.coverage_percentage}%`))}async executeIntentsStage(t){console.log(`[WorkflowEngine] Executing INTENTS stage for feature: ${this.featureName}`);let n=Ue(this.projectPath,this.workflowId,"spec");console.log(`[WorkflowEngine] Reading SPEC artifact from: ${n}`),console.log("[WorkflowEngine] Generating INTENT artifacts with implementation tasks");let o=await Promise.resolve().then(()=>F(cn(),1)),r=await import("path"),i=await o.readFile(n,"utf-8"),s=[],c=i.split(`
785
785
  `),a=!1;for(let p of c){if(p.match(/^##\s+Components/i)){a=!0;continue}if(a&&p.match(/^##\s+/)&&(a=!1),a&&p.match(/^###\s+(.+)$/)){let h=p.match(/^###\s+(.+)$/);h&&s.push(h[1].trim())}}let l=r.join(this.projectPath,".olympus","workflow",this.workflowId,"intents");await o.ensureDir(l);let u=new Date().toISOString(),d=[{id:"INTENT-001",title:"Setup Database Schema",component:"Database Components",goal:"Create database tables, indexes, and migration scripts",acceptanceCriteria:["Database tables created with proper schema","Indexes created for performance optimization","Migration scripts tested and validated","Rollback scripts prepared"],steps:["Create migration script for feature_data table","Create migration script for feature_audit_log table","Add indexes on foreign keys and frequently queried columns","Test migration in development environment","Create rollback migration script","Document schema changes"],technicalNotes:"Use migration framework (Flyway/Alembic/TypeORM migrations). Ensure backward compatibility.",dependencies:[],effort:4},{id:"INTENT-002",title:"Implement Backend API Endpoints",component:"Backend Services",goal:"Create RESTful API endpoints for feature operations",acceptanceCriteria:["All CRUD endpoints implemented","Request validation middleware in place","Error handling properly configured","Unit tests passing with >80% coverage"],steps:["Create API route definitions","Implement POST /api/v1/feature endpoint","Implement GET /api/v1/feature/:id endpoint","Implement PUT /api/v1/feature/:id endpoint","Implement DELETE /api/v1/feature/:id endpoint","Add request validation middleware","Add error handling middleware","Write unit tests for all endpoints"],technicalNotes:"Follow REST conventions. Use async/await for database operations. Implement proper error responses.",dependencies:["INTENT-001"],effort:8},{id:"INTENT-003",title:"Build Frontend Components",component:"Frontend Components",goal:"Create user interface components for feature interaction",acceptanceCriteria:["Main feature UI component implemented","Form validation working correctly","Error states handled gracefully","Responsive design across devices","Accessibility standards met (WCAG 2.1 AA)"],steps:["Create main feature component","Implement form inputs with validation","Add error boundary component","Implement loading states","Add success/error notifications","Make responsive for mobile/tablet/desktop","Test with screen readers","Write component tests"],technicalNotes:"Use component library patterns. Implement proper state management. Follow accessibility guidelines.",dependencies:["INTENT-002"],effort:8},{id:"INTENT-004",title:"Implement Authentication and Authorization",component:"Backend Services",goal:"Add authentication and authorization for feature endpoints",acceptanceCriteria:["JWT authentication middleware implemented","Role-based access control enforced","Token refresh mechanism working","Unauthorized access properly blocked"],steps:["Implement JWT verification middleware","Create role-based permission checks","Add token refresh endpoint","Implement token blacklist for logout","Add authentication to all protected routes","Write authentication tests"],technicalNotes:"Use secure token storage. Implement token rotation. Follow OWASP authentication guidelines.",dependencies:["INTENT-002"],effort:4},{id:"INTENT-005",title:"Add Rate Limiting and Caching",component:"Backend Services",goal:"Implement rate limiting and caching for performance and security",acceptanceCriteria:["Rate limiting active on all endpoints","Rate limit headers in responses","Application-level caching implemented","Cache invalidation working correctly"],steps:["Set up Redis for rate limiting and caching","Implement rate limiting middleware","Add rate limit headers to responses","Implement application-level cache","Add cache invalidation on mutations","Configure CDN caching rules","Write performance tests"],technicalNotes:"Use Redis for distributed rate limiting. Implement cache warming strategy. Monitor cache hit rates.",dependencies:["INTENT-002"],effort:4},{id:"INTENT-006",title:"Setup Infrastructure and Deployment",component:"Infrastructure Components",goal:"Configure deployment pipeline and infrastructure",acceptanceCriteria:["Docker container configured and building","CI/CD pipeline running successfully","Monitoring and alerting configured","Staging environment deployed"],steps:["Create Dockerfile for application","Configure Docker Compose for local development","Set up CI/CD pipeline (GitHub Actions/Jenkins)","Configure staging environment","Set up monitoring (Prometheus/Grafana)","Configure alerting rules","Document deployment process"],technicalNotes:"Use multi-stage Docker builds. Implement health checks. Set up automated rollbacks.",dependencies:["INTENT-002","INTENT-003"],effort:8},{id:"INTENT-007",title:"Write Integration Tests and Documentation",component:"Backend Services",goal:"Create comprehensive tests and documentation",acceptanceCriteria:["Integration tests covering all workflows","API documentation complete","Test coverage >80%","Documentation reviewed and approved"],steps:["Write end-to-end integration tests","Test authentication flows","Test error scenarios","Generate API documentation (OpenAPI/Swagger)","Write user-facing documentation","Create troubleshooting guide","Run full test suite"],technicalNotes:"Use test fixtures for data setup. Mock external services. Document edge cases.",dependencies:["INTENT-003","INTENT-004","INTENT-005"],effort:4}];for(let p of d){let h=`---
786
786
  id: ${p.id}
787
787
  feature: ${this.workflowId}
@@ -809,7 +809,7 @@ ${p.acceptanceCriteria.map(y=>`- [ ] ${y}`).join(`
809
809
 
810
810
  ## Implementation Steps
811
811
 
812
- ${p.steps.map((y,T)=>`${T+1}. ${y}`).join(`
812
+ ${p.steps.map((y,w)=>`${w+1}. ${y}`).join(`
813
813
  `)}
814
814
 
815
815
  ## Technical Notes
@@ -826,7 +826,7 @@ ${p.effort}h
826
826
 
827
827
  ---
828
828
  *Generated by WorkflowEngine based on SPEC-001*
829
- `;await o.writeFile(r.join(l,`${p.id}.md`),h,"utf-8")}let f=d.reduce((p,h)=>p+h.effort,0),g={};for(let p of d)g[p.id]=p.dependencies;await o.writeFile(r.join(l,"dependency-graph.json"),JSON.stringify(g,null,2),"utf-8"),console.log(`[WorkflowEngine] Generated ${d.length} INTENT files`),console.log(`[WorkflowEngine] Total estimated effort: ${f}h`),console.log(`[WorkflowEngine] Validating INTENTS against SPEC at: ${n}`);let m=await Ca(l,n);t.validation_results.intents=m,m.passed?(console.log("[WorkflowEngine] INTENTS validation passed"),console.log(`[WorkflowEngine] Coverage: ${m.coverage_percentage}%`)):(console.log("[WorkflowEngine] INTENTS validation failed:",m.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${m.coverage_percentage}%`))}};var Na={idea:"idea-intake",prd:"prd-writer",spec:"spec-writer",intents:"intent-generator",complete:null};function Pa(e){switch(e){case"idea":return"capture and validate the initial feature concept";case"prd":return"create a comprehensive Product Requirements Document";case"spec":return"write a detailed technical specification";case"intents":return"generate implementation intent files";case"complete":return"finalize and validate all workflow artifacts";default:return"proceed with the next stage"}}function xa(e,t){let n=Na[t.current_stage],o=Pa(t.current_stage),r=`You are beginning a structured workflow for feature: ${e}
829
+ `;await o.writeFile(r.join(l,`${p.id}.md`),h,"utf-8")}let f=d.reduce((p,h)=>p+h.effort,0),g={};for(let p of d)g[p.id]=p.dependencies;await o.writeFile(r.join(l,"dependency-graph.json"),JSON.stringify(g,null,2),"utf-8"),console.log(`[WorkflowEngine] Generated ${d.length} INTENT files`),console.log(`[WorkflowEngine] Total estimated effort: ${f}h`),console.log(`[WorkflowEngine] Validating INTENTS against SPEC at: ${n}`);let m=await Da(l,n);t.validation_results.intents=m,m.passed?(console.log("[WorkflowEngine] INTENTS validation passed"),console.log(`[WorkflowEngine] Coverage: ${m.coverage_percentage}%`)):(console.log("[WorkflowEngine] INTENTS validation failed:",m.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${m.coverage_percentage}%`))}};var La={idea:"idea-intake",prd:"prd-writer",spec:"spec-writer",intents:"intent-generator",complete:null};function Ma(e){switch(e){case"idea":return"capture and validate the initial feature concept";case"prd":return"create a comprehensive Product Requirements Document";case"spec":return"write a detailed technical specification";case"intents":return"generate implementation intent files";case"complete":return"finalize and validate all workflow artifacts";default:return"proceed with the next stage"}}function $a(e,t){let n=La[t.current_stage],o=Ma(t.current_stage),r=`You are beginning a structured workflow for feature: ${e}
830
830
 
831
831
  `;return r+=`Current stage: ${t.current_stage}
832
832
  `,r+=`Status: ${t.status}
@@ -835,7 +835,7 @@ ${p.effort}h
835
835
 
836
836
  `,r+=`Use: Task(subagent_type="${n}", prompt="...")
837
837
  `):r+=`Next step: ${o}
838
- `,r}function Da(e,t){let n=Na[t.current_stage],o=Pa(t.current_stage),r=`Resuming workflow for feature: ${e}
838
+ `,r}function Fa(e,t){let n=La[t.current_stage],o=Ma(t.current_stage),r=`Resuming workflow for feature: ${e}
839
839
 
840
840
  `;return r+=`You were interrupted during: ${t.current_stage}
841
841
  `,r+=`Last update: ${t.updated_at}
@@ -848,7 +848,7 @@ ${p.effort}h
848
848
 
849
849
  `,r+=`Use: Task(subagent_type="${n}", prompt="...")
850
850
  `):r+=`Continue from where you left off: ${o}
851
- `,r}function yo(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function La(){v({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=yo(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(.+?)\s+--structured$/i),o=t.match(/^\/plan\s+continue$/i);if(n){let r=n[1].trim();try{await new ln(e.directory,r).start(r);let s=r.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),c=await me(e.directory,s);return c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:xa(r,c)}}:{continue:!0}}catch(i){return console.error("[Structured Workflow]",i),{continue:!0}}}if(o)try{let r=await _a(e.directory);if(r.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature} --structured` to start a new workflow."}};let i=r[0],s=await me(e.directory,i);return s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Da(s.feature_name,s)}}:{continue:!0}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}return{continue:!0}}}),v({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=yo(e);if(!t)return{continue:!0};let n=Ar(t),o=br(n);if(o.length===0)return{continue:!0};let r=o.some(a=>a.type==="ultrawork"),i=o.some(a=>a.type==="ultrathink"),s=o.some(a=>a.type==="search"),c=o.some(a=>a.type==="analyze");return r?(zr(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ti}}):i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ni}}:s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:oi}}:c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ri}}:{continue:!0}}}),v({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=jr().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),v({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Kr(),n=e.sessionId||"default",o={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},r=t.processChatParams(n,o);return r.requested&&r.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),v({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=yo(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await _i({prompt:t,directory:e.directory,sessionId:e.sessionId}),await vi({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var Ve=require("fs"),Ue=require("path"),Ma=require("os");function up(e,t){let n=(0,Ue.join)((0,Ma.homedir)(),".claude"),o=[];e&&(o.push((0,Ue.join)(n,"sessions",e,"todos.json")),o.push((0,Ue.join)(n,"todos",`${e}.json`))),t&&(o.push((0,Ue.join)(t,".olympus","todos.json")),o.push((0,Ue.join)(t,".claude","todos.json")));let r=(0,Ue.join)(n,"todos");if((0,Ve.existsSync)(r))try{let i=(0,Ve.readdirSync)(r);for(let s of i)s.endsWith(".json")&&o.push((0,Ue.join)(r,s))}catch{}return o}function dp(e){try{let t=(0,Ve.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(o=>o&&typeof o.content=="string"&&typeof o.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(o=>{let r=o;return r&&typeof r.content=="string"&&typeof r.status=="string"}):[]}catch{return[]}}function fp(e){return e.status!=="completed"&&e.status!=="cancelled"}async function At(e,t){let n=up(e,t),o=new Set,r=[],i=[];for(let s of n){if(!(0,Ve.existsSync)(s))continue;let c=dp(s);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),fp(a)&&i.push(a))}}return{count:i.length,todos:i,total:r.length}}function $a(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var un=require("path");function Fa(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}var Ua=500;function ja(e){let t=et((0,un.join)(Ne(),"user-preferences.json"),null),n=et((0,un.join)(yt(e),"patterns.json"),null),o=et((0,un.join)(Ne(),"agent-performance.json"),{}),r=[];t&&pp(t)&&r.push(mp(t)),n&&n.conventions.length>0&&r.push(gp(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(hp(t.recurring_corrections.slice(0,5)));let i=Object.values(o).filter(a=>a.weak_areas.length>0);i.length>0&&r.push(kp(i));let s=yp(o);if(s&&r.push(s),r.length===0)return"";let c=`<learned-context>
851
+ `,r}function To(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function Ua(){R({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=To(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(.+?)\s+--structured$/i),o=t.match(/^\/plan\s+continue$/i);if(n){let r=n[1].trim();try{await new dn(e.directory,r).start(r);let s=r.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),c=await ge(e.directory,s);return c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:$a(r,c)}}:{continue:!0}}catch(i){return console.error("[Structured Workflow]",i),{continue:!0}}}if(o)try{let r=await Ia(e.directory);if(r.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature} --structured` to start a new workflow."}};let i=r[0],s=await ge(e.directory,i);return s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Fa(s.feature_name,s)}}:{continue:!0}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}return{continue:!0}}}),R({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=To(e);if(!t)return{continue:!0};let n=Pr(t),o=xr(n);if(o.length===0)return{continue:!0};let r=o.some(a=>a.type==="ultrawork"),i=o.some(a=>a.type==="ultrathink"),s=o.some(a=>a.type==="search"),c=o.some(a=>a.type==="analyze");return r?(ei(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ii}}):i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:si}}:s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ai}}:c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ci}}:{continue:!0}}}),R({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=Br().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),R({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Qr(),n=e.sessionId||"default",o={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},r=t.processChatParams(n,o);return r.requested&&r.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),R({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=To(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Ii({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Ci({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var Ke=require("fs"),je=require("path"),ja=require("os");function kp(e,t){let n=(0,je.join)((0,ja.homedir)(),".claude"),o=[];e&&(o.push((0,je.join)(n,"sessions",e,"todos.json")),o.push((0,je.join)(n,"todos",`${e}.json`))),t&&(o.push((0,je.join)(t,".olympus","todos.json")),o.push((0,je.join)(t,".claude","todos.json")));let r=(0,je.join)(n,"todos");if((0,Ke.existsSync)(r))try{let i=(0,Ke.readdirSync)(r);for(let s of i)s.endsWith(".json")&&o.push((0,je.join)(r,s))}catch{}return o}function yp(e){try{let t=(0,Ke.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(o=>o&&typeof o.content=="string"&&typeof o.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(o=>{let r=o;return r&&typeof r.content=="string"&&typeof r.status=="string"}):[]}catch{return[]}}function Ep(e){return e.status!=="completed"&&e.status!=="cancelled"}async function At(e,t){let n=kp(e,t),o=new Set,r=[],i=[];for(let s of n){if(!(0,Ke.existsSync)(s))continue;let c=yp(s);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),Ep(a)&&i.push(a))}}return{count:i.length,todos:i,total:r.length}}function Ha(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var fn=require("path");function Wa(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}var Ga=500;function Ba(e){let t=tt((0,fn.join)(Pe(),"user-preferences.json"),null),n=tt((0,fn.join)(St(e),"patterns.json"),null),o=tt((0,fn.join)(Pe(),"agent-performance.json"),{}),r=[];t&&Sp(t)&&r.push(Tp(t)),n&&n.conventions.length>0&&r.push(wp(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(_p(t.recurring_corrections.slice(0,5)));let i=Object.values(o).filter(a=>a.weak_areas.length>0);i.length>0&&r.push(Op(i));let s=vp(o);if(s&&r.push(s),r.length===0)return"";let c=`<learned-context>
852
852
 
853
853
  ${r.join(`
854
854
 
@@ -858,21 +858,21 @@ ${r.join(`
858
858
 
859
859
  ---
860
860
 
861
- `;return c.length>Ua*4?c.substring(0,Ua*4)+`
861
+ `;return c.length>Ga*4?c.substring(0,Ga*4)+`
862
862
  ...</learned-context>
863
863
 
864
864
  ---
865
865
 
866
- `:c}function pp(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function mp(e){let t=["## User Preferences"];e.verbosity!=="unknown"&&t.push(`- Verbosity: ${e.verbosity}`),e.autonomy!=="unknown"&&t.push(`- Autonomy: ${e.autonomy}`);for(let n of e.explicit_rules.slice(0,5))t.push(`- ${n}`);return t.join(`
867
- `)}function gp(e){let t=["## Project Conventions"];for(let n of e.conventions.slice(0,5))t.push(`- ${n}`);return e.tech_stack.length>0&&t.push(`- Tech: ${e.tech_stack.join(", ")}`),t.join(`
868
- `)}function hp(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
869
- `)}function kp(e){let t=["## Agent Notes"];for(let n of e.slice(0,3))t.push(`- ${n.agent_name}: struggles with ${n.weak_areas.join(", ")}`);return t.join(`
870
- `)}function yp(e){let t=Object.values(e).filter(c=>c.token_efficiency&&Fa(c)).sort((c,a)=>{let l=c.token_efficiency?.efficiency_score??0;return(a.token_efficiency?.efficiency_score??0)-l});if(t.length===0)return"";let n=[];n.push("<olympus-efficiency>"),n.push("AGENT EFFICIENCY (success%/avg tokens):");for(let c of t.slice(0,3)){let a=Math.round(c.success_rate*100),l=c.token_efficiency.avg_tokens_per_success,u=l>=1e3?`${(l/1e3).toFixed(1)}k`:`${Math.round(l)}`,f=c.success_rate>=.9&&c.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${c.agent_name}: ${a}%/${u}${f}`)}let o=Ge(),r=o>=1e3?`${(o/1e3).toFixed(0)}k`:o.toString(),i=Math.round(o*1.5),s=i>=1e3?`${(i/1e3).toFixed(0)}k`:i.toString();return n.push(""),n.push(`SESSION BUDGET: ~${r} baseline | warn at ${s}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
871
- `)}function Ha(e){if(e.length===0)return"";let t=["## Agent Discoveries"];t.push(""),t.push("These insights were discovered during previous work:"),t.push("");for(let n of e.slice(0,5))t.push(`- **${n.category}**: ${n.summary}`),t.push(` ${n.details.substring(0,200)}`);return t.join(`
872
- `)}var dn=require("path"),Ke=require("fs"),Ep=require("crypto");function Sp(e){let t=(0,dn.join)(Ne(),"discoveries.jsonl"),n=yt(e),o=(0,dn.join)(n,"discoveries.jsonl"),r=Wa(t),i=Wa(o),s=[...r,...i],c={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0};for(let l of s)c[l.category]++;let a=[...s].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:i,global_discoveries:r,total_discoveries:s.length,categories:c,most_useful:a.slice(0,5)}}function Ga(e,t=10){let n=Sp(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,s=o.filter(c=>c.expires_at?new Date(c.expires_at)>r:!0).map(c=>{let a=(r.getTime()-new Date(c.timestamp).getTime())/864e5,l=Math.max(.1,1-a/90),u=(c.verification_count+1)*l*c.confidence;return{discovery:c,score:u}});return s.sort((c,a)=>a.score-c.score),s.slice(0,t).map(c=>c.discovery)}function Wa(e){if(!(0,Ke.existsSync)(e))return[];try{return(0,Ke.readFileSync)(e,"utf-8").split(`
873
- `).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function Ba(){v({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=ja(e.directory),n=Ga(e.directory,5),o=Ha(n),r=t+(o?`
866
+ `:c}function Sp(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function Tp(e){let t=["## User Preferences"];e.verbosity!=="unknown"&&t.push(`- Verbosity: ${e.verbosity}`),e.autonomy!=="unknown"&&t.push(`- Autonomy: ${e.autonomy}`);for(let n of e.explicit_rules.slice(0,5))t.push(`- ${n}`);return t.join(`
867
+ `)}function wp(e){let t=["## Project Conventions"];for(let n of e.conventions.slice(0,5))t.push(`- ${n}`);return e.tech_stack.length>0&&t.push(`- Tech: ${e.tech_stack.join(", ")}`),t.join(`
868
+ `)}function _p(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
869
+ `)}function Op(e){let t=["## Agent Notes"];for(let n of e.slice(0,3))t.push(`- ${n.agent_name}: struggles with ${n.weak_areas.join(", ")}`);return t.join(`
870
+ `)}function vp(e){let t=Object.values(e).filter(c=>c.token_efficiency&&Wa(c)).sort((c,a)=>{let l=c.token_efficiency?.efficiency_score??0;return(a.token_efficiency?.efficiency_score??0)-l});if(t.length===0)return"";let n=[];n.push("<olympus-efficiency>"),n.push("AGENT EFFICIENCY (success%/avg tokens):");for(let c of t.slice(0,3)){let a=Math.round(c.success_rate*100),l=c.token_efficiency.avg_tokens_per_success,u=l>=1e3?`${(l/1e3).toFixed(1)}k`:`${Math.round(l)}`,f=c.success_rate>=.9&&c.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${c.agent_name}: ${a}%/${u}${f}`)}let o=Be(),r=o>=1e3?`${(o/1e3).toFixed(0)}k`:o.toString(),i=Math.round(o*1.5),s=i>=1e3?`${(i/1e3).toFixed(0)}k`:i.toString();return n.push(""),n.push(`SESSION BUDGET: ~${r} baseline | warn at ${s}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
871
+ `)}function qa(e){if(e.length===0)return"";let t=["## Agent Discoveries"];t.push(""),t.push("These insights were discovered during previous work:"),t.push("");for(let n of e.slice(0,5))t.push(`- **${n.category}**: ${n.summary}`),t.push(` ${n.details.substring(0,200)}`);return t.join(`
872
+ `)}var pn=require("path"),Je=require("fs"),Rp=require("crypto");function Ip(e){let t=(0,pn.join)(Pe(),"discoveries.jsonl"),n=St(e),o=(0,pn.join)(n,"discoveries.jsonl"),r=Ya(t),i=Ya(o),s=[...r,...i],c={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0};for(let l of s)c[l.category]++;let a=[...s].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:i,global_discoveries:r,total_discoveries:s.length,categories:c,most_useful:a.slice(0,5)}}function Va(e,t=10){let n=Ip(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,s=o.filter(c=>c.expires_at?new Date(c.expires_at)>r:!0).map(c=>{let a=(r.getTime()-new Date(c.timestamp).getTime())/864e5,l=Math.max(.1,1-a/90),u=(c.verification_count+1)*l*c.confidence;return{discovery:c,score:u}});return s.sort((c,a)=>a.score-c.score),s.slice(0,t).map(c=>c.discovery)}function Ya(e){if(!(0,Je.existsSync)(e))return[];try{return(0,Je.readFileSync)(e,"utf-8").split(`
873
+ `).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function Ka(){R({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Ba(e.directory),n=Va(e.directory,5),o=qa(n),r=t+(o?`
874
874
 
875
- `+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),v({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[];try{let s=te(n,t);s.token_budget||(yi(s,n),J(n,s))}catch(s){console.error("[Olympus Learning] Failed to initialize token budget:",s)}let r=We(n);r?.active&&o.push(`<session-restore>
875
+ `+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),R({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[];try{let s=ne(n,t);s.token_budget||(wi(s,n),z(n,s))}catch(s){console.error("[Olympus Learning] Failed to initialize token budget:",s)}let r=Ge(n);r?.active&&o.push(`<session-restore>
876
876
 
877
877
  [ULTRAWORK MODE RESTORED]
878
878
 
@@ -897,7 +897,7 @@ Please continue working on these tasks.
897
897
  ---
898
898
 
899
899
  `),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
900
- `)}}:{continue:!0}}})}var lt=require("fs"),Re=require("path"),Io=require("os");var ne=require("fs"),je=require("path"),qa=require("os");function Eo(e){let t=(0,je.join)(e,".olympus");return(0,je.join)(t,"ascent-state.json")}function Tp(e){let t=(0,je.join)(e,".olympus");(0,ne.existsSync)(t)||(0,ne.mkdirSync)(t,{recursive:!0})}function bt(e){let t=Eo(e);if(!(0,ne.existsSync)(t))return null;try{let n=(0,ne.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function wp(e,t){try{Tp(e);let n=Eo(e);return(0,ne.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function fn(e){let t=Eo(e);if(!(0,ne.existsSync)(t))return!0;try{return(0,ne.unlinkSync)(t),!0}catch{return!1}}function Ya(e){let t=bt(e);return!t||!t.active?null:(t.iteration+=1,wp(e,t)?t:null)}function Va(e,t){let n=(0,je.join)((0,qa.homedir)(),".claude"),o=[(0,je.join)(n,"sessions",e,"transcript.md"),(0,je.join)(n,"sessions",e,"messages.json"),(0,je.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,ne.existsSync)(r))try{let i=(0,ne.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${_p(t)}\\s*</promise>`,"is").test(i))return!0}catch{continue}return!1}function _p(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ae=require("fs"),So=require("path"),Op=3;function To(e){return(0,So.join)(e,".olympus","ascent-verification.json")}function Nt(e){let t=To(e);if(!(0,ae.existsSync)(t))return null;try{return JSON.parse((0,ae.readFileSync)(t,"utf-8"))}catch{return null}}function Ka(e,t){let n=To(e),o=(0,So.join)(e,".olympus");if(!(0,ae.existsSync)(o))try{(0,ae.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,ae.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function Ct(e){let t=To(e);if((0,ae.existsSync)(t))try{return(0,ae.unlinkSync)(t),!0}catch{return!1}return!0}function Ja(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:Op,requested_at:new Date().toISOString(),original_task:n};return Ka(e,o),o}function za(e,t,n){let o=Nt(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(Ct(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(Ct(e),{...o,pending:!1}):(Ka(e,o),o)):null}function wo(e){return`<ascent-verification>
900
+ `)}}:{continue:!0}}})}var ut=require("fs"),Ie=require("path"),Ao=require("os");var oe=require("fs"),He=require("path"),Ja=require("os");function wo(e){let t=(0,He.join)(e,".olympus");return(0,He.join)(t,"ascent-state.json")}function bp(e){let t=(0,He.join)(e,".olympus");(0,oe.existsSync)(t)||(0,oe.mkdirSync)(t,{recursive:!0})}function Nt(e){let t=wo(e);if(!(0,oe.existsSync)(t))return null;try{let n=(0,oe.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Cp(e,t){try{bp(e);let n=wo(e);return(0,oe.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function mn(e){let t=wo(e);if(!(0,oe.existsSync)(t))return!0;try{return(0,oe.unlinkSync)(t),!0}catch{return!1}}function za(e){let t=Nt(e);return!t||!t.active?null:(t.iteration+=1,Cp(e,t)?t:null)}function Xa(e,t){let n=(0,He.join)((0,Ja.homedir)(),".claude"),o=[(0,He.join)(n,"sessions",e,"transcript.md"),(0,He.join)(n,"sessions",e,"messages.json"),(0,He.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,oe.existsSync)(r))try{let i=(0,oe.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${Ap(t)}\\s*</promise>`,"is").test(i))return!0}catch{continue}return!1}function Ap(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ce=require("fs"),_o=require("path"),Np=3;function Oo(e){return(0,_o.join)(e,".olympus","ascent-verification.json")}function xt(e){let t=Oo(e);if(!(0,ce.existsSync)(t))return null;try{return JSON.parse((0,ce.readFileSync)(t,"utf-8"))}catch{return null}}function Qa(e,t){let n=Oo(e),o=(0,_o.join)(e,".olympus");if(!(0,ce.existsSync)(o))try{(0,ce.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,ce.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function Pt(e){let t=Oo(e);if((0,ce.existsSync)(t))try{return(0,ce.unlinkSync)(t),!0}catch{return!1}return!0}function Za(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:Np,requested_at:new Date().toISOString(),original_task:n};return Qa(e,o),o}function ec(e,t,n){let o=xt(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(Pt(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(Pt(e),{...o,pending:!1}):(Qa(e,o),o)):null}function vo(e){return`<ascent-verification>
901
901
 
902
902
  [ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
903
903
 
@@ -937,7 +937,7 @@ DO NOT output the completion promise again until Oracle approves.
937
937
 
938
938
  ---
939
939
 
940
- `}function Xa(e){return`<ascent-continuation-after-rejection>
940
+ `}function tc(e){return`<ascent-continuation-after-rejection>
941
941
 
942
942
  [ORACLE REJECTED - Continue Working]
943
943
 
@@ -962,7 +962,7 @@ Continue working now.
962
962
 
963
963
  ---
964
964
 
965
- `}function Qa(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Za(e){let t=[/oracle.*?(rejected|found issues|not complete|incomplete)/i,/issues? (found|identified|detected)/i,/not yet complete/i,/missing.*?(implementation|feature|test)/i,/bug.*?(found|detected|identified)/i,/error.*?(found|detected|identified)/i];for(let n of t)if(n.test(e)){let o=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:o?o[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var j=require("fs"),at=require("path"),_o=require("os");function Oo(e){let t=e||process.cwd(),n=(0,at.join)(t,".olympus");return(0,at.join)(n,"olympus-state.json")}function vo(){return(0,at.join)((0,_o.homedir)(),".claude","olympus-state.json")}function vp(e){let t=e||process.cwd(),n=(0,at.join)(t,".olympus");(0,j.existsSync)(n)||(0,j.mkdirSync)(n,{recursive:!0})}function Rp(){let e=(0,at.join)((0,_o.homedir)(),".claude");(0,j.existsSync)(e)||(0,j.mkdirSync)(e,{recursive:!0})}function ct(e){let t=Oo(e);if((0,j.existsSync)(t))try{let o=(0,j.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=vo();if((0,j.existsSync)(n))try{let o=(0,j.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function ec(e,t){try{vp(t);let n=Oo(t);(0,j.writeFileSync)(n,JSON.stringify(e,null,2)),Rp();let o=vo();return(0,j.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Ro(e){let t=Oo(e);if((0,j.existsSync)(t))try{(0,j.unlinkSync)(t)}catch{}let n=vo();if((0,j.existsSync)(n))try{return(0,j.unlinkSync)(n),!0}catch{return!1}return!0}function tc(e){let t=ct(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),ec(t,e)?t:null)}function nc(e){let t=ct(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),ec(t,e))}function oc(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
965
+ `}function nc(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function oc(e){let t=[/oracle.*?(rejected|found issues|not complete|incomplete)/i,/issues? (found|identified|detected)/i,/not yet complete/i,/missing.*?(implementation|feature|test)/i,/bug.*?(found|detected|identified)/i,/error.*?(found|detected|identified)/i];for(let n of t)if(n.test(e)){let o=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:o?o[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var W=require("fs"),ct=require("path"),Ro=require("os");function Io(e){let t=e||process.cwd(),n=(0,ct.join)(t,".olympus");return(0,ct.join)(n,"olympus-state.json")}function bo(){return(0,ct.join)((0,Ro.homedir)(),".claude","olympus-state.json")}function Pp(e){let t=e||process.cwd(),n=(0,ct.join)(t,".olympus");(0,W.existsSync)(n)||(0,W.mkdirSync)(n,{recursive:!0})}function xp(){let e=(0,ct.join)((0,Ro.homedir)(),".claude");(0,W.existsSync)(e)||(0,W.mkdirSync)(e,{recursive:!0})}function lt(e){let t=Io(e);if((0,W.existsSync)(t))try{let o=(0,W.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=bo();if((0,W.existsSync)(n))try{let o=(0,W.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function rc(e,t){try{Pp(t);let n=Io(t);(0,W.writeFileSync)(n,JSON.stringify(e,null,2)),xp();let o=bo();return(0,W.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Co(e){let t=Io(e);if((0,W.existsSync)(t))try{(0,W.unlinkSync)(t)}catch{}let n=bo();if((0,W.existsSync)(n))try{return(0,W.unlinkSync)(n),!0}catch{return!1}return!0}function ic(e){let t=lt(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),rc(t,e)?t:null)}function sc(e){let t=lt(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),rc(t,e))}function ac(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
966
966
 
967
967
  **ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
968
968
 
@@ -984,7 +984,7 @@ Original task: ${e.original_prompt}
984
984
 
985
985
  ---
986
986
 
987
- `}function rc(e){let t=(0,Re.join)((0,Io.homedir)(),".claude"),n=[(0,Re.join)(t,"sessions",e,"transcript.md"),(0,Re.join)(t,"sessions",e,"messages.json"),(0,Re.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,lt.existsSync)(o))try{let r=(0,lt.readFileSync)(o,"utf-8");if(Qa(r))return!0}catch{continue}return!1}function Ip(e){let t=(0,Re.join)((0,Io.homedir)(),".claude"),n=[(0,Re.join)(t,"sessions",e,"transcript.md"),(0,Re.join)(t,"sessions",e,"messages.json"),(0,Re.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,lt.existsSync)(o))try{let r=(0,lt.readFileSync)(o,"utf-8"),i=Za(r);if(i.rejected)return i}catch{continue}return{rejected:!1,feedback:""}}async function Ap(e,t){let n=t||process.cwd(),o=bt(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=Nt(n);if(r?.pending){if(e){if(rc(e))return Ct(n),fn(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=Ip(e);if(l.rejected){za(n,!1,l.feedback);let u=Nt(n);if(u)return{shouldBlock:!0,message:Xa(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:wo(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(Va(e||"",o.completion_promise)){Ja(n,o.completion_promise,o.prompt);let a=Nt(n);return a?{shouldBlock:!0,message:wo(a),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(fn(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${o.iteration} iteration(s). Great work!`,mode:"none"})}if(o.iteration>=o.max_iterations)return fn(n),Ct(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let s=Ya(n);return s?{shouldBlock:!0,message:`<ascent-continuation>
987
+ `}function cc(e){let t=(0,Ie.join)((0,Ao.homedir)(),".claude"),n=[(0,Ie.join)(t,"sessions",e,"transcript.md"),(0,Ie.join)(t,"sessions",e,"messages.json"),(0,Ie.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,ut.existsSync)(o))try{let r=(0,ut.readFileSync)(o,"utf-8");if(nc(r))return!0}catch{continue}return!1}function Dp(e){let t=(0,Ie.join)((0,Ao.homedir)(),".claude"),n=[(0,Ie.join)(t,"sessions",e,"transcript.md"),(0,Ie.join)(t,"sessions",e,"messages.json"),(0,Ie.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,ut.existsSync)(o))try{let r=(0,ut.readFileSync)(o,"utf-8"),i=oc(r);if(i.rejected)return i}catch{continue}return{rejected:!1,feedback:""}}async function Lp(e,t){let n=t||process.cwd(),o=Nt(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=xt(n);if(r?.pending){if(e){if(cc(e))return Pt(n),mn(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=Dp(e);if(l.rejected){ec(n,!1,l.feedback);let u=xt(n);if(u)return{shouldBlock:!0,message:tc(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:vo(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(Xa(e||"",o.completion_promise)){Za(n,o.completion_promise,o.prompt);let a=xt(n);return a?{shouldBlock:!0,message:vo(a),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(mn(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${o.iteration} iteration(s). Great work!`,mode:"none"})}if(o.iteration>=o.max_iterations)return mn(n),Pt(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let s=za(n);return s?{shouldBlock:!0,message:`<ascent-continuation>
988
988
 
989
989
  [ASCENT LOOP - ITERATION ${s.iteration}/${s.max_iterations}]
990
990
 
@@ -1003,7 +1003,7 @@ ${s.prompt?`Original task: ${s.prompt}`:""}
1003
1003
 
1004
1004
  ---
1005
1005
 
1006
- `,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function bp(e,t,n){let o=We(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return Xr(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=Qr(t);return r?{shouldBlock:!0,message:Zr(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Cp(e,t,n){let o=ct(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return Ro(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!o.oracle_approved&&o.requires_oracle_verification)return e&&rc(e)?(nc(t),Ro(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
1006
+ `,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function Mp(e,t,n){let o=Ge(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return ti(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=ni(t);return r?{shouldBlock:!0,message:oi(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function $p(e,t,n){let o=lt(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return Co(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!o.oracle_approved&&o.requires_oracle_verification)return e&&cc(e)?(sc(t),Co(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
1007
1007
 
1008
1008
  [OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
1009
1009
 
@@ -1026,11 +1026,11 @@ DO NOT stop until Oracle has approved.
1026
1026
 
1027
1027
  ---
1028
1028
 
1029
- `,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=tc(t);return r?{shouldBlock:!0,message:oc(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Np(e,t){let n=await At(e,t);if(n.count===0)return null;let o=$a(n),r=o?`
1029
+ `,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=ic(t);return r?{shouldBlock:!0,message:ac(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Fp(e,t){let n=await At(e,t);if(n.count===0)return null;let o=Ha(n),r=o?`
1030
1030
 
1031
1031
  Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
1032
1032
 
1033
- ${ii}
1033
+ ${li}
1034
1034
 
1035
1035
  [Status: ${n.count} of ${n.total} tasks remaining]${r}
1036
1036
 
@@ -1038,20 +1038,20 @@ ${ii}
1038
1038
 
1039
1039
  ---
1040
1040
 
1041
- `,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function ic(e,t){let n=t||process.cwd(),r=(await At(e,n)).count>0,i=await Ap(e,n);if(i?.shouldBlock)return i;let s=await bp(e,n,r);if(s?.shouldBlock)return s;let c=await Cp(e,n,r);if(c?.shouldBlock)return c;if(r){let a=await Np(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function sc(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var ut=require("fs"),Ao=require("path"),ac=require("os");var cc=require("crypto");function Pp(){let e=(0,Ao.join)((0,ac.homedir)(),".claude","todos");if(!(0,ut.existsSync)(e))return 0;let t=0;try{let n=(0,ut.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,ut.readFileSync)((0,Ao.join)(e,o),"utf-8"),i=JSON.parse(r);Array.isArray(i)&&(t+=i.filter(s=>s.status!=="completed"&&s.status!=="cancelled").length)}catch{}}catch{}return t}async function lc(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=te(t,n),r=Pp();if(r>0&&o.pending_completion){let i={id:(0,cc.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:t,event_type:"cancellation",original_task:o.pending_completion.task_description,agent_used:o.pending_completion.agent_used,user_message:`[Stopped with ${r} incomplete todos]`,feedback_category:"rejection",confidence:.7};Pe(i)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},J(t,o)}function uc(){v({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await ic(t,n),r=sc(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),v({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await lc({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var Fo=require("fs"),Uo=require("os"),xt=require("path");var ge=require("fs"),ie=require("path");var bo=require("path"),dc=require("os"),xp=(0,bo.join)((0,dc.homedir)(),".olympus"),pn=(0,bo.join)(xp,"rules-injector"),fc=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],pc=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],mc=[".github/copilot-instructions.md"],gc=/\.instructions\.md$/,hc=".claude/rules",kc=[".md",".mdc"],Co=["read","write","edit","multiedit"];function Dp(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function Lp(e,t){return Dp(t)?gc.test(e):kc.some(n=>e.endsWith(n))}function xo(e){let t;try{t=(0,ge.statSync)(e).isDirectory()?e:(0,ie.dirname)(e)}catch{t=(0,ie.dirname)(e)}for(;;){for(let o of fc){let r=(0,ie.join)(t,o);if((0,ge.existsSync)(r))return t}let n=(0,ie.dirname)(t);if(n===t)return null;t=n}}function Po(e,t){if((0,ge.existsSync)(e))try{let n=(0,ge.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,ie.join)(e,o.name);o.isDirectory()?Po(r,t):o.isFile()&&Lp(o.name,e)&&t.push(r)}}catch{}}function No(e){try{return(0,ge.realpathSync)(e)}catch{return e}}function Do(e,t,n){let o=[],r=new Set,i=(0,ie.dirname)(n),s=0;for(;;){for(let[u,d]of pc){let f=(0,ie.join)(i,u,d),g=[];Po(f,g);for(let m of g){let p=No(m);r.has(p)||(r.add(p),o.push({path:m,realPath:p,isGlobal:!1,distance:s}))}}if(e&&i===e)break;let l=(0,ie.dirname)(i);if(l===i)break;i=l,s++}if(e)for(let l of mc){let u=(0,ie.join)(e,l);if((0,ge.existsSync)(u))try{if((0,ge.statSync)(u).isFile()){let f=No(u);r.has(f)||(r.add(f),o.push({path:u,realPath:f,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let c=(0,ie.join)(t,hc),a=[];Po(c,a);for(let l of a){let u=No(l);r.has(u)||(r.add(u),o.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return o.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),o}var yc=require("crypto"),Ec=require("path");function Mp(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function Lo(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let o=e.globs;if(!o)return{applies:!1};let r=Array.isArray(o)?o:[o];if(r.length===0)return{applies:!1};let s=(n?(0,Ec.relative)(n,t):t).replace(/\\/g,"/");for(let c of r)if(Mp(c,s))return{applies:!0,reason:`glob: ${c}`};return{applies:!1}}function Sc(e,t){return t.has(e)}function Tc(e){return(0,yc.createHash)("sha256").update(e).digest("hex").slice(0,16)}function wc(e,t){return t.has(e)}function Mo(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let o=n[1],r=n[2];try{return{metadata:$p(o),body:r}}catch{return{metadata:{},body:e}}}function $p(e){let t=e.split(`
1042
- `),n={},o=0;for(;o<t.length;){let r=t[o],i=r.indexOf(":");if(i===-1){o++;continue}let s=r.slice(0,i).trim(),c=r.slice(i+1).trim();if(s==="description")n.description=Pt(c);else if(s==="alwaysApply")n.alwaysApply=c==="true";else if(s==="globs"||s==="paths"||s==="applyTo"){let{value:a,consumed:l}=Fp(c,t,o);n.globs=jp(n.globs,a),o+=l;continue}o++}return n}function Pt(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function Fp(e,t,n){if(e.startsWith("["))return{value:Up(e),consumed:1};if(!e||e===""){let r=[],i=1;for(let s=n+1;s<t.length;s++){let c=t[s],a=c.match(/^\s+-\s*(.*)$/);if(a){let l=Pt(a[1].trim());l&&r.push(l),i++}else if(c.trim()==="")i++;else break}if(r.length>0)return{value:r,consumed:i}}let o=Pt(e);return o.includes(",")?{value:o.split(",").map(i=>i.trim()).filter(i=>i.length>0),consumed:1}:{value:o,consumed:1}}function Up(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,i="";for(let c=0;c<t.length;c++){let a=t[c];if(!r&&(a==='"'||a==="'"))r=!0,i=a;else if(r&&a===i)r=!1,i="";else if(!r&&a===","){let l=o.trim();l&&n.push(Pt(l)),o=""}else o+=a}let s=o.trim();return s&&n.push(Pt(s)),n}function jp(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var ce=require("fs"),_c=require("path");function $o(e){return(0,_c.join)(pn,`${e}.json`)}function Oc(e){let t=$o(e);if(!(0,ce.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,ce.readFileSync)(t,"utf-8"),o=JSON.parse(n);return{contentHashes:new Set(o.injectedHashes),realPaths:new Set(o.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function vc(e,t){(0,ce.existsSync)(pn)||(0,ce.mkdirSync)(pn,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,ce.writeFileSync)($o(e),JSON.stringify(n,null,2))}function Rc(e){let t=$o(e);(0,ce.existsSync)(t)&&(0,ce.unlinkSync)(t)}function Ic(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Oc(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,xt.resolve)(e,s):null}function r(s,c){let a=o(s);if(!a)return[];let l=xo(a),u=n(c),d=(0,Uo.homedir)(),f=Do(l,d,a),g=[];for(let m of f)if(!Sc(m.realPath,u.realPaths))try{let p=(0,Fo.readFileSync)(m.path,"utf-8"),{metadata:h,body:y}=Mo(p),T;if(m.isSingleFile)T="copilot-instructions (always apply)";else{let D=Lo(h,a,l);if(!D.applies)continue;T=D.reason??"matched"}let k=Tc(y);if(wc(k,u.contentHashes))continue;let A=l?(0,xt.relative)(l,m.path):m.path;g.push({relativePath:A,matchReason:T,content:y,distance:m.distance}),u.realPaths.add(m.realPath),u.contentHashes.add(k)}catch{}return g.length>0&&(g.sort((m,p)=>m.distance-p.distance),vc(c,u)),g}function i(s){if(s.length===0)return"";let c="";for(let a of s)c+=`
1041
+ `,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function lc(e,t){let n=t||process.cwd(),r=(await At(e,n)).count>0,i=await Lp(e,n);if(i?.shouldBlock)return i;let s=await Mp(e,n,r);if(s?.shouldBlock)return s;let c=await $p(e,n,r);if(c?.shouldBlock)return c;if(r){let a=await Fp(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function uc(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var dt=require("fs"),No=require("path"),dc=require("os");var fc=require("crypto");function Up(){let e=(0,No.join)((0,dc.homedir)(),".claude","todos");if(!(0,dt.existsSync)(e))return 0;let t=0;try{let n=(0,dt.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,dt.readFileSync)((0,No.join)(e,o),"utf-8"),i=JSON.parse(r);Array.isArray(i)&&(t+=i.filter(s=>s.status!=="completed"&&s.status!=="cancelled").length)}catch{}}catch{}return t}async function pc(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=ne(t,n),r=Up();if(r>0&&o.pending_completion){let i={id:(0,fc.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:t,event_type:"cancellation",original_task:o.pending_completion.task_description,agent_used:o.pending_completion.agent_used,user_message:`[Stopped with ${r} incomplete todos]`,feedback_category:"rejection",confidence:.7};xe(i)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},z(t,o)}function mc(){R({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await lc(t,n),r=uc(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),R({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await pc({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var Ho=require("fs"),Wo=require("os"),Lt=require("path");var he=require("fs"),se=require("path");var Po=require("path"),gc=require("os"),jp=(0,Po.join)((0,gc.homedir)(),".olympus"),gn=(0,Po.join)(jp,"rules-injector"),hc=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],kc=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],yc=[".github/copilot-instructions.md"],Ec=/\.instructions\.md$/,Sc=".claude/rules",Tc=[".md",".mdc"],xo=["read","write","edit","multiedit"];function Hp(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function Wp(e,t){return Hp(t)?Ec.test(e):Tc.some(n=>e.endsWith(n))}function Mo(e){let t;try{t=(0,he.statSync)(e).isDirectory()?e:(0,se.dirname)(e)}catch{t=(0,se.dirname)(e)}for(;;){for(let o of hc){let r=(0,se.join)(t,o);if((0,he.existsSync)(r))return t}let n=(0,se.dirname)(t);if(n===t)return null;t=n}}function Lo(e,t){if((0,he.existsSync)(e))try{let n=(0,he.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,se.join)(e,o.name);o.isDirectory()?Lo(r,t):o.isFile()&&Wp(o.name,e)&&t.push(r)}}catch{}}function Do(e){try{return(0,he.realpathSync)(e)}catch{return e}}function $o(e,t,n){let o=[],r=new Set,i=(0,se.dirname)(n),s=0;for(;;){for(let[u,d]of kc){let f=(0,se.join)(i,u,d),g=[];Lo(f,g);for(let m of g){let p=Do(m);r.has(p)||(r.add(p),o.push({path:m,realPath:p,isGlobal:!1,distance:s}))}}if(e&&i===e)break;let l=(0,se.dirname)(i);if(l===i)break;i=l,s++}if(e)for(let l of yc){let u=(0,se.join)(e,l);if((0,he.existsSync)(u))try{if((0,he.statSync)(u).isFile()){let f=Do(u);r.has(f)||(r.add(f),o.push({path:u,realPath:f,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let c=(0,se.join)(t,Sc),a=[];Lo(c,a);for(let l of a){let u=Do(l);r.has(u)||(r.add(u),o.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return o.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),o}var wc=require("crypto"),_c=require("path");function Gp(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function Fo(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let o=e.globs;if(!o)return{applies:!1};let r=Array.isArray(o)?o:[o];if(r.length===0)return{applies:!1};let s=(n?(0,_c.relative)(n,t):t).replace(/\\/g,"/");for(let c of r)if(Gp(c,s))return{applies:!0,reason:`glob: ${c}`};return{applies:!1}}function Oc(e,t){return t.has(e)}function vc(e){return(0,wc.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Rc(e,t){return t.has(e)}function Uo(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let o=n[1],r=n[2];try{return{metadata:Bp(o),body:r}}catch{return{metadata:{},body:e}}}function Bp(e){let t=e.split(`
1042
+ `),n={},o=0;for(;o<t.length;){let r=t[o],i=r.indexOf(":");if(i===-1){o++;continue}let s=r.slice(0,i).trim(),c=r.slice(i+1).trim();if(s==="description")n.description=Dt(c);else if(s==="alwaysApply")n.alwaysApply=c==="true";else if(s==="globs"||s==="paths"||s==="applyTo"){let{value:a,consumed:l}=qp(c,t,o);n.globs=Vp(n.globs,a),o+=l;continue}o++}return n}function Dt(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function qp(e,t,n){if(e.startsWith("["))return{value:Yp(e),consumed:1};if(!e||e===""){let r=[],i=1;for(let s=n+1;s<t.length;s++){let c=t[s],a=c.match(/^\s+-\s*(.*)$/);if(a){let l=Dt(a[1].trim());l&&r.push(l),i++}else if(c.trim()==="")i++;else break}if(r.length>0)return{value:r,consumed:i}}let o=Dt(e);return o.includes(",")?{value:o.split(",").map(i=>i.trim()).filter(i=>i.length>0),consumed:1}:{value:o,consumed:1}}function Yp(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,i="";for(let c=0;c<t.length;c++){let a=t[c];if(!r&&(a==='"'||a==="'"))r=!0,i=a;else if(r&&a===i)r=!1,i="";else if(!r&&a===","){let l=o.trim();l&&n.push(Dt(l)),o=""}else o+=a}let s=o.trim();return s&&n.push(Dt(s)),n}function Vp(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var le=require("fs"),Ic=require("path");function jo(e){return(0,Ic.join)(gn,`${e}.json`)}function bc(e){let t=jo(e);if(!(0,le.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,le.readFileSync)(t,"utf-8"),o=JSON.parse(n);return{contentHashes:new Set(o.injectedHashes),realPaths:new Set(o.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function Cc(e,t){(0,le.existsSync)(gn)||(0,le.mkdirSync)(gn,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,le.writeFileSync)(jo(e),JSON.stringify(n,null,2))}function Ac(e){let t=jo(e);(0,le.existsSync)(t)&&(0,le.unlinkSync)(t)}function Nc(e){let t=new Map;function n(s){return t.has(s)||t.set(s,bc(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,Lt.resolve)(e,s):null}function r(s,c){let a=o(s);if(!a)return[];let l=Mo(a),u=n(c),d=(0,Wo.homedir)(),f=$o(l,d,a),g=[];for(let m of f)if(!Oc(m.realPath,u.realPaths))try{let p=(0,Ho.readFileSync)(m.path,"utf-8"),{metadata:h,body:y}=Uo(p),w;if(m.isSingleFile)w="copilot-instructions (always apply)";else{let L=Fo(h,a,l);if(!L.applies)continue;w=L.reason??"matched"}let k=vc(y);if(Rc(k,u.contentHashes))continue;let C=l?(0,Lt.relative)(l,m.path):m.path;g.push({relativePath:C,matchReason:w,content:y,distance:m.distance}),u.realPaths.add(m.realPath),u.contentHashes.add(k)}catch{}return g.length>0&&(g.sort((m,p)=>m.distance-p.distance),Cc(c,u)),g}function i(s){if(s.length===0)return"";let c="";for(let a of s)c+=`
1043
1043
 
1044
1044
  [Rule: ${a.relativePath}]
1045
1045
  [Match: ${a.matchReason}]
1046
- ${a.content}`;return c}return{processToolExecution:(s,c,a)=>{if(!Co.includes(s.toLowerCase()))return"";let l=r(c,a);return i(l)},getRulesForFile:s=>{let c=o(s);if(!c)return[];let a=xo(c),l=(0,Uo.homedir)(),u=Do(a,l,c),d=[];for(let f of u)try{let g=(0,Fo.readFileSync)(f.path,"utf-8"),{metadata:m,body:p}=Mo(g),h;if(f.isSingleFile)h="copilot-instructions (always apply)";else{let T=Lo(m,c,a);if(!T.applies)continue;h=T.reason??"matched"}let y=a?(0,xt.relative)(a,f.path):f.path;d.push({relativePath:y,matchReason:h,content:p,distance:f.distance})}catch{}return d.sort((f,g)=>f.distance-g.distance)},clearSession:s=>{t.delete(s),Rc(s)},isTrackedTool:s=>Co.includes(s.toLowerCase())}}var gn=require("node:fs"),Ie=require("node:path");var le=require("node:fs"),Cc=require("node:path");var jo=require("node:path"),Ac=require("node:os"),Hp=(0,jo.join)((0,Ac.homedir)(),".olympus"),mn=(0,jo.join)(Hp,"directory-readme"),bc="README.md",Ho=["read","write","edit","multiedit"];function Wo(e){return(0,Cc.join)(mn,`${e}.json`)}function Nc(e){let t=Wo(e);if(!(0,le.existsSync)(t))return new Set;try{let n=(0,le.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function Pc(e,t){(0,le.existsSync)(mn)||(0,le.mkdirSync)(mn,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,le.writeFileSync)(Wo(e),JSON.stringify(n,null,2))}function xc(e){let t=Wo(e);(0,le.existsSync)(t)&&(0,le.unlinkSync)(t)}var Dc=4,Wp=5e3;function Gp(e,t=Wp){if(Math.ceil(e.length/Dc)<=t)return{result:e,truncated:!1};let o=t*Dc;return{result:e.slice(0,o),truncated:!0}}function Lc(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Nc(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,Ie.resolve)(e,s):null}function r(s){let c=[],a=s;for(;;){let l=(0,Ie.join)(a,bc);if((0,gn.existsSync)(l)&&c.push(l),a===e)break;let u=(0,Ie.dirname)(a);if(u===a||!u.startsWith(e))break;a=u}return c.reverse()}function i(s,c){let a=o(s);if(!a)return"";let l=(0,Ie.dirname)(a),u=n(c),d=r(l),f="";for(let g of d){let m=(0,Ie.dirname)(g);if(!u.has(m))try{let p=(0,gn.readFileSync)(g,"utf-8"),{result:h,truncated:y}=Gp(p),T=y?`
1046
+ ${a.content}`;return c}return{processToolExecution:(s,c,a)=>{if(!xo.includes(s.toLowerCase()))return"";let l=r(c,a);return i(l)},getRulesForFile:s=>{let c=o(s);if(!c)return[];let a=Mo(c),l=(0,Wo.homedir)(),u=$o(a,l,c),d=[];for(let f of u)try{let g=(0,Ho.readFileSync)(f.path,"utf-8"),{metadata:m,body:p}=Uo(g),h;if(f.isSingleFile)h="copilot-instructions (always apply)";else{let w=Fo(m,c,a);if(!w.applies)continue;h=w.reason??"matched"}let y=a?(0,Lt.relative)(a,f.path):f.path;d.push({relativePath:y,matchReason:h,content:p,distance:f.distance})}catch{}return d.sort((f,g)=>f.distance-g.distance)},clearSession:s=>{t.delete(s),Ac(s)},isTrackedTool:s=>xo.includes(s.toLowerCase())}}var kn=require("node:fs"),be=require("node:path");var ue=require("node:fs"),Dc=require("node:path");var Go=require("node:path"),Pc=require("node:os"),Kp=(0,Go.join)((0,Pc.homedir)(),".olympus"),hn=(0,Go.join)(Kp,"directory-readme"),xc="README.md",Bo=["read","write","edit","multiedit"];function qo(e){return(0,Dc.join)(hn,`${e}.json`)}function Lc(e){let t=qo(e);if(!(0,ue.existsSync)(t))return new Set;try{let n=(0,ue.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function Mc(e,t){(0,ue.existsSync)(hn)||(0,ue.mkdirSync)(hn,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,ue.writeFileSync)(qo(e),JSON.stringify(n,null,2))}function $c(e){let t=qo(e);(0,ue.existsSync)(t)&&(0,ue.unlinkSync)(t)}var Fc=4,Jp=5e3;function zp(e,t=Jp){if(Math.ceil(e.length/Fc)<=t)return{result:e,truncated:!1};let o=t*Fc;return{result:e.slice(0,o),truncated:!0}}function Uc(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Lc(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,be.resolve)(e,s):null}function r(s){let c=[],a=s;for(;;){let l=(0,be.join)(a,xc);if((0,kn.existsSync)(l)&&c.push(l),a===e)break;let u=(0,be.dirname)(a);if(u===a||!u.startsWith(e))break;a=u}return c.reverse()}function i(s,c){let a=o(s);if(!a)return"";let l=(0,be.dirname)(a),u=n(c),d=r(l),f="";for(let g of d){let m=(0,be.dirname)(g);if(!u.has(m))try{let p=(0,kn.readFileSync)(g,"utf-8"),{result:h,truncated:y}=zp(p),w=y?`
1047
1047
 
1048
1048
  [Note: Content was truncated to save context window space. For full context, please read the file directly: ${g}]`:"";f+=`
1049
1049
 
1050
1050
  [Project README: ${g}]
1051
- ${h}${T}`,u.add(m)}catch{}}return f&&Pc(c,u),f}return{processToolExecution:(s,c,a)=>Ho.includes(s.toLowerCase())?i(c,a):"",getReadmesForFile:s=>{let c=o(s);if(!c)return[];let a=(0,Ie.dirname)(c);return r(a)},clearSession:s=>{t.delete(s),xc(s)},isTrackedTool:s=>Ho.includes(s.toLowerCase())}}var Mc="non-interactive-env",$c={CI:"true",DEBIAN_FRONTEND:"noninteractive",GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",HOMEBREW_NO_AUTO_UPDATE:"1",GIT_EDITOR:":",EDITOR:":",VISUAL:"",GIT_SEQUENCE_EDITOR:":",GIT_MERGE_AUTOEDIT:"no",GIT_PAGER:"cat",PAGER:"cat",npm_config_yes:"true",PIP_NO_INPUT:"1",YARN_ENABLE_IMMUTABLE_INSTALLS:"false"},Go={npm:{bad:["npm init","npm install (prompts)"],good:["npm init -y","npm install --yes"]},apt:{bad:["apt-get install pkg"],good:["apt-get install -y pkg","DEBIAN_FRONTEND=noninteractive apt-get install pkg"]},pip:{bad:["pip install pkg (with prompts)"],good:["pip install --no-input pkg","PIP_NO_INPUT=1 pip install pkg"]},git:{bad:["git commit","git merge branch","git add -p","git rebase -i"],good:["git commit -m 'msg'","git merge --no-edit branch","git add .","git rebase --no-edit"]},system:{bad:["rm file (prompts)","cp a b (prompts)","ssh host"],good:["rm -f file","cp -f a b","ssh -o BatchMode=yes host","unzip -o file.zip"]},banned:["vim","nano","vi","emacs","less","more","man","python (REPL)","node (REPL)","git add -p","git rebase -i"],workarounds:{yesPipe:"yes | ./script.sh",heredoc:`./script.sh <<EOF
1051
+ ${h}${w}`,u.add(m)}catch{}}return f&&Mc(c,u),f}return{processToolExecution:(s,c,a)=>Bo.includes(s.toLowerCase())?i(c,a):"",getReadmesForFile:s=>{let c=o(s);if(!c)return[];let a=(0,be.dirname)(c);return r(a)},clearSession:s=>{t.delete(s),$c(s)},isTrackedTool:s=>Bo.includes(s.toLowerCase())}}var jc="non-interactive-env",Hc={CI:"true",DEBIAN_FRONTEND:"noninteractive",GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",HOMEBREW_NO_AUTO_UPDATE:"1",GIT_EDITOR:":",EDITOR:":",VISUAL:"",GIT_SEQUENCE_EDITOR:":",GIT_MERGE_AUTOEDIT:"no",GIT_PAGER:"cat",PAGER:"cat",npm_config_yes:"true",PIP_NO_INPUT:"1",YARN_ENABLE_IMMUTABLE_INSTALLS:"false"},Yo={npm:{bad:["npm init","npm install (prompts)"],good:["npm init -y","npm install --yes"]},apt:{bad:["apt-get install pkg"],good:["apt-get install -y pkg","DEBIAN_FRONTEND=noninteractive apt-get install pkg"]},pip:{bad:["pip install pkg (with prompts)"],good:["pip install --no-input pkg","PIP_NO_INPUT=1 pip install pkg"]},git:{bad:["git commit","git merge branch","git add -p","git rebase -i"],good:["git commit -m 'msg'","git merge --no-edit branch","git add .","git rebase --no-edit"]},system:{bad:["rm file (prompts)","cp a b (prompts)","ssh host"],good:["rm -f file","cp -f a b","ssh -o BatchMode=yes host","unzip -o file.zip"]},banned:["vim","nano","vi","emacs","less","more","man","python (REPL)","node (REPL)","git add -p","git rebase -i"],workarounds:{yesPipe:"yes | ./script.sh",heredoc:`./script.sh <<EOF
1052
1052
  option1
1053
1053
  option2
1054
- EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Fc=Go.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function Bp(e){for(let t=0;t<Fc.length;t++)if(Fc[t].test(e))return Go.banned[t]}function qp(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function Yp(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${qp(o)}`).join(" ")};`}var Bo={name:Mc,async beforeCommand(e){let t=Bp(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${Yp($c)} ${e}`,warning:n}:{command:e,warning:n}}};var Yo=require("child_process");var Uc="olympus-orchestrator",jc=".olympus/",Hc=["Write","Edit","write","edit"],Wc=`
1054
+ EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Wc=Yo.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function Xp(e){for(let t=0;t<Wc.length;t++)if(Wc[t].test(e))return Yo.banned[t]}function Qp(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function Zp(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${Qp(o)}`).join(" ")};`}var Vo={name:jc,async beforeCommand(e){let t=Xp(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${Zp(Hc)} ${e}`,warning:n}:{command:e,warning:n}}};var Jo=require("child_process");var Gc="olympus-orchestrator",Bc=".olympus/",qc=["Write","Edit","write","edit"],Yc=`
1055
1055
 
1056
1056
  ---
1057
1057
 
@@ -1077,7 +1077,7 @@ You should NOT:
1077
1077
  3. Verify the subagent's work after completion
1078
1078
 
1079
1079
  ---
1080
- `;var Gc=`[SYSTEM REMINDER - QUEST CONTINUATION]
1080
+ `;var Vc=`[SYSTEM REMINDER - QUEST CONTINUATION]
1081
1081
 
1082
1082
  You have an active work plan with incomplete tasks. Continue working.
1083
1083
 
@@ -1086,7 +1086,7 @@ RULES:
1086
1086
  - Mark each checkbox [x] in the plan file when done
1087
1087
  - Learnings are automatically captured in .olympus/learning/discoveries.jsonl
1088
1088
  - Do not stop until all tasks are complete
1089
- - If blocked, document the blocker and move to the next task`,Bc=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
1089
+ - If blocked, document the blocker and move to the next task`,Kc=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
1090
1090
 
1091
1091
  Subagents FREQUENTLY claim completion when:
1092
1092
  - Tests are actually FAILING
@@ -1101,7 +1101,7 @@ Subagents FREQUENTLY claim completion when:
1101
1101
  3. Check build/typecheck - Must succeed
1102
1102
 
1103
1103
  DO NOT TRUST THE AGENT'S SELF-REPORT.
1104
- VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,qc=`
1104
+ VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Jc=`
1105
1105
 
1106
1106
  [SYSTEM DIRECTIVE - SINGLE TASK ONLY]
1107
1107
 
@@ -1124,7 +1124,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
1124
1124
  - Batch delegation = sloppy work = rework = wasted tokens
1125
1125
 
1126
1126
  **REFUSE multi-task requests. DEMAND single-task clarity.**
1127
- `,Yc=`
1127
+ `,zc=`
1128
1128
 
1129
1129
  ================================================================================
1130
1130
  HARD BLOCK: DELEGATION REQUIRED
@@ -1163,41 +1163,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
1163
1163
  Delegate to a subagent to proceed.
1164
1164
 
1165
1165
  ================================================================================
1166
- `;var Dt=".olympus",hn="quest.json",Vp=`${Dt}/${hn}`,Vc="notepads",Kp=`${Dt}/${Vc}`;var he=require("fs"),kn=require("path");function Kc(e){return(0,kn.join)(e,Dt,hn)}function yn(e){let t=Kc(e);if(!(0,he.existsSync)(t))return null;try{let n=(0,he.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function En(e){if(!(0,he.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,he.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],o=t.match(/^[-*]\s*\[[xX]\]/gm)||[],r=n.length+o.length,i=o.length;return{total:r,completed:i,isComplete:r===0||i===r}}catch{return{total:0,completed:0,isComplete:!0}}}var Lt=class{recentTasks=[];maxTracked=3;recordTaskCompletion(t){this.recentTasks.unshift(t),this.recentTasks.length>this.maxTracked&&this.recentTasks.pop()}isVerificationEdit(t,n){return this.recentTasks.some(r=>r.filesModified.includes(t))&&n<10}getRecentTaskFiles(){let t=this.recentTasks.flatMap(n=>n.filesModified);return Array.from(new Set(t))}getRecentTasks(){return[...this.recentTasks]}clear(){this.recentTasks=[]}get trackedCount(){return this.recentTasks.length}},nE=new Lt;var Je=require("fs"),qo=require("path");function Mt(e,t){let n=t||process.cwd(),o=(0,qo.join)(n,".olympus","logs"),r=(0,qo.join)(o,"hook-violations.jsonl");try{(0,Je.existsSync)(o)||(0,Je.mkdirSync)(o,{recursive:!0});let i=JSON.stringify(e)+`
1167
- `;(0,Je.appendFileSync)(r,i,"utf-8")}catch(i){console.error("[Hook Logging] Failed to log violation:",i)}}var Jc=new Lt;function zc(e){return e?e.replace(/\\/g,"/").includes(jc):!0}function Xp(e){if(!e)return!1;let t=e.replace(/\\/g,"/");return t.includes("__tests__/")||t.endsWith(".test.ts")||t.endsWith(".test.js")||t.endsWith(".spec.ts")||t.endsWith(".spec.js")}function Qp(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",o=t.new_string??"";if(!n&&!o)return 0;let r=n.split(`
1166
+ `;var Mt=".olympus",yn="quest.json",em=`${Mt}/${yn}`,Xc="notepads",tm=`${Mt}/${Xc}`;var ke=require("fs"),En=require("path");function Qc(e){return(0,En.join)(e,Mt,yn)}function Sn(e){let t=Qc(e);if(!(0,ke.existsSync)(t))return null;try{let n=(0,ke.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Tn(e){if(!(0,ke.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,ke.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],o=t.match(/^[-*]\s*\[[xX]\]/gm)||[],r=n.length+o.length,i=o.length;return{total:r,completed:i,isComplete:r===0||i===r}}catch{return{total:0,completed:0,isComplete:!0}}}var $t=class{recentTasks=[];maxTracked=3;recordTaskCompletion(t){this.recentTasks.unshift(t),this.recentTasks.length>this.maxTracked&&this.recentTasks.pop()}isVerificationEdit(t,n){return this.recentTasks.some(r=>r.filesModified.includes(t))&&n<10}getRecentTaskFiles(){let t=this.recentTasks.flatMap(n=>n.filesModified);return Array.from(new Set(t))}getRecentTasks(){return[...this.recentTasks]}clear(){this.recentTasks=[]}get trackedCount(){return this.recentTasks.length}},lE=new $t;var ze=require("fs"),Ko=require("path");function Ft(e,t){let n=t||process.cwd(),o=(0,Ko.join)(n,".olympus","logs"),r=(0,Ko.join)(o,"hook-violations.jsonl");try{(0,ze.existsSync)(o)||(0,ze.mkdirSync)(o,{recursive:!0});let i=JSON.stringify(e)+`
1167
+ `;(0,ze.appendFileSync)(r,i,"utf-8")}catch(i){console.error("[Hook Logging] Failed to log violation:",i)}}var Zc=new $t;function el(e){return e?e.replace(/\\/g,"/").includes(Bc):!0}function rm(e){if(!e)return!1;let t=e.replace(/\\/g,"/");return t.includes("__tests__/")||t.endsWith(".test.ts")||t.endsWith(".test.js")||t.endsWith(".spec.ts")||t.endsWith(".spec.js")}function im(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",o=t.new_string??"";if(!n&&!o)return 0;let r=n.split(`
1168
1168
  `).length,i=o.split(`
1169
1169
  `).length;return Math.abs(i-r)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
1170
- `).length:0}return 0}function Xc(e){return Hc.includes(e)}function Zp(e){try{let t=(0,Yo.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Yo.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let i of n.split(`
1170
+ `).length:0}return 0}function tl(e){return qc.includes(e)}function sm(e){try{let t=(0,Jo.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Jo.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let i of n.split(`
1171
1171
  `)){if(!i)continue;let s=i.substring(0,2).trim(),c=i.substring(3);s==="A"||s==="??"?o.set(c,"added"):s==="D"?o.set(c,"deleted"):o.set(c,"modified")}let r=[];for(let i of t.split(`
1172
- `)){let s=i.split(" ");if(s.length<3)continue;let[c,a,l]=s,u=c==="-"?0:parseInt(c,10),d=a==="-"?0:parseInt(a,10);r.push({path:l,added:u,removed:d,status:o.get(l)??"modified"})}return r}catch{return[]}}function em(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
1172
+ `)){let s=i.split(" ");if(s.length<3)continue;let[c,a,l]=s,u=c==="-"?0:parseInt(c,10),d=a==="-"?0:parseInt(a,10);r.push({path:l,added:u,removed:d,status:o.get(l)??"modified"})}return r}catch{return[]}}function am(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
1173
1173
  No file changes detected.
1174
1174
  `;let t=e.filter(i=>i.status==="modified"),n=e.filter(i=>i.status==="added"),o=e.filter(i=>i.status==="deleted"),r=["[FILE CHANGES SUMMARY]"];if(t.length>0){r.push("Modified files:");for(let i of t)r.push(` ${i.path} (+${i.added}, -${i.removed})`);r.push("")}if(n.length>0){r.push("Created files:");for(let i of n)r.push(` ${i.path} (+${i.added})`);r.push("")}if(o.length>0){r.push("Deleted files:");for(let i of o)r.push(` ${i.path} (-${i.removed})`);r.push("")}return r.join(`
1175
- `)}function Qc(e){let t=Bc;return e&&(t+=`
1175
+ `)}function nl(e){let t=Kc;return e&&(t+=`
1176
1176
 
1177
1177
  ---
1178
1178
 
1179
1179
  **If ANY verification fails, resume the subagent with the fix:**
1180
- Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function tm(e,t,n){let o=t.total-t.completed;return`
1180
+ Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function cm(e,t,n){let o=t.total-t.completed;return`
1181
1181
  ---
1182
1182
 
1183
1183
  **State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
1184
1184
 
1185
1185
  ---
1186
1186
 
1187
- ${Qc(n)}
1187
+ ${nl(n)}
1188
1188
 
1189
- ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function nm(e,t,n){return Gc.replace(/{PLAN_NAME}/g,e)+`
1189
+ ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function lm(e,t,n){return Vc.replace(/{PLAN_NAME}/g,e)+`
1190
1190
 
1191
- [Status: ${n-t}/${n} completed, ${t} remaining]`}function om(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!Xc(t))return{continue:!0};let i=n?.filePath??n?.path??n?.file;if(!i)return{continue:!0};let s=i.replace(/\\/g,"/");if(zc(s))return Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(Xp(s))return Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let c=Qp(t,n);return Jc.isVerificationEdit(s,c)?(Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:c,wasBlocked:!1,reason:`Allowed: Verification edit (${c} lines on recent task file)`},r),{continue:!0}):(Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:c,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:Yc})}function rm(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:i}=e,s=r||process.cwd();if(Xc(n)){let c=o?.filePath??o?.path??o?.file;if(c&&!zc(c))return{continue:!0,modifiedOutput:t+Wc}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let a=Zp(s),l=a.map(f=>f.path);Jc.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:i||`task-${Date.now()}`});let u=em(a),d=yn(s);if(d){let f=En(d.active_plan);return{continue:!0,modifiedOutput:`
1191
+ [Status: ${n-t}/${n} completed, ${t} remaining]`}function um(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!tl(t))return{continue:!0};let i=n?.filePath??n?.path??n?.file;if(!i)return{continue:!0};let s=i.replace(/\\/g,"/");if(el(s))return Ft({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(rm(s))return Ft({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let c=im(t,n);return Zc.isVerificationEdit(s,c)?(Ft({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:c,wasBlocked:!1,reason:`Allowed: Verification edit (${c} lines on recent task file)`},r),{continue:!0}):(Ft({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:c,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:zc})}function dm(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:i}=e,s=r||process.cwd();if(tl(n)){let c=o?.filePath??o?.path??o?.file;if(c&&!el(c))return{continue:!0,modifiedOutput:t+Yc}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let a=sm(s),l=a.map(f=>f.path);Zc.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:i||`task-${Date.now()}`});let u=am(a),d=Sn(s);if(d){let f=Tn(d.active_plan);return{continue:!0,modifiedOutput:`
1192
1192
  ## SUBAGENT WORK COMPLETED
1193
1193
 
1194
1194
  ${u}
1195
1195
  <system-reminder>
1196
- ${tm(d.plan_name,f,i)}
1196
+ ${cm(d.plan_name,f,i)}
1197
1197
  </system-reminder>`}}return{continue:!0,modifiedOutput:t+`
1198
1198
  <system-reminder>
1199
- ${Qc(i)}
1200
- </system-reminder>`}}return{continue:!0}}function im(e){let t=yn(e);if(!t)return{shouldContinue:!1};let n=En(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:nm(t.plan_name,o,n.total)}}function Sn(e){return{name:Uc,preTool:(t,n)=>om({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>rm({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>im(e),getSingleTaskDirective:()=>qc}}function Zc(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function el(){v({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=Ic(e.directory||process.cwd()),n=Zc(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),v({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=Lc(e.directory||process.cwd()),n=Zc(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),v({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!Bo.beforeCommand)return{continue:!0};let n=await Bo.beforeCommand(t.command);return{continue:!0,hookSpecificOutput:n.warning?{hookEventName:"PreToolUse",additionalContext:n.warning}:void 0,modifiedInput:n.command!==t.command?{...t,command:n.command}:void 0}}catch(n){return console.error("[nonInteractiveEnv] Error:",n),{continue:!0}}}}),v({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>Sn(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var sm=["oldString and newString must be different","oldString not found","oldString found multiple times","old_string not found","old_string and new_string must be different"],am=`
1199
+ ${nl(i)}
1200
+ </system-reminder>`}}return{continue:!0}}function fm(e){let t=Sn(e);if(!t)return{shouldContinue:!1};let n=Tn(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:lm(t.plan_name,o,n.total)}}function wn(e){return{name:Gc,preTool:(t,n)=>um({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>dm({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>fm(e),getSingleTaskDirective:()=>Jc}}function ol(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function rl(){R({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=Nc(e.directory||process.cwd()),n=ol(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),R({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=Uc(e.directory||process.cwd()),n=ol(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),R({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!Vo.beforeCommand)return{continue:!0};let n=await Vo.beforeCommand(t.command);return{continue:!0,hookSpecificOutput:n.warning?{hookEventName:"PreToolUse",additionalContext:n.warning}:void 0,modifiedInput:n.command!==t.command?{...t,command:n.command}:void 0}}catch(n){return console.error("[nonInteractiveEnv] Error:",n),{continue:!0}}}}),R({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>wn(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var pm=["oldString and newString must be different","oldString not found","oldString found multiple times","old_string not found","old_string and new_string must be different"],mm=`
1201
1201
  [EDIT ERROR - IMMEDIATE ACTION REQUIRED]
1202
1202
 
1203
1203
  You made an Edit mistake. STOP and do this NOW:
@@ -1208,7 +1208,7 @@ You made an Edit mistake. STOP and do this NOW:
1208
1208
  4. CONTINUE with corrected action based on the real file content
1209
1209
 
1210
1210
  DO NOT attempt another edit until you've read and verified the file state.
1211
- `;function cm(e){let t=e.toLowerCase();return sm.some(n=>t.includes(n.toLowerCase()))}function tl(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:cm(t.output)?{...t,output:t.output+am}:t}}var rl=H(require("fs"),1),wn=H(require("path"),1),il=require("os");var Tn=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Vo=["type:","noqa","pyright:","ruff:","mypy:","pylint:","flake8:","pyre:","pytype:","eslint-disable","eslint-enable","eslint-ignore","prettier-ignore","ts-ignore","ts-expect-error","ts-nocheck","@ts-ignore","@ts-expect-error","@ts-nocheck","clippy::","allow(","deny(","warn(","forbid(","nolint","go:generate","go:build","go:embed","coverage:","c8 ignore","istanbul ignore","biome-ignore","region","endregion","#region","#endregion"],Ko=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
1211
+ `;function gm(e){let t=e.toLowerCase();return pm.some(n=>t.includes(n.toLowerCase()))}function il(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:gm(t.output)?{...t,output:t.output+mm}:t}}var cl=F(require("fs"),1),On=F(require("path"),1),ll=require("os");var _n=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),zo=["type:","noqa","pyright:","ruff:","mypy:","pylint:","flake8:","pyre:","pytype:","eslint-disable","eslint-enable","eslint-ignore","prettier-ignore","ts-ignore","ts-expect-error","ts-nocheck","@ts-ignore","@ts-expect-error","@ts-nocheck","clippy::","allow(","deny(","warn(","forbid(","nolint","go:generate","go:build","go:embed","coverage:","c8 ignore","istanbul ignore","biome-ignore","region","endregion","#region","#endregion"],Xo=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
1212
1212
 
1213
1213
  Your recent changes contain comments or docstrings, which triggered this hook.
1214
1214
  You need to take immediate action. You must follow the conditions below.
@@ -1246,13 +1246,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
1246
1246
  Review in the above priority order and take the corresponding action EVERY TIME this appears.
1247
1247
 
1248
1248
  Detected comments/docstrings:
1249
- `,Jo={js:/\/\/.*$|\/\*[\s\S]*?\*\//gm,ts:/\/\/.*$|\/\*[\s\S]*?\*\//gm,jsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,tsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,java:/\/\/.*$|\/\*[\s\S]*?\*\//gm,c:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cpp:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cs:/\/\/.*$|\/\*[\s\S]*?\*\//gm,go:/\/\/.*$/gm,rust:/\/\/.*$|\/\*[\s\S]*?\*\//gm,swift:/\/\/.*$|\/\*[\s\S]*?\*\//gm,kotlin:/\/\/.*$|\/\*[\s\S]*?\*\//gm,py:/#.*$|'''[\s\S]*?'''|"""[\s\S]*?"""/gm,rb:/#.*$|=begin[\s\S]*?=end/gm,sh:/#.*$/gm,bash:/#.*$/gm,zsh:/#.*$/gm,yaml:/#.*$/gm,yml:/#.*$/gm,toml:/#.*$/gm,html:/<!--[\s\S]*?-->/gm,xml:/<!--[\s\S]*?-->/gm,vue:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,svelte:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,sql:/--.*$/gm,lua:/--.*$|--\[\[[\s\S]*?\]\]/gm},zo={".js":"js",".mjs":"js",".cjs":"js",".ts":"ts",".mts":"ts",".cts":"ts",".jsx":"jsx",".tsx":"tsx",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"cs",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".py":"py",".pyi":"py",".rb":"rb",".sh":"sh",".bash":"bash",".zsh":"zsh",".yaml":"yaml",".yml":"yml",".toml":"toml",".html":"html",".htm":"html",".xml":"xml",".vue":"vue",".svelte":"svelte",".sql":"sql",".lua":"lua"};function lm(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function um(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Tn){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>Tn.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function dm(e){let t=e.text.toLowerCase().trim();for(let n of Vo)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function fm(e){return{shouldSkip:!1}}function pm(e){let t=e.text.toLowerCase(),n=["copyright","license","licensed under","spdx-license-identifier","all rights reserved","mit license","apache license","gnu general public","bsd license"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function mm(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:`todo marker: ${o}`};return{shouldSkip:!1}}var gm=[lm,um,dm,pm,mm,fm];function Xo(e){return e.filter(t=>{for(let n of gm)if(n(t).shouldSkip)return!1;return!0})}var hm=process.env.COMMENT_CHECKER_DEBUG==="1",km=wn.join((0,il.tmpdir)(),"comment-checker-debug.log");function ze(...e){if(hm){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1250
- `;rl.appendFileSync(km,t)}}function ym(e){let t=wn.extname(e).toLowerCase();return zo[t]}function Qo(e,t){let n=ym(t);if(!n)return ze("unsupported language for:",t),[];let o=Jo[n];if(!o)return ze("no pattern for language:",n),[];let r=[],i=e.split(`
1249
+ `,Qo={js:/\/\/.*$|\/\*[\s\S]*?\*\//gm,ts:/\/\/.*$|\/\*[\s\S]*?\*\//gm,jsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,tsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,java:/\/\/.*$|\/\*[\s\S]*?\*\//gm,c:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cpp:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cs:/\/\/.*$|\/\*[\s\S]*?\*\//gm,go:/\/\/.*$/gm,rust:/\/\/.*$|\/\*[\s\S]*?\*\//gm,swift:/\/\/.*$|\/\*[\s\S]*?\*\//gm,kotlin:/\/\/.*$|\/\*[\s\S]*?\*\//gm,py:/#.*$|'''[\s\S]*?'''|"""[\s\S]*?"""/gm,rb:/#.*$|=begin[\s\S]*?=end/gm,sh:/#.*$/gm,bash:/#.*$/gm,zsh:/#.*$/gm,yaml:/#.*$/gm,yml:/#.*$/gm,toml:/#.*$/gm,html:/<!--[\s\S]*?-->/gm,xml:/<!--[\s\S]*?-->/gm,vue:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,svelte:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,sql:/--.*$/gm,lua:/--.*$|--\[\[[\s\S]*?\]\]/gm},Zo={".js":"js",".mjs":"js",".cjs":"js",".ts":"ts",".mts":"ts",".cts":"ts",".jsx":"jsx",".tsx":"tsx",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"cs",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".py":"py",".pyi":"py",".rb":"rb",".sh":"sh",".bash":"bash",".zsh":"zsh",".yaml":"yaml",".yml":"yml",".toml":"toml",".html":"html",".htm":"html",".xml":"xml",".vue":"vue",".svelte":"svelte",".sql":"sql",".lua":"lua"};function hm(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function km(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of _n){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>_n.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function ym(e){let t=e.text.toLowerCase().trim();for(let n of zo)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function Em(e){return{shouldSkip:!1}}function Sm(e){let t=e.text.toLowerCase(),n=["copyright","license","licensed under","spdx-license-identifier","all rights reserved","mit license","apache license","gnu general public","bsd license"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function Tm(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:`todo marker: ${o}`};return{shouldSkip:!1}}var wm=[hm,km,ym,Sm,Tm,Em];function er(e){return e.filter(t=>{for(let n of wm)if(n(t).shouldSkip)return!1;return!0})}var _m=process.env.COMMENT_CHECKER_DEBUG==="1",Om=On.join((0,ll.tmpdir)(),"comment-checker-debug.log");function Xe(...e){if(_m){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1250
+ `;cl.appendFileSync(Om,t)}}function vm(e){let t=On.extname(e).toLowerCase();return Zo[t]}function tr(e,t){let n=vm(t);if(!n)return Xe("unsupported language for:",t),[];let o=Qo[n];if(!o)return Xe("no pattern for language:",n),[];let r=[],i=e.split(`
1251
1251
  `);o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let c=s.index,a=s[0],u=e.substring(0,c).split(`
1252
- `).length,d="line",f=!1;a.startsWith("/*")||a.startsWith("<!--")?d="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(d="docstring",f=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:f})}return r}function Em(e,t){return Qo(e,t)}function nl(e,t,n){let o=Qo(e,t);if(n){let r=Qo(n,t),i=new Set(r.map(s=>s.text));return o.filter(s=>!i.has(s.text))}return o}function Sm(e){if(e.length===0)return"";let t=new Map;for(let o of e){let r=t.get(o.filePath)||[];r.push(o),t.set(o.filePath,r)}let n=Ko;for(let[o,r]of t){n+=`
1252
+ `).length,d="line",f=!1;a.startsWith("/*")||a.startsWith("<!--")?d="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(d="docstring",f=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:f})}return r}function Rm(e,t){return tr(e,t)}function sl(e,t,n){let o=tr(e,t);if(n){let r=tr(n,t),i=new Set(r.map(s=>s.text));return o.filter(s=>!i.has(s.text))}return o}function Im(e){if(e.length===0)return"";let t=new Map;for(let o of e){let r=t.get(o.filePath)||[];r.push(o),t.set(o.filePath,r)}let n=Xo;for(let[o,r]of t){n+=`
1253
1253
  File: ${o}
1254
1254
  `;for(let i of r){let s=i.isDocstring?"docstring":i.commentType;n+=` Line ${i.lineNumber} (${s}): ${i.text.substring(0,100)}${i.text.length>100?"...":""}
1255
- `}}return n}function Tm(e,t,n,o,r){let i=[];if(t)i=Em(t,e);else if(o)i=nl(o,e,n);else if(r&&r.length>0)for(let c of r){let a=nl(c.new_string,e,c.old_string);i.push(...a)}let s=Xo(i);return ze(`found ${i.length} comments, ${s.length} flagged after filtering`),s.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:s.length,message:Sm(s),comments:s}}var $t=new Map,wm=6e4;function _m(){let e=Date.now();for(let[t,n]of $t)e-n.timestamp>wm&&$t.delete(t)}var ol=!1;function sl(e){return ze("createCommentCheckerHook called",{config:e}),ol||(ol=!0,setInterval(_m,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,r=t.tool_input.content,i=t.tool_input.old_string??t.tool_input.oldString,s=t.tool_input.new_string??t.tool_input.newString,c=t.tool_input.edits;if(!o)return null;let a=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return ze("registering pendingCall:",{callId:a,filePath:o,tool:n}),$t.set(a,{filePath:o,content:r,oldString:i,newString:s,edits:c,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o,r;for(let[s,c]of $t)if(c.sessionId===t.session_id&&c.tool===n){o=c,r=s;break}if(!o){let s=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!s)return null;o={filePath:s,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(r&&$t.delete(r),t.tool_response){let s=t.tool_response.toLowerCase();if(s.includes("error:")||s.includes("failed to")||s.includes("could not")||s.startsWith("error"))return ze("skipping due to tool failure in response"),null}let i=Tm(o.filePath,o.content,o.oldString,o.newString,o.edits);return i.hasComments&&i.message?(ze("detected comments, returning message"),e?.customPrompt||i.message):null}}}var pl=H(require("fs"),1),ml=H(require("path"),1),gl=require("os");var cl=[/(\d+)\s*tokens?\s*>\s*(\d+)\s*maximum/i,/prompt.*?(\d+).*?tokens.*?exceeds.*?(\d+)/i,/(\d+).*?tokens.*?limit.*?(\d+)/i,/context.*?length.*?(\d+).*?maximum.*?(\d+)/i,/max.*?context.*?(\d+).*?but.*?(\d+)/i],ll=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],Om=[/thinking.*first block/i,/first block.*thinking/i,/must.*start.*thinking/i,/thinking.*redacted_thinking/i,/expected.*thinking.*found/i,/thinking.*disabled.*cannot.*contain/i],vm=/messages\.(\d+)/;function Rm(e){return Om.some(t=>t.test(e))}function Zo(e){for(let t of cl){let n=e.match(t);if(n){let o=parseInt(n[1],10),r=parseInt(n[2],10);return o>r?{current:o,max:r}:{current:r,max:o}}}return null}function al(e){let t=e.match(vm);if(t)return parseInt(t[1],10)}function dt(e){if(Rm(e))return!1;let t=e.toLowerCase();return ll.some(n=>t.includes(n.toLowerCase()))}function _n(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:al(e)};if(dt(e)){let l=Zo(e);return{currentTokens:l?.current??0,maxTokens:l?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],o=t.data,r=o?.responseBody,i=t.message,s=t.error,c=s?.error;if(typeof r=="string"&&n.push(r),typeof i=="string"&&n.push(i),typeof s?.message=="string"&&n.push(s.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof c?.message=="string"&&n.push(c.message),typeof o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let l=JSON.stringify(t);dt(l)&&n.push(l)}catch{}let a=n.join(" ");if(!dt(a))return null;if(typeof r=="string")try{let l=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of l){let f=r.match(d);if(f)try{let g=JSON.parse(f[1]),m=g.error?.message||"",p=Zo(m);if(p)return{currentTokens:p.current,maxTokens:p.max,requestId:g.request_id,errorType:g.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&dt(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=Zo(l);if(u)return{currentTokens:u.current,maxTokens:u.max,errorType:"token_limit_exceeded"}}return a.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:al(a)}:dt(a)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function er(e){return dt(e)}var tr=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
1255
+ `}}return n}function bm(e,t,n,o,r){let i=[];if(t)i=Rm(t,e);else if(o)i=sl(o,e,n);else if(r&&r.length>0)for(let c of r){let a=sl(c.new_string,e,c.old_string);i.push(...a)}let s=er(i);return Xe(`found ${i.length} comments, ${s.length} flagged after filtering`),s.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:s.length,message:Im(s),comments:s}}var Ut=new Map,Cm=6e4;function Am(){let e=Date.now();for(let[t,n]of Ut)e-n.timestamp>Cm&&Ut.delete(t)}var al=!1;function ul(e){return Xe("createCommentCheckerHook called",{config:e}),al||(al=!0,setInterval(Am,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,r=t.tool_input.content,i=t.tool_input.old_string??t.tool_input.oldString,s=t.tool_input.new_string??t.tool_input.newString,c=t.tool_input.edits;if(!o)return null;let a=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return Xe("registering pendingCall:",{callId:a,filePath:o,tool:n}),Ut.set(a,{filePath:o,content:r,oldString:i,newString:s,edits:c,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o,r;for(let[s,c]of Ut)if(c.sessionId===t.session_id&&c.tool===n){o=c,r=s;break}if(!o){let s=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!s)return null;o={filePath:s,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(r&&Ut.delete(r),t.tool_response){let s=t.tool_response.toLowerCase();if(s.includes("error:")||s.includes("failed to")||s.includes("could not")||s.startsWith("error"))return Xe("skipping due to tool failure in response"),null}let i=bm(o.filePath,o.content,o.oldString,o.newString,o.edits);return i.hasComments&&i.message?(Xe("detected comments, returning message"),e?.customPrompt||i.message):null}}}var kl=F(require("fs"),1),yl=F(require("path"),1),El=require("os");var fl=[/(\d+)\s*tokens?\s*>\s*(\d+)\s*maximum/i,/prompt.*?(\d+).*?tokens.*?exceeds.*?(\d+)/i,/(\d+).*?tokens.*?limit.*?(\d+)/i,/context.*?length.*?(\d+).*?maximum.*?(\d+)/i,/max.*?context.*?(\d+).*?but.*?(\d+)/i],pl=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],Nm=[/thinking.*first block/i,/first block.*thinking/i,/must.*start.*thinking/i,/thinking.*redacted_thinking/i,/expected.*thinking.*found/i,/thinking.*disabled.*cannot.*contain/i],Pm=/messages\.(\d+)/;function xm(e){return Nm.some(t=>t.test(e))}function nr(e){for(let t of fl){let n=e.match(t);if(n){let o=parseInt(n[1],10),r=parseInt(n[2],10);return o>r?{current:o,max:r}:{current:r,max:o}}}return null}function dl(e){let t=e.match(Pm);if(t)return parseInt(t[1],10)}function ft(e){if(xm(e))return!1;let t=e.toLowerCase();return pl.some(n=>t.includes(n.toLowerCase()))}function vn(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:dl(e)};if(ft(e)){let l=nr(e);return{currentTokens:l?.current??0,maxTokens:l?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],o=t.data,r=o?.responseBody,i=t.message,s=t.error,c=s?.error;if(typeof r=="string"&&n.push(r),typeof i=="string"&&n.push(i),typeof s?.message=="string"&&n.push(s.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof c?.message=="string"&&n.push(c.message),typeof o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let l=JSON.stringify(t);ft(l)&&n.push(l)}catch{}let a=n.join(" ");if(!ft(a))return null;if(typeof r=="string")try{let l=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of l){let f=r.match(d);if(f)try{let g=JSON.parse(f[1]),m=g.error?.message||"",p=nr(m);if(p)return{currentTokens:p.current,maxTokens:p.max,requestId:g.request_id,errorType:g.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&ft(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=nr(l);if(u)return{currentTokens:u.current,maxTokens:u.max,errorType:"token_limit_exceeded"}}return a.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:dl(a)}:ft(a)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function or(e){return ft(e)}var rr=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
1256
1256
 
1257
1257
  The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
1258
1258
 
@@ -1277,7 +1277,7 @@ Current Status:
1277
1277
  - Context limit exceeded
1278
1278
  - Further API calls will fail until context is reduced
1279
1279
  - Action required before continuing
1280
- `,nr="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",or=`API ERROR: Non-empty content validation failed.
1280
+ `,ir="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",sr=`API ERROR: Non-empty content validation failed.
1281
1281
 
1282
1282
  This error typically occurs when:
1283
1283
  - A message has empty text content
@@ -1288,7 +1288,7 @@ Suggested actions:
1288
1288
  2. If the error persists, start a new session
1289
1289
 
1290
1290
  The system will attempt automatic recovery.
1291
- `;var rr=`CONTEXT RECOVERY FAILED
1291
+ `;var ar=`CONTEXT RECOVERY FAILED
1292
1292
 
1293
1293
  All automatic recovery attempts have been exhausted.
1294
1294
  Please start a new session to continue.
@@ -1299,13 +1299,13 @@ Before starting a new session:
1299
1299
  3. Document the current state of the task
1300
1300
 
1301
1301
  You can copy this conversation summary to continue in a new session.
1302
- `;var ir={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var Im=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",Am=ml.join((0,gl.tmpdir)(),"context-limit-recovery-debug.log");function On(...e){if(Im){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1303
- `;pl.appendFileSync(Am,t)}}var vn=new Map,hl=3e5;function ul(e){let t=vn.get(e),n=Date.now();return t&&n-t.lastErrorTime>hl&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},vn.set(e,t)),t}function bm(){let e=Date.now();for(let[t,n]of vn)e-n.lastErrorTime>hl&&vn.delete(t)}var dl=!1;function kl(e){return On("createContextLimitRecoveryHook called",{config:e}),dl||(dl=!0,setInterval(bm,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=_n(t.tool_response);if(!n&&!er(t.tool_response))return null;On("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=ul(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=fl(n,o,e);return r.message?(On("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=_n(t.error);if(!n)return{attempted:!1,success:!1};On("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=ul(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=fl(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function fl(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:or,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>ir.maxAttempts)return{message:rr,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=tr;return e?.currentTokens&&e?.maxTokens&&(o+=`
1302
+ `;var cr={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var Dm=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",Lm=yl.join((0,El.tmpdir)(),"context-limit-recovery-debug.log");function Rn(...e){if(Dm){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1303
+ `;kl.appendFileSync(Lm,t)}}var In=new Map,Sl=3e5;function ml(e){let t=In.get(e),n=Date.now();return t&&n-t.lastErrorTime>Sl&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},In.set(e,t)),t}function Mm(){let e=Date.now();for(let[t,n]of In)e-n.lastErrorTime>Sl&&In.delete(t)}var gl=!1;function Tl(e){return Rn("createContextLimitRecoveryHook called",{config:e}),gl||(gl=!0,setInterval(Mm,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=vn(t.tool_response);if(!n&&!or(t.tool_response))return null;Rn("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=ml(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=hl(n,o,e);return r.message?(Rn("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=vn(t.error);if(!n)return{attempted:!1,success:!1};Rn("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=ml(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=hl(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function hl(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:sr,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>cr.maxAttempts)return{message:ar,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=rr;return e?.currentTokens&&e?.maxTokens&&(o+=`
1304
1304
  Token Details:
1305
1305
  - Current: ${e.currentTokens.toLocaleString()} tokens
1306
1306
  - Maximum: ${e.maxTokens.toLocaleString()} tokens
1307
1307
  - Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
1308
- `),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:nr,errorType:e?.errorType||"token_limit_exceeded"}}var yl=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,Cm=/exceeds maximum allowed tokens/i;function Nm(e){let t=e.match(yl);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Pm(e,t){return e.toLowerCase()==="read"&&(yl.test(t)||Cm.test(t))}function xm(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
1308
+ `),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:ir,errorType:e?.errorType||"token_limit_exceeded"}}var wl=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,$m=/exceeds maximum allowed tokens/i;function Fm(e){let t=e.match(wl);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Um(e,t){return e.toLowerCase()==="read"&&(wl.test(t)||$m.test(t))}function jm(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
1309
1309
 
1310
1310
  ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
1311
1311
 
@@ -1335,7 +1335,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
1335
1335
  - Need overview/summary? \u2192 Use multimodal-looker agent
1336
1336
  - Need specific section? \u2192 Grep to find it, then Read that portion
1337
1337
 
1338
- Proceed with one of these strategies.`.trim()}function El(){return{postToolUse:e=>{if(!e.tool_response||!Pm(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=Nm(e.tool_response);return xm(t,n||void 0)}}}var vl=H(require("fs"),1),Rl=H(require("path"),1),Il=require("os");var sr=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,Rn=4,ar=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
1338
+ Proceed with one of these strategies.`.trim()}function _l(){return{postToolUse:e=>{if(!e.tool_response||!Um(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=Fm(e.tool_response);return jm(t,n||void 0)}}}var Cl=F(require("fs"),1),Al=F(require("path"),1),Nl=require("os");var lr=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,bn=4,ur=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
1339
1339
 
1340
1340
  Your context usage is getting high. Consider these actions to prevent hitting the limit:
1341
1341
 
@@ -1355,7 +1355,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
1355
1355
 
1356
1356
  Current Status: Context usage is high but recoverable.
1357
1357
  Action recommended: Use /compact when convenient.
1358
- `,cr=`CRITICAL: CONTEXT WINDOW ALMOST FULL
1358
+ `,dr=`CRITICAL: CONTEXT WINDOW ALMOST FULL
1359
1359
 
1360
1360
  Your context usage is critically high. Immediate action required:
1361
1361
 
@@ -1374,8 +1374,8 @@ Your context usage is critically high. Immediate action required:
1374
1374
 
1375
1375
  WARNING: Further messages may fail if context is not reduced.
1376
1376
  Action required: Run /compact now.
1377
- `;var Dm=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Lm=Rl.join((0,Il.tmpdir)(),"preemptive-compaction-debug.log");function ft(...e){if(Dm){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1378
- `;vl.appendFileSync(Lm,t)}}var In=new Map;function Mm(){let e=Date.now(),t=1800*1e3;for(let[n,o]of In)e-o.lastWarningTime>t&&In.delete(n)}var Sl=!1;function Al(e){return Math.ceil(e.length/Rn)}function $m(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=sr,i=Al(e),s=i/r,c=s>=n,a=s>=o,l="none";return a?l="compact":c&&(l="warn"),{totalTokens:i,usageRatio:s,isWarning:c,isCritical:a,action:l}}function An(e){let t=In.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},In.set(e,t)),t}function Fm(e,t){let n=An(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,i=Date.now();return i-n.lastWarningTime<o?(ft("skipping warning - cooldown active",{sessionId:e,elapsed:i-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(ft("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Um(e){let t=An(e);t.lastWarningTime=Date.now(),t.warningCount++}function bl(e){return ft("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(Sl||(Sl=!0,setInterval(Mm,300*1e3)),{postToolUse:t=>{if(!t.tool_response)return null;let n=t.tool_name.toLowerCase();if(!["read","grep","glob","bash","webfetch"].includes(n))return null;let r=Al(t.tool_response),i=An(t.session_id);i.estimatedTokens+=r,ft("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:i.estimatedTokens});let s=$m("x".repeat(i.estimatedTokens*Rn),e);return!s.isWarning||!Fm(t.session_id,e)?null:(Um(t.session_id),ft("injecting context warning",{sessionId:t.session_id,usageRatio:s.usageRatio,isCritical:s.isCritical}),e?.customMessage?e.customMessage:s.isCritical?cr:ar)},stop:t=>{let n=An(t.session_id);return n.warningCount>0&&(ft("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var ue=require("fs"),Nl=require("path");var lr=require("path"),Cl=require("os"),jm=(0,lr.join)((0,Cl.homedir)(),".olympus"),bn=(0,lr.join)(jm,"agent-usage-reminder"),ur=new Set(["grep","safe_grep","glob","safe_glob","webfetch","context7_resolve-library-id","context7_query-docs","websearch_web_search_exa","context7_get-library-docs","grep_app_searchgithub"]),dr=new Set(["task","call_omo_agent","olympus_task"]),fr=`
1377
+ `;var Hm=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Wm=Al.join((0,Nl.tmpdir)(),"preemptive-compaction-debug.log");function pt(...e){if(Hm){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1378
+ `;Cl.appendFileSync(Wm,t)}}var Cn=new Map;function Gm(){let e=Date.now(),t=1800*1e3;for(let[n,o]of Cn)e-o.lastWarningTime>t&&Cn.delete(n)}var Ol=!1;function Pl(e){return Math.ceil(e.length/bn)}function Bm(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=lr,i=Pl(e),s=i/r,c=s>=n,a=s>=o,l="none";return a?l="compact":c&&(l="warn"),{totalTokens:i,usageRatio:s,isWarning:c,isCritical:a,action:l}}function An(e){let t=Cn.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},Cn.set(e,t)),t}function qm(e,t){let n=An(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,i=Date.now();return i-n.lastWarningTime<o?(pt("skipping warning - cooldown active",{sessionId:e,elapsed:i-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(pt("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Ym(e){let t=An(e);t.lastWarningTime=Date.now(),t.warningCount++}function xl(e){return pt("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(Ol||(Ol=!0,setInterval(Gm,300*1e3)),{postToolUse:t=>{if(!t.tool_response)return null;let n=t.tool_name.toLowerCase();if(!["read","grep","glob","bash","webfetch"].includes(n))return null;let r=Pl(t.tool_response),i=An(t.session_id);i.estimatedTokens+=r,pt("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:i.estimatedTokens});let s=Bm("x".repeat(i.estimatedTokens*bn),e);return!s.isWarning||!qm(t.session_id,e)?null:(Ym(t.session_id),pt("injecting context warning",{sessionId:t.session_id,usageRatio:s.usageRatio,isCritical:s.isCritical}),e?.customMessage?e.customMessage:s.isCritical?dr:ur)},stop:t=>{let n=An(t.session_id);return n.warningCount>0&&(pt("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var de=require("fs"),Ll=require("path");var fr=require("path"),Dl=require("os"),Vm=(0,fr.join)((0,Dl.homedir)(),".olympus"),Nn=(0,fr.join)(Vm,"agent-usage-reminder"),pr=new Set(["grep","safe_grep","glob","safe_glob","webfetch","context7_resolve-library-id","context7_query-docs","websearch_web_search_exa","context7_get-library-docs","grep_app_searchgithub"]),mr=new Set(["task","call_omo_agent","olympus_task"]),gr=`
1379
1379
  [Agent Usage Reminder]
1380
1380
 
1381
1381
  You called a search/fetch tool directly without leveraging specialized agents.
@@ -1399,7 +1399,7 @@ WHY:
1399
1399
  - Reduces context window usage in main session
1400
1400
 
1401
1401
  ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
1402
- `;function pr(e){return(0,Nl.join)(bn,`${e}.json`)}function mr(e){let t=pr(e);if(!(0,ue.existsSync)(t))return null;try{let n=(0,ue.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Cn(e){(0,ue.existsSync)(bn)||(0,ue.mkdirSync)(bn,{recursive:!0});let t=pr(e.sessionID);(0,ue.writeFileSync)(t,JSON.stringify(e,null,2))}function gr(e){let t=pr(e);(0,ue.existsSync)(t)&&(0,ue.unlinkSync)(t)}function Hm(e){let t=e||process.cwd();return bt(t)?.active?{active:!0,mode:"ascent"}:ct(t)?.active?{active:!0,mode:"olympus"}:We(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function Wm(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function Gm(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
1402
+ `;function hr(e){return(0,Ll.join)(Nn,`${e}.json`)}function kr(e){let t=hr(e);if(!(0,de.existsSync)(t))return null;try{let n=(0,de.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Pn(e){(0,de.existsSync)(Nn)||(0,de.mkdirSync)(Nn,{recursive:!0});let t=hr(e.sessionID);(0,de.writeFileSync)(t,JSON.stringify(e,null,2))}function yr(e){let t=hr(e);(0,de.existsSync)(t)&&(0,de.unlinkSync)(t)}function Km(e){let t=e||process.cwd();return Nt(t)?.active?{active:!0,mode:"ascent"}:lt(t)?.active?{active:!0,mode:"olympus"}:Ge(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function Jm(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function zm(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
1403
1403
 
1404
1404
  [${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
1405
1405
 
@@ -1425,27 +1425,29 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
1425
1425
 
1426
1426
  ---
1427
1427
 
1428
- `}function Pl(){let e=new Map,t=new Map;function n(a){if(!e.has(a)){let u=mr(a)??{sessionID:a,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(a,u)}return e.get(a)}function o(a){let l=n(a);l.agentUsed=!0,l.updatedAt=Date.now(),Cn(l)}function r(a){e.delete(a),gr(a),t.delete(a)}function i(a,l,u){let d=t.get(a)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:a};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(a,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(a,d)),d.consecutiveCount)}return{"tool.execute.after":async(a,l)=>{let{tool:u,sessionID:d}=a,f=u.toLowerCase();if(dr.has(f)){o(d),i(d,f,"");return}let g=a.properties||{},m=Wm(g),p=i(d,f,m||""),h=Hm();if(h.active){let T=Gm(p,h.mode);if(T){l.output=T+l.output;return}}if(!ur.has(f))return;let y=n(d);y.agentUsed||(l.output+=fr,y.reminderCount++,y.updatedAt=Date.now(),Cn(y))},event:async({event:a})=>{let l=a.properties;if(a.type==="session.deleted"){let u=l?.info;u?.id&&r(u.id)}if(a.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&r(u)}}}}function xl(){let e=process.cwd(),t=tl();v({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async a=>{if(!a.toolName||!a.toolOutput)return{continue:!0};let l=t.afterToolExecute({tool:a.toolName,sessionId:a.sessionId||"",callId:""},{title:"",output:String(a.toolOutput),metadata:void 0});return l.output!==String(a.toolOutput)?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.output.substring(String(a.toolOutput).length)}}:{continue:!0}}});let n=sl();v({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async a=>{if(!a.toolName)return{continue:!0};let l=n.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let o=kl();v({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async a=>{if(!a.toolName)return{continue:!0};let l=o.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let r=El();v({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async a=>{if(!a.toolName||a.toolName.toLowerCase()!=="read")return{continue:!0};let l=r.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let i=bl();v({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async a=>{if(!a.toolName)return{continue:!0};let l=i.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let s=Pl();v({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async a=>{if(!a.toolName)return{continue:!0};let l={title:"",output:a.toolOutput?String(a.toolOutput):"",metadata:void 0};await s["tool.execute.after"]({tool:a.toolName,sessionID:a.sessionId||"",callID:""},l);let u=a.toolOutput?String(a.toolOutput):"";return l.output!==u?{continue:!0,message:l.output.substring(u.length)}:{continue:!0}}});let c=Sn(e);v({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async a=>{if(!a.toolName)return{continue:!0};let l=c.postTool(a.toolName,a.toolInput||{},a.toolOutput?String(a.toolOutput):"");return l.continue?l.modifiedOutput?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.modifiedOutput}}:l.message?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.message}}:{continue:!0}:{continue:!1,stopReason:l.message}}})}var ql=require("node:fs");var N=require("node:fs"),oe=require("node:path");var pt=require("node:path"),Nn=require("node:os");function Bm(){return process.env.XDG_DATA_HOME??(0,pt.join)((0,Nn.homedir)(),".local","share")}function qm(){return(0,pt.join)(Bm(),"claude-code","storage")}var Dl=qm(),Ft=(0,pt.join)(Dl,"message"),mt=(0,pt.join)(Dl,"part"),He=new Set(["thinking","redacted_thinking","reasoning"]),Ll=new Set(["step-start","step-finish"]);var de="[user interrupted]",Pn={tool_result_missing:{title:"Tool Crash Recovery",message:"Injecting cancelled tool results..."},thinking_block_order:{title:"Thinking Block Recovery",message:"Fixing message structure..."},thinking_disabled_violation:{title:"Thinking Strip Recovery",message:"Stripping thinking blocks..."},empty_content:{title:"Empty Content Recovery",message:"Adding placeholder content..."}};var Ml=process.env.SESSION_RECOVERY_DEBUG==="1",$l=(0,pt.join)((0,Nn.tmpdir)(),"session-recovery-debug.log");function Ym(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function Vm(e){if(!(0,N.existsSync)(Ft))return"";let t=(0,oe.join)(Ft,e);if((0,N.existsSync)(t))return t;for(let n of(0,N.readdirSync)(Ft)){let o=(0,oe.join)(Ft,n,e);if((0,N.existsSync)(o))return o}return""}function Ae(e){let t=Vm(e);if(!t||!(0,N.existsSync)(t))return[];let n=[];for(let o of(0,N.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,N.readFileSync)((0,oe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n.sort((o,r)=>{let i=o.time?.created??0,s=r.time?.created??0;return i!==s?i-s:o.id.localeCompare(r.id)})}function Te(e){let t=(0,oe.join)(mt,e);if(!(0,N.existsSync)(t))return[];let n=[];for(let o of(0,N.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,N.readFileSync)((0,oe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Fl(e){return He.has(e.type)||Ll.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Ul(e){return Te(e).some(Fl)}function Ut(e,t,n){let o=(0,oe.join)(mt,t);(0,N.existsSync)(o)||(0,N.mkdirSync)(o,{recursive:!0});let r=Ym(),i={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,N.writeFileSync)((0,oe.join)(o,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function hr(e){let t=Ae(e),n=[];for(let o of t)Ul(o.id)||n.push(o.id);return n}function jl(e,t){let n=Ae(e),o=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let r of o){if(r<0||r>=n.length)continue;let i=n[r];if(!Ul(i.id))return i.id}return null}function kr(e){let t=Ae(e),n=[];for(let o of t){if(o.role!=="assistant")continue;Te(o.id).some(s=>He.has(s.type))&&n.push(o.id)}return n}function Hl(e){let t=Ae(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=Te(o.id);if(r.length===0)continue;let i=r.some(c=>He.has(c.type)),s=r.some(Fl);i&&!s&&n.push(o.id)}return n}function yr(e){let t=Ae(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=Te(o.id);if(r.length===0)continue;let s=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];He.has(s.type)||n.push(o.id)}return n}function Km(e,t){let n=Ae(e),o=n.findIndex(r=>r.id===t);if(o===-1)return"";for(let r=o-1;r>=0;r--){let i=n[r];if(i.role!=="assistant")continue;let s=Te(i.id);for(let c of s)if(He.has(c.type)){let a=c.thinking,l=c.text,u=a||l;if(u&&u.trim().length>0)return u}}return""}function Er(e,t){let n=(0,oe.join)(mt,t);(0,N.existsSync)(n)||(0,N.mkdirSync)(n,{recursive:!0});let o=Km(e,t),r="prt_0000000000_thinking",i={id:r,sessionID:e,messageID:t,type:"thinking",thinking:o||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,N.writeFileSync)((0,oe.join)(n,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function Wl(e){let t=(0,oe.join)(mt,e);if(!(0,N.existsSync)(t))return!1;let n=!1;for(let o of(0,N.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,oe.join)(t,o),i=(0,N.readFileSync)(r,"utf-8"),s=JSON.parse(i);He.has(s.type)&&((0,N.unlinkSync)(r),n=!0)}catch{continue}return n}function jt(e,t=de){let n=(0,oe.join)(mt,e);if(!(0,N.existsSync)(n))return!1;let o=!1;for(let r of(0,N.readdirSync)(n))if(r.endsWith(".json"))try{let i=(0,oe.join)(n,r),s=(0,N.readFileSync)(i,"utf-8"),c=JSON.parse(s);if(c.type==="text"){let a=c;a.text?.trim()||(a.text=t,a.synthetic=!0,(0,N.writeFileSync)(i,JSON.stringify(a,null,2)),o=!0)}}catch{continue}return o}function Gl(e){let t=Ae(e),n=[];for(let o of t)Te(o.id).some(s=>s.type!=="text"?!1:!s.text?.trim())&&n.push(o.id);return n}function Bl(e,t){let n=Ae(e);if(t<0||t>=n.length)return null;let o=n[t];if(o.role!=="assistant")return null;let r=Te(o.id);if(r.length===0)return null;let s=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];return He.has(s.type)?null:o.id}function V(...e){if(Ml){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1429
- `;(0,ql.appendFileSync)($l,t)}}function Yl(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Vl(e){let n=Yl(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Kl(e){let t=Yl(e);return t.includes("tool_use")&&t.includes("tool_result")?"tool_result_missing":t.includes("thinking")&&(t.includes("first block")||t.includes("must start with")||t.includes("preceeding")||t.includes("final block")||t.includes("cannot be thinking")||t.includes("expected")&&t.includes("found"))?"thinking_block_order":t.includes("thinking is disabled")&&t.includes("cannot contain")?"thinking_disabled_violation":t.includes("empty")&&(t.includes("content")||t.includes("message"))?"empty_content":null}function Jm(e){return Kl(e)!==null}function zm(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Xm(e,t){V("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=Te(t.info.id).map(i=>({type:i.type==="tool"?"tool_use":i.type,id:"callID"in i?i.callID:i.id,name:"tool"in i?i.tool:void 0,input:"state"in i?i.state?.input:void 0})));let o=zm(n);return o.length===0?(V("No tool_use IDs found"),!1):(V("Found tool_use IDs to inject results for",o),!0)}async function Qm(e,t,n){V("recoverThinkingBlockOrder",{sessionID:e});let o=Vl(n);if(o!==null){let s=Bl(e,o);if(s)return V("Found target message by index",{targetIndex:o,targetMessageID:s}),Er(e,s)}let r=yr(e);if(r.length===0)return V("No orphan thinking messages found"),!1;V("Found orphan thinking messages",r);let i=!1;for(let s of r)Er(e,s)&&(i=!0);return i}async function Zm(e,t){V("recoverThinkingDisabledViolation",{sessionID:e});let n=kr(e);if(n.length===0)return V("No messages with thinking blocks found"),!1;V("Found messages with thinking blocks",n);let o=!1;for(let r of n)Wl(r)&&(o=!0);return o}async function eg(e,t,n){V("recoverEmptyContentMessage",{sessionID:e});let o=Vl(n),r=t.info?.id,i=!1,s=Gl(e);for(let l of s)jt(l,de)&&(i=!0);let c=Hl(e);for(let l of c)Ut(e,l,de)&&(i=!0);if(o!==null){let l=jl(e,o);if(l&&(jt(l,de)||Ut(e,l,de)))return!0}if(r&&(jt(r,de)||Ut(e,r,de)))return!0;let a=hr(e);for(let l of a)jt(l,de)&&(i=!0),Ut(e,l,de)&&(i=!0);return i}async function tg(e,t,n,o){V("handleSessionRecovery",{sessionID:e,error:t});let r=Kl(t);if(!r)return V("Not a recoverable error"),{attempted:!1,success:!1};V("Detected recoverable error type",r);try{let i=!1,s=n||{info:{},parts:[]};switch(r){case"tool_result_missing":i=await Xm(e,s);break;case"thinking_block_order":i=await Qm(e,s,t);break;case"thinking_disabled_violation":i=await Zm(e,s);break;case"empty_content":i=await eg(e,s,t);break}V("Recovery result",{errorType:r,success:i});let c=o?.customMessages?.[r]||Pn[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:i,message:i?c:void 0,errorType:r}}catch(i){return V("Recovery failed with error",i),{attempted:!0,success:!1,errorType:r}}}function Jl(e){return V("createSessionRecoveryHook",{config:e}),{onError:async t=>tg(t.session_id,t.error,t.message,e),isRecoverable:t=>Jm(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Pn[t]?.message}}}function zl(){let e=Jl();v({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var fe=require("fs"),xn=require("path"),Xl=require("os");var Ht=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let i=this.config?.defaultConcurrency;return i!==void 0?i===0?1/0:i:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let i=this.queues.get(t)??[];i.push(r),this.queues.set(t,i)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var ng=1800*1e3,gt=(0,xn.join)((0,Xl.homedir)(),".claude",".olympus","background-tasks"),Dn=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Ht(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,fe.existsSync)(gt)||(0,fe.mkdirSync)(gt,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,xn.join)(gt,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,fe.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,fe.existsSync)(n)&&(0,fe.unlinkSync)(n)}loadPersistedTasks(){if((0,fe.existsSync)(gt))try{let{readdirSync:t}=require("fs"),n=t(gt);for(let o of n)if(o.endsWith(".json"))try{let r=(0,xn.join)(gt,o),i=(0,fe.readFileSync)(r,"utf-8"),s=JSON.parse(i);s.startedAt=new Date(s.startedAt),s.completedAt&&(s.completedAt=new Date(s.completedAt)),s.progress?.lastUpdate&&(s.progress.lastUpdate=new Date(s.progress.lastUpdate)),s.progress?.lastMessageAt&&(s.progress.lastMessageAt=new Date(s.progress.lastMessageAt)),this.tasks.set(s.id,s)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??ng;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let i=r.filter(s=>t-s.startedAt.getTime()<=n);i.length===0?this.notifications.delete(o):i.length!==r.length&&this.notifications.set(o,i)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(a=>a.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let i=this.generateTaskId(),s=`ses_${this.generateTaskId()}`,c={id:i,sessionId:s,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(i,c),this.persistTask(c),c}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let i=this.tasks.get(t);i&&(i.status=n,o&&(i.result=o),r&&(i.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(i.completedAt=new Date,i.concurrencyKey&&this.concurrencyManager.release(i.concurrencyKey),this.markForNotification(i)),this.persistTask(i))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(i=>i.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),i=Math.floor(r/60),s=Math.floor(i/60);return s>0?`${s}h ${i%60}m ${r%60}s`:i>0?`${i}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let i=this.formatDuration(r.startedAt,r.completedAt),s=r.status.toUpperCase(),c=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${s}] ${r.description} - ${i}${c}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
1430
- `)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},Sr;function Tr(e){return Sr||(Sr=new Dn(e)),Sr}function og(e){let t=e.status.toUpperCase(),n=rg(e.startedAt,e.completedAt),r=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&r.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let i=e.result.substring(0,200),s=e.result.length>200?"...":"";r.push(` Result: ${i}${s}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
1431
- `)}function rg(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),i=Math.floor(r/60);return i>0?`${i}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function ig(e){if(e.length===0)return"";let t=e.length===1?`
1428
+ `}function Ml(){let e=new Map,t=new Map;function n(a){if(!e.has(a)){let u=kr(a)??{sessionID:a,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(a,u)}return e.get(a)}function o(a){let l=n(a);l.agentUsed=!0,l.updatedAt=Date.now(),Pn(l)}function r(a){e.delete(a),yr(a),t.delete(a)}function i(a,l,u){let d=t.get(a)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:a};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(a,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(a,d)),d.consecutiveCount)}return{"tool.execute.after":async(a,l)=>{let{tool:u,sessionID:d}=a,f=u.toLowerCase();if(mr.has(f)){o(d),i(d,f,"");return}let g=a.properties||{},m=Jm(g),p=i(d,f,m||""),h=Km();if(h.active){let w=zm(p,h.mode);if(w){l.output=w+l.output;return}}if(!pr.has(f))return;let y=n(d);y.agentUsed||(l.output+=gr,y.reminderCount++,y.updatedAt=Date.now(),Pn(y))},event:async({event:a})=>{let l=a.properties;if(a.type==="session.deleted"){let u=l?.info;u?.id&&r(u.id)}if(a.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&r(u)}}}}function $l(){let e=process.cwd(),t=il();R({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async a=>{if(!a.toolName||!a.toolOutput)return{continue:!0};let l=t.afterToolExecute({tool:a.toolName,sessionId:a.sessionId||"",callId:""},{title:"",output:String(a.toolOutput),metadata:void 0});return l.output!==String(a.toolOutput)?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.output.substring(String(a.toolOutput).length)}}:{continue:!0}}});let n=ul();R({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async a=>{if(!a.toolName)return{continue:!0};let l=n.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let o=Tl();R({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async a=>{if(!a.toolName)return{continue:!0};let l=o.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let r=_l();R({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async a=>{if(!a.toolName||a.toolName.toLowerCase()!=="read")return{continue:!0};let l=r.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let i=xl();R({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async a=>{if(!a.toolName)return{continue:!0};let l=i.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let s=Ml();R({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async a=>{if(!a.toolName)return{continue:!0};let l={title:"",output:a.toolOutput?String(a.toolOutput):"",metadata:void 0};await s["tool.execute.after"]({tool:a.toolName,sessionID:a.sessionId||"",callID:""},l);let u=a.toolOutput?String(a.toolOutput):"";return l.output!==u?{continue:!0,message:l.output.substring(u.length)}:{continue:!0}}});let c=wn(e);R({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async a=>{if(!a.toolName)return{continue:!0};let l=c.postTool(a.toolName,a.toolInput||{},a.toolOutput?String(a.toolOutput):"");return l.continue?l.modifiedOutput?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.modifiedOutput}}:l.message?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.message}}:{continue:!0}:{continue:!1,stopReason:l.message}}})}var Jl=require("node:fs");var P=require("node:fs"),re=require("node:path");var mt=require("node:path"),xn=require("node:os");function Xm(){return process.env.XDG_DATA_HOME??(0,mt.join)((0,xn.homedir)(),".local","share")}function Qm(){return(0,mt.join)(Xm(),"claude-code","storage")}var Fl=Qm(),jt=(0,mt.join)(Fl,"message"),gt=(0,mt.join)(Fl,"part"),We=new Set(["thinking","redacted_thinking","reasoning"]),Ul=new Set(["step-start","step-finish"]);var fe="[user interrupted]",Dn={tool_result_missing:{title:"Tool Crash Recovery",message:"Injecting cancelled tool results..."},thinking_block_order:{title:"Thinking Block Recovery",message:"Fixing message structure..."},thinking_disabled_violation:{title:"Thinking Strip Recovery",message:"Stripping thinking blocks..."},empty_content:{title:"Empty Content Recovery",message:"Adding placeholder content..."}};var jl=process.env.SESSION_RECOVERY_DEBUG==="1",Hl=(0,mt.join)((0,xn.tmpdir)(),"session-recovery-debug.log");function Zm(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function eg(e){if(!(0,P.existsSync)(jt))return"";let t=(0,re.join)(jt,e);if((0,P.existsSync)(t))return t;for(let n of(0,P.readdirSync)(jt)){let o=(0,re.join)(jt,n,e);if((0,P.existsSync)(o))return o}return""}function Ce(e){let t=eg(e);if(!t||!(0,P.existsSync)(t))return[];let n=[];for(let o of(0,P.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,P.readFileSync)((0,re.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n.sort((o,r)=>{let i=o.time?.created??0,s=r.time?.created??0;return i!==s?i-s:o.id.localeCompare(r.id)})}function we(e){let t=(0,re.join)(gt,e);if(!(0,P.existsSync)(t))return[];let n=[];for(let o of(0,P.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,P.readFileSync)((0,re.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Wl(e){return We.has(e.type)||Ul.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Gl(e){return we(e).some(Wl)}function Ht(e,t,n){let o=(0,re.join)(gt,t);(0,P.existsSync)(o)||(0,P.mkdirSync)(o,{recursive:!0});let r=Zm(),i={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,P.writeFileSync)((0,re.join)(o,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function Er(e){let t=Ce(e),n=[];for(let o of t)Gl(o.id)||n.push(o.id);return n}function Bl(e,t){let n=Ce(e),o=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let r of o){if(r<0||r>=n.length)continue;let i=n[r];if(!Gl(i.id))return i.id}return null}function Sr(e){let t=Ce(e),n=[];for(let o of t){if(o.role!=="assistant")continue;we(o.id).some(s=>We.has(s.type))&&n.push(o.id)}return n}function ql(e){let t=Ce(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=we(o.id);if(r.length===0)continue;let i=r.some(c=>We.has(c.type)),s=r.some(Wl);i&&!s&&n.push(o.id)}return n}function Tr(e){let t=Ce(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=we(o.id);if(r.length===0)continue;let s=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];We.has(s.type)||n.push(o.id)}return n}function tg(e,t){let n=Ce(e),o=n.findIndex(r=>r.id===t);if(o===-1)return"";for(let r=o-1;r>=0;r--){let i=n[r];if(i.role!=="assistant")continue;let s=we(i.id);for(let c of s)if(We.has(c.type)){let a=c.thinking,l=c.text,u=a||l;if(u&&u.trim().length>0)return u}}return""}function wr(e,t){let n=(0,re.join)(gt,t);(0,P.existsSync)(n)||(0,P.mkdirSync)(n,{recursive:!0});let o=tg(e,t),r="prt_0000000000_thinking",i={id:r,sessionID:e,messageID:t,type:"thinking",thinking:o||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,P.writeFileSync)((0,re.join)(n,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function Yl(e){let t=(0,re.join)(gt,e);if(!(0,P.existsSync)(t))return!1;let n=!1;for(let o of(0,P.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,re.join)(t,o),i=(0,P.readFileSync)(r,"utf-8"),s=JSON.parse(i);We.has(s.type)&&((0,P.unlinkSync)(r),n=!0)}catch{continue}return n}function Wt(e,t=fe){let n=(0,re.join)(gt,e);if(!(0,P.existsSync)(n))return!1;let o=!1;for(let r of(0,P.readdirSync)(n))if(r.endsWith(".json"))try{let i=(0,re.join)(n,r),s=(0,P.readFileSync)(i,"utf-8"),c=JSON.parse(s);if(c.type==="text"){let a=c;a.text?.trim()||(a.text=t,a.synthetic=!0,(0,P.writeFileSync)(i,JSON.stringify(a,null,2)),o=!0)}}catch{continue}return o}function Vl(e){let t=Ce(e),n=[];for(let o of t)we(o.id).some(s=>s.type!=="text"?!1:!s.text?.trim())&&n.push(o.id);return n}function Kl(e,t){let n=Ce(e);if(t<0||t>=n.length)return null;let o=n[t];if(o.role!=="assistant")return null;let r=we(o.id);if(r.length===0)return null;let s=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];return We.has(s.type)?null:o.id}function K(...e){if(jl){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1429
+ `;(0,Jl.appendFileSync)(Hl,t)}}function zl(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Xl(e){let n=zl(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Ql(e){let t=zl(e);return t.includes("tool_use")&&t.includes("tool_result")?"tool_result_missing":t.includes("thinking")&&(t.includes("first block")||t.includes("must start with")||t.includes("preceeding")||t.includes("final block")||t.includes("cannot be thinking")||t.includes("expected")&&t.includes("found"))?"thinking_block_order":t.includes("thinking is disabled")&&t.includes("cannot contain")?"thinking_disabled_violation":t.includes("empty")&&(t.includes("content")||t.includes("message"))?"empty_content":null}function ng(e){return Ql(e)!==null}function og(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function rg(e,t){K("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=we(t.info.id).map(i=>({type:i.type==="tool"?"tool_use":i.type,id:"callID"in i?i.callID:i.id,name:"tool"in i?i.tool:void 0,input:"state"in i?i.state?.input:void 0})));let o=og(n);return o.length===0?(K("No tool_use IDs found"),!1):(K("Found tool_use IDs to inject results for",o),!0)}async function ig(e,t,n){K("recoverThinkingBlockOrder",{sessionID:e});let o=Xl(n);if(o!==null){let s=Kl(e,o);if(s)return K("Found target message by index",{targetIndex:o,targetMessageID:s}),wr(e,s)}let r=Tr(e);if(r.length===0)return K("No orphan thinking messages found"),!1;K("Found orphan thinking messages",r);let i=!1;for(let s of r)wr(e,s)&&(i=!0);return i}async function sg(e,t){K("recoverThinkingDisabledViolation",{sessionID:e});let n=Sr(e);if(n.length===0)return K("No messages with thinking blocks found"),!1;K("Found messages with thinking blocks",n);let o=!1;for(let r of n)Yl(r)&&(o=!0);return o}async function ag(e,t,n){K("recoverEmptyContentMessage",{sessionID:e});let o=Xl(n),r=t.info?.id,i=!1,s=Vl(e);for(let l of s)Wt(l,fe)&&(i=!0);let c=ql(e);for(let l of c)Ht(e,l,fe)&&(i=!0);if(o!==null){let l=Bl(e,o);if(l&&(Wt(l,fe)||Ht(e,l,fe)))return!0}if(r&&(Wt(r,fe)||Ht(e,r,fe)))return!0;let a=Er(e);for(let l of a)Wt(l,fe)&&(i=!0),Ht(e,l,fe)&&(i=!0);return i}async function cg(e,t,n,o){K("handleSessionRecovery",{sessionID:e,error:t});let r=Ql(t);if(!r)return K("Not a recoverable error"),{attempted:!1,success:!1};K("Detected recoverable error type",r);try{let i=!1,s=n||{info:{},parts:[]};switch(r){case"tool_result_missing":i=await rg(e,s);break;case"thinking_block_order":i=await ig(e,s,t);break;case"thinking_disabled_violation":i=await sg(e,s);break;case"empty_content":i=await ag(e,s,t);break}K("Recovery result",{errorType:r,success:i});let c=o?.customMessages?.[r]||Dn[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:i,message:i?c:void 0,errorType:r}}catch(i){return K("Recovery failed with error",i),{attempted:!0,success:!1,errorType:r}}}function Zl(e){return K("createSessionRecoveryHook",{config:e}),{onError:async t=>cg(t.session_id,t.error,t.message,e),isRecoverable:t=>ng(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Dn[t]?.message}}}function eu(){let e=Zl();R({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var pe=require("fs"),Ln=require("path"),tu=require("os");var Gt=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let i=this.config?.defaultConcurrency;return i!==void 0?i===0?1/0:i:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let i=this.queues.get(t)??[];i.push(r),this.queues.set(t,i)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var lg=1800*1e3,ht=(0,Ln.join)((0,tu.homedir)(),".claude",".olympus","background-tasks"),Mn=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Gt(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,pe.existsSync)(ht)||(0,pe.mkdirSync)(ht,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,Ln.join)(ht,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,pe.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,pe.existsSync)(n)&&(0,pe.unlinkSync)(n)}loadPersistedTasks(){if((0,pe.existsSync)(ht))try{let{readdirSync:t}=require("fs"),n=t(ht);for(let o of n)if(o.endsWith(".json"))try{let r=(0,Ln.join)(ht,o),i=(0,pe.readFileSync)(r,"utf-8"),s=JSON.parse(i);s.startedAt=new Date(s.startedAt),s.completedAt&&(s.completedAt=new Date(s.completedAt)),s.progress?.lastUpdate&&(s.progress.lastUpdate=new Date(s.progress.lastUpdate)),s.progress?.lastMessageAt&&(s.progress.lastMessageAt=new Date(s.progress.lastMessageAt)),this.tasks.set(s.id,s)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??lg;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let i=r.filter(s=>t-s.startedAt.getTime()<=n);i.length===0?this.notifications.delete(o):i.length!==r.length&&this.notifications.set(o,i)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(a=>a.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let i=this.generateTaskId(),s=`ses_${this.generateTaskId()}`,c={id:i,sessionId:s,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(i,c),this.persistTask(c),c}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let i=this.tasks.get(t);i&&(i.status=n,o&&(i.result=o),r&&(i.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(i.completedAt=new Date,i.concurrencyKey&&this.concurrencyManager.release(i.concurrencyKey),this.markForNotification(i)),this.persistTask(i))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(i=>i.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),i=Math.floor(r/60),s=Math.floor(i/60);return s>0?`${s}h ${i%60}m ${r%60}s`:i>0?`${i}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let i=this.formatDuration(r.startedAt,r.completedAt),s=r.status.toUpperCase(),c=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${s}] ${r.description} - ${i}${c}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
1430
+ `)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},_r;function Or(e){return _r||(_r=new Mn(e)),_r}function ug(e){let t=e.status.toUpperCase(),n=dg(e.startedAt,e.completedAt),r=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&r.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let i=e.result.substring(0,200),s=e.result.length>200?"...":"";r.push(` Result: ${i}${s}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
1431
+ `)}function dg(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),i=Math.floor(r/60);return i>0?`${i}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function fg(e){if(e.length===0)return"";let t=e.length===1?`
1432
1432
  [BACKGROUND TASK COMPLETED]
1433
1433
  `:`
1434
1434
  [${e.length} BACKGROUND TASKS COMPLETED]
1435
- `,n=e.map(o=>og(o)).join(`
1435
+ `,n=e.map(o=>ug(o)).join(`
1436
1436
 
1437
1437
  `);return`${t}
1438
1438
  ${n}
1439
- `}function sg(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let i=(n?.formatNotification??ig)(o);return{hasNotifications:!0,tasks:o,message:i}}function Ql(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Tr(),r=sg(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function Zl(){v({name:"backgroundNotification",event:"Notification",priority:10,handler:async e=>{let t={sessionId:e.sessionId,directory:e.directory,event:e.event?{type:e.event.type,properties:e.event.properties}:void 0},n=await Ql(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var _r=null,wr=!1;async function ag(){if(!wr)try{let{encode:e}=await import("gpt-tokenizer");_r=e,wr=!0}catch{wr=!0}}function cg(e){return Math.ceil(e.length/4)}async function Xe(e){if(!e||e.length===0)return 0;await ag();try{if(_r)return _r(e).length}catch{}return cg(e)}async function eu(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return Xe(n.content);if("output"in n&&typeof n.output=="string")return Xe(n.output);if("text"in n&&typeof n.text=="string")return Xe(n.text);if("result"in n&&typeof n.result=="string")return Xe(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return Xe(t)}var Or=[{model_pattern:"claude-opus",input_per_million:15,output_per_million:75,effective_date:"2025-01-01"},{model_pattern:"claude-sonnet",input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},{model_pattern:"claude-haiku",input_per_million:.25,output_per_million:1.25,effective_date:"2025-01-01"}];function tu(e,t,n,o=Or){let r=o.find(c=>new RegExp(c.model_pattern,"i").test(n));if(!r){let c=o.find(u=>u.model_pattern==="claude-sonnet")||{input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},a=e/1e6*c.input_per_million,l=t/1e6*c.output_per_million;return{inputCost:a,outputCost:l,totalCost:a+l,pricingVersion:c.effective_date}}let i=e/1e6*r.input_per_million,s=t/1e6*r.output_per_million;return{inputCost:i,outputCost:s,totalCost:i+s,pricingVersion:r.effective_date}}var ou=require("crypto");function lg(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function ug(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function nu(e,t=1e4){return e.token_budget?(e.token_budget.input_tokens===void 0&&(e.token_budget.input_tokens=0),e.token_budget.output_tokens===void 0&&(e.token_budget.output_tokens=0)):e.token_budget={session_baseline:t,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e}function ru(){v({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=lg(e);if(!t)return{continue:!0};let n=await Xe(t),o=te(e.directory,e.sessionId);nu(o);let r=ug(e);r&&o.token_budget&&(o.token_budget.current_model=r),o.token_budget&&(o.token_budget.input_tokens+=n,o.token_budget.current_usage+=n,J(e.directory,o))}catch(t){console.error("[Olympus Learning Capture] Error in prompt handler:",t)}return{continue:!0}}}),v({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{try{if(!e.directory||!e.toolName)return{continue:!0};let t=e.toolOutput?await eu(e.toolOutput):0,n=te(e.directory,e.sessionId);nu(n),n.token_budget&&(n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,J(e.directory,n))}catch(t){console.error("[Olympus Learning Capture] Error in tool use handler:",t)}return{continue:!0}}}),v({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=te(e.directory,e.sessionId);if(!t.token_budget)return{continue:!0};let n=t.token_budget.current_usage,o=t.token_budget.input_tokens||0,r=t.token_budget.output_tokens||0;if(n===0)return{continue:!0};let i=t.token_budget.current_model||"unknown",s={input_tokens:o,output_tokens:r,total_tokens:n,estimated:!0,model:i},c={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=tu(o,r,i);c.input_cost=l.inputCost,c.output_cost=l.outputCost,c.total_cost=l.totalCost,c.pricing_version=l.pricingVersion}catch{}let a={id:(0,ou.randomUUID)(),timestamp:new Date().toISOString(),session_id:t.session_id,project_path:e.directory,event_type:"success",user_message:"Session completed",feedback_category:"praise",confidence:.5,token_usage:s,cost_estimate:c,agent_used:t.pending_completion?.agent_used,original_task:t.pending_completion?.task_description};if(Pe(a),t.pending_completion?.agent_used){let l=li();ui(t.pending_completion.agent_used,l)}t.token_budget.current_usage=0,t.token_budget.input_tokens=0,t.token_budget.output_tokens=0,t.token_budget.warning_issued=!1,t.token_budget.started_at=new Date().toISOString(),delete t.token_budget.current_model,J(e.directory,t)}catch(t){console.error("[Olympus Learning Capture] Error in stop handler:",t)}return{continue:!0}}})}function iu(){v({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=te(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let o=e.toolOutput;o.token_usage&&typeof o.token_usage=="object"&&(n=o.token_usage.total_tokens??0)}if(n>0&&Ei(t,n),Ti(t)){let o=t.token_budget,r=(o.current_usage/1e3).toFixed(1),i=(o.session_baseline/1e3).toFixed(0),s=(o.current_usage/o.session_baseline).toFixed(2);return Si(t),J(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${s}x baseline of ${i}k).
1439
+ `}function pg(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let i=(n?.formatNotification??fg)(o);return{hasNotifications:!0,tasks:o,message:i}}function nu(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Or(),r=pg(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function ou(){R({name:"backgroundNotification",event:"Notification",priority:10,handler:async e=>{let t={sessionId:e.sessionId,directory:e.directory,event:e.event?{type:e.event.type,properties:e.event.properties}:void 0},n=await nu(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var Rr=null,vr=!1;async function mg(){if(!vr)try{let{encode:e}=await import("gpt-tokenizer");Rr=e,vr=!0}catch{vr=!0}}function gg(e){return Math.ceil(e.length/4)}async function Qe(e){if(!e||e.length===0)return 0;await mg();try{if(Rr)return Rr(e).length}catch{}return gg(e)}async function ru(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return Qe(n.content);if("output"in n&&typeof n.output=="string")return Qe(n.output);if("text"in n&&typeof n.text=="string")return Qe(n.text);if("result"in n&&typeof n.result=="string")return Qe(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return Qe(t)}var Ir=[{model_pattern:"claude-opus",input_per_million:15,output_per_million:75,effective_date:"2025-01-01"},{model_pattern:"claude-sonnet",input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},{model_pattern:"claude-haiku",input_per_million:.25,output_per_million:1.25,effective_date:"2025-01-01"}];function iu(e,t,n,o=Ir){let r=o.find(c=>new RegExp(c.model_pattern,"i").test(n));if(!r){let c=o.find(u=>u.model_pattern==="claude-sonnet")||{input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},a=e/1e6*c.input_per_million,l=t/1e6*c.output_per_million;return{inputCost:a,outputCost:l,totalCost:a+l,pricingVersion:c.effective_date}}let i=e/1e6*r.input_per_million,s=t/1e6*r.output_per_million;return{inputCost:i,outputCost:s,totalCost:i+s,pricingVersion:r.effective_date}}var cu=require("crypto"),kt=F(require("fs"),1),$n=F(require("path"),1),lu=F(require("os"),1),uu=process.env.OLYMPUS_DEBUG_HOOKS==="1",su=$n.join(lu.homedir(),".claude","olympus","learning","hooks-debug.log");function E(e,t,n){if(uu)try{let r=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?r+=`
1440
+ ${JSON.stringify(n,null,2)}`:r+=` ${n}`),r+=`
1441
+ `;let i=$n.dirname(su);kt.existsSync(i)||kt.mkdirSync(i,{recursive:!0}),kt.appendFileSync(su,r,"utf8")}catch(o){console.error("[Olympus Debug] Failed to write debug log:",o)}}function br(e,t){uu&&E(e,"Context received",{directory:t.directory,sessionId:t.sessionId,hasPrompt:!!t.prompt,promptLength:t.prompt?.length||0,hasMessage:!!t.message,messageModel:t.message?.model,toolName:t.toolName,hasToolOutput:!!t.toolOutput,toolOutputType:t.toolOutput?typeof t.toolOutput:void 0,hasParts:!!t.parts,partsLength:t.parts?.length||0})}function hg(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function kg(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function au(e,t=1e4){return e.token_budget?(e.token_budget.input_tokens===void 0&&(e.token_budget.input_tokens=0),e.token_budget.output_tokens===void 0&&(e.token_budget.output_tokens=0)):e.token_budget={session_baseline:t,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e}function du(){R({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{E("learningCapturePrompt","Hook fired"),br("learningCapturePrompt",e);try{if(!e.directory)return E("learningCapturePrompt","No directory in context - skipping"),{continue:!0};E("learningCapturePrompt","Extracting prompt text");let t=hg(e);if(!t)return E("learningCapturePrompt","No prompt text extracted - skipping"),{continue:!0};E("learningCapturePrompt",`Prompt text extracted (${t.length} chars)`),E("learningCapturePrompt","Estimating input tokens");let n=await Qe(t);E("learningCapturePrompt",`Estimated tokens: ${n}`),E("learningCapturePrompt","Loading session state",{directory:e.directory,sessionId:e.sessionId});let o=ne(e.directory,e.sessionId);E("learningCapturePrompt","Session state loaded",{hasTokenBudget:!!o.token_budget,currentUsage:o.token_budget?.current_usage,inputTokens:o.token_budget?.input_tokens,outputTokens:o.token_budget?.output_tokens}),au(o),E("learningCapturePrompt","Token budget ensured");let r=kg(e);if(E("learningCapturePrompt",`Model identifier: ${r||"none"}`),r&&o.token_budget&&(o.token_budget.current_model=r,E("learningCapturePrompt",`Model set in token budget: ${r}`)),o.token_budget){let i=o.token_budget.input_tokens,s=o.token_budget.current_usage;o.token_budget.input_tokens+=n,o.token_budget.current_usage+=n,E("learningCapturePrompt","Tokens accumulated",{addedTokens:n,inputTokens:{before:i,after:o.token_budget.input_tokens},currentUsage:{before:s,after:o.token_budget.current_usage}}),E("learningCapturePrompt","Saving session state"),z(e.directory,o),E("learningCapturePrompt","Session state saved successfully")}else E("learningCapturePrompt","WARNING: No token budget after ensure - this should not happen")}catch(t){E("learningCapturePrompt","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in prompt handler:",t)}return E("learningCapturePrompt","Hook completed"),{continue:!0}}}),R({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{E("learningCaptureTool","Hook fired"),br("learningCaptureTool",e);try{if(!e.directory||!e.toolName)return E("learningCaptureTool","Missing directory or toolName - skipping",{hasDirectory:!!e.directory,hasToolName:!!e.toolName}),{continue:!0};E("learningCaptureTool",`Processing tool: ${e.toolName}`),E("learningCaptureTool","Estimating output tokens from tool result");let t=e.toolOutput?await ru(e.toolOutput):0;E("learningCaptureTool",`Estimated output tokens: ${t}`),E("learningCaptureTool","Loading session state",{directory:e.directory,sessionId:e.sessionId});let n=ne(e.directory,e.sessionId);if(E("learningCaptureTool","Session state loaded",{hasTokenBudget:!!n.token_budget,currentUsage:n.token_budget?.current_usage,inputTokens:n.token_budget?.input_tokens,outputTokens:n.token_budget?.output_tokens}),au(n),E("learningCaptureTool","Token budget ensured"),n.token_budget){let o=n.token_budget.output_tokens,r=n.token_budget.current_usage;n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,E("learningCaptureTool","Tokens accumulated",{addedTokens:t,outputTokens:{before:o,after:n.token_budget.output_tokens},currentUsage:{before:r,after:n.token_budget.current_usage}}),E("learningCaptureTool","Saving session state"),z(e.directory,n),E("learningCaptureTool","Session state saved successfully")}else E("learningCaptureTool","WARNING: No token budget after ensure - this should not happen")}catch(t){E("learningCaptureTool","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in tool use handler:",t)}return E("learningCaptureTool","Hook completed"),{continue:!0}}}),R({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{E("learningCaptureStop","Hook fired"),br("learningCaptureStop",e);try{if(!e.directory)return E("learningCaptureStop","No directory in context - skipping"),{continue:!0};E("learningCaptureStop","Loading session state",{directory:e.directory,sessionId:e.sessionId});let t=ne(e.directory,e.sessionId);if(E("learningCaptureStop","Session state loaded",{hasTokenBudget:!!t.token_budget,currentUsage:t.token_budget?.current_usage,inputTokens:t.token_budget?.input_tokens,outputTokens:t.token_budget?.output_tokens,currentModel:t.token_budget?.current_model}),!t.token_budget)return E("learningCaptureStop","No token budget in session state - skipping (backward compatibility)"),{continue:!0};let n=t.token_budget.current_usage,o=t.token_budget.input_tokens||0,r=t.token_budget.output_tokens||0;if(E("learningCaptureStop","Token totals",{totalTokens:n,inputTokens:o,outputTokens:r}),n===0)return E("learningCaptureStop","No token usage recorded - skipping feedback entry creation"),{continue:!0};let i=t.token_budget.current_model||"unknown";E("learningCaptureStop",`Using model identifier: ${i}`);let s={input_tokens:o,output_tokens:r,total_tokens:n,estimated:!0,model:i};E("learningCaptureStop","Token usage object created",s),E("learningCaptureStop","Calculating cost estimate");let c={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=iu(o,r,i);c.input_cost=l.inputCost,c.output_cost=l.outputCost,c.total_cost=l.totalCost,c.pricing_version=l.pricingVersion,E("learningCaptureStop","Cost calculated successfully",{inputCost:l.inputCost,outputCost:l.outputCost,totalCost:l.totalCost})}catch(l){E("learningCaptureStop","Cost calculation failed (not critical)",{error:l instanceof Error?l.message:String(l)})}let a={id:(0,cu.randomUUID)(),timestamp:new Date().toISOString(),session_id:t.session_id,project_path:e.directory,event_type:"success",user_message:"Session completed",feedback_category:"praise",confidence:.5,token_usage:s,cost_estimate:c,agent_used:t.pending_completion?.agent_used,original_task:t.pending_completion?.task_description};if(E("learningCaptureStop","Feedback entry created",{id:a.id,sessionId:a.session_id,agentUsed:a.agent_used,totalCost:c.total_cost}),E("learningCaptureStop","Appending feedback entry to storage"),xe(a),E("learningCaptureStop","Feedback entry saved successfully"),t.pending_completion?.agent_used){E("learningCaptureStop",`Updating agent performance for: ${t.pending_completion.agent_used}`);let l=pi();mi(t.pending_completion.agent_used,l),E("learningCaptureStop","Agent performance updated successfully")}else E("learningCaptureStop","No agent used - skipping performance update");E("learningCaptureStop","Resetting token budget for next session"),t.token_budget.current_usage=0,t.token_budget.input_tokens=0,t.token_budget.output_tokens=0,t.token_budget.warning_issued=!1,t.token_budget.started_at=new Date().toISOString(),delete t.token_budget.current_model,E("learningCaptureStop","Saving reset session state"),z(e.directory,t),E("learningCaptureStop","Session state saved successfully")}catch(t){E("learningCaptureStop","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in stop handler:",t)}return E("learningCaptureStop","Hook completed"),{continue:!0}}})}function fu(){R({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=ne(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let o=e.toolOutput;o.token_usage&&typeof o.token_usage=="object"&&(n=o.token_usage.total_tokens??0)}if(n>0&&_i(t,n),vi(t)){let o=t.token_budget,r=(o.current_usage/1e3).toFixed(1),i=(o.session_baseline/1e3).toFixed(0),s=(o.current_usage/o.session_baseline).toFixed(2);return Oi(t),z(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${s}x baseline of ${i}k).
1440
1442
  This is informational - continue if task requires it.
1441
- Consider: delegate to subagent, break into smaller tasks.`}}return J(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}var su=!1;function au(){su||(La(),Ba(),uc(),el(),xl(),zl(),Zl(),ru(),iu(),su=!0)}var Un=require("fs"),hu=require("os"),Fn=require("path");function Ln(e,t=!1){let n=e.length,o=0,r="",i=0,s=16,c=0,a=0,l=0,u=0,d=0;function f(k,A){let D=0,R=0;for(;D<k||!A;){let w=e.charCodeAt(o);if(w>=48&&w<=57)R=R*16+w-48;else if(w>=65&&w<=70)R=R*16+w-65+10;else if(w>=97&&w<=102)R=R*16+w-97+10;else break;o++,D++}return D<k&&(R=-1),R}function g(k){o=k,r="",i=0,s=16,d=0}function m(){let k=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&ht(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&ht(e.charCodeAt(o)))for(o++;o<e.length&&ht(e.charCodeAt(o));)o++;else return d=3,e.substring(k,o);let A=o;if(o<e.length&&(e.charCodeAt(o)===69||e.charCodeAt(o)===101))if(o++,(o<e.length&&e.charCodeAt(o)===43||e.charCodeAt(o)===45)&&o++,o<e.length&&ht(e.charCodeAt(o))){for(o++;o<e.length&&ht(e.charCodeAt(o));)o++;A=o}else d=3;return e.substring(k,A)}function p(){let k="",A=o;for(;;){if(o>=n){k+=e.substring(A,o),d=2;break}let D=e.charCodeAt(o);if(D===34){k+=e.substring(A,o),o++;break}if(D===92){if(k+=e.substring(A,o),o++,o>=n){d=2;break}switch(e.charCodeAt(o++)){case 34:k+='"';break;case 92:k+="\\";break;case 47:k+="/";break;case 98:k+="\b";break;case 102:k+="\f";break;case 110:k+=`
1442
- `;break;case 114:k+="\r";break;case 116:k+=" ";break;case 117:let w=f(4,!0);w>=0?k+=String.fromCharCode(w):d=4;break;default:d=5}A=o;continue}if(D>=0&&D<=31)if(Wt(D)){k+=e.substring(A,o),d=2;break}else d=6;o++}return k}function h(){if(r="",d=0,i=o,a=c,u=l,o>=n)return i=n,s=17;let k=e.charCodeAt(o);if(vr(k)){do o++,r+=String.fromCharCode(k),k=e.charCodeAt(o);while(vr(k));return s=15}if(Wt(k))return o++,r+=String.fromCharCode(k),k===13&&e.charCodeAt(o)===10&&(o++,r+=`
1443
- `),c++,l=o,s=14;switch(k){case 123:return o++,s=1;case 125:return o++,s=2;case 91:return o++,s=3;case 93:return o++,s=4;case 58:return o++,s=6;case 44:return o++,s=5;case 34:return o++,r=p(),s=10;case 47:let A=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Wt(e.charCodeAt(o));)o++;return r=e.substring(A,o),s=12}if(e.charCodeAt(o+1)===42){o+=2;let D=n-1,R=!1;for(;o<D;){let w=e.charCodeAt(o);if(w===42&&e.charCodeAt(o+1)===47){o+=2,R=!0;break}o++,Wt(w)&&(w===13&&e.charCodeAt(o)===10&&o++,c++,l=o)}return R||(o++,d=1),r=e.substring(A,o),s=13}return r+=String.fromCharCode(k),o++,s=16;case 45:if(r+=String.fromCharCode(k),o++,o===n||!ht(e.charCodeAt(o)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=m(),s=11;default:for(;o<n&&y(k);)o++,k=e.charCodeAt(o);if(i!==o){switch(r=e.substring(i,o),r){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return r+=String.fromCharCode(k),o++,s=16}}function y(k){if(vr(k)||Wt(k))return!1;switch(k){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function T(){let k;do k=h();while(k>=12&&k<=15);return k}return{setPosition:g,getPosition:()=>o,scan:t?T:h,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>o-i,getTokenStartLine:()=>a,getTokenStartCharacter:()=>i-u,getTokenError:()=>d}}function vr(e){return e===32||e===9}function Wt(e){return e===10||e===13}function ht(e){return e>=48&&e<=57}var cu;(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"})(cu||(cu={}));var fg=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),kt=200,pg={" ":{"\n":new Array(kt).fill(0).map((e,t)=>`
1444
- `+" ".repeat(t)),"\r":new Array(kt).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(kt).fill(0).map((e,t)=>`\r
1445
- `+" ".repeat(t))}," ":{"\n":new Array(kt).fill(0).map((e,t)=>`
1446
- `+" ".repeat(t)),"\r":new Array(kt).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(kt).fill(0).map((e,t)=>`\r
1447
- `+" ".repeat(t))}};var Mn;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Mn||(Mn={}));function lu(e,t=[],n=Mn.DEFAULT){let o=null,r=[],i=[];function s(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return uu(e,{onObjectBegin:()=>{let a={};s(a),i.push(r),r=a,o=null},onObjectProperty:a=>{o=a},onObjectEnd:()=>{r=i.pop()},onArrayBegin:()=>{let a=[];s(a),i.push(r),r=a,o=null},onArrayEnd:()=>{r=i.pop()},onLiteralValue:s,onError:(a,l,u)=>{t.push({error:a,offset:l,length:u})}},n),r[0]}function uu(e,t,n=Mn.DEFAULT){let o=Ln(e,!1),r=[],i=0;function s(E){return E?()=>i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(E){return E?_=>i===0&&E(_,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(E){return E?_=>i===0&&E(_,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(E){return E?()=>{i>0?i++:E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(i=1)}:()=>!0}function u(E){return E?()=>{i>0&&i--,i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=a(t.onObjectProperty),g=u(t.onObjectEnd),m=l(t.onArrayBegin),p=u(t.onArrayEnd),h=a(t.onLiteralValue),y=c(t.onSeparator),T=s(t.onComment),k=c(t.onError),A=n&&n.disallowComments,D=n&&n.allowTrailingComma;function R(){for(;;){let E=o.scan();switch(o.getTokenError()){case 4:w(14);break;case 5:w(15);break;case 3:w(13);break;case 1:A||w(11);break;case 2:w(12);break;case 6:w(16);break}switch(E){case 12:case 13:A?w(10):T();break;case 16:w(1);break;case 15:case 14:break;default:return E}}}function w(E,_=[],P=[]){if(k(E),_.length+P.length>0){let C=o.getToken();for(;C!==17;){if(_.indexOf(C)!==-1){R();break}else if(P.indexOf(C)!==-1)break;C=R()}}}function ke(E){let _=o.getTokenValue();return E?h(_):(f(_),r.push(_)),R(),!0}function S(){switch(o.getToken()){case 11:let E=o.getTokenValue(),_=Number(E);isNaN(_)&&(w(2),_=0),h(_);break;case 7:h(null);break;case 8:h(!0);break;case 9:h(!1);break;default:return!1}return R(),!0}function b(){return o.getToken()!==10?(w(3,[],[2,5]),!1):(ke(!1),o.getToken()===6?(y(":"),R(),M()||w(4,[],[2,5])):w(5,[],[2,5]),r.pop(),!0)}function I(){d(),R();let E=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(E||w(4,[],[]),y(","),R(),o.getToken()===2&&D)break}else E&&w(6,[],[]);b()||w(4,[],[2,5]),E=!0}return g(),o.getToken()!==2?w(7,[2],[]):R(),!0}function F(){m(),R();let E=!0,_=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(_||w(4,[],[]),y(","),R(),o.getToken()===4&&D)break}else _&&w(6,[],[]);E?(r.push(0),E=!1):r[r.length-1]++,M()||w(4,[],[4,5]),_=!0}return p(),E||r.pop(),o.getToken()!==4?w(8,[4],[]):R(),!0}function M(){switch(o.getToken()){case 3:return F();case 1:return I();case 10:return ke(!0);default:return S()}}return R(),o.getToken()===17?n.allowEmptyContent?!0:(w(4,[],[]),!1):M()?(o.getToken()!==17&&w(9,[],[]),!0):(w(4,[],[]),!1)}var du;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(du||(du={}));var fu;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(fu||(fu={}));var mu=lu;var pu;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(pu||(pu={}));var Tg={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100},learning:{tokenMetrics:{enabled:!0,warningThreshold:1.5,minimumSamples:5,injectionTokenBudget:150,sessionBaseline:1e4}},pricing:{models:Or,customPricing:[]}};function wg(){return{user:(0,Fn.join)((0,hu.homedir)(),".claude","olympus","config.jsonc"),project:(0,Fn.join)(process.cwd(),".claude","olympus.jsonc")}}function gu(e){if(!(0,Un.existsSync)(e))return null;try{let t=(0,Un.readFileSync)(e,"utf-8"),n=[],o=mu(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),o}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function $n(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?n[o]=$n(i,r):r!==void 0&&(n[o]=r)}return n}function _g(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}if(process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),process.env.OLYMPUS_MAX_ASCENT_ITERATIONS){let t=parseInt(process.env.OLYMPUS_MAX_ASCENT_ITERATIONS,10);!isNaN(t)&&t>=10&&t<=1e3?e.ascent={...e.ascent,maxIterations:t}:isNaN(t)||console.warn(`Warning: OLYMPUS_MAX_ASCENT_ITERATIONS must be between 10 and 1000. Got: ${t}`)}return e}function ku(){let e=wg(),t={...Tg},n=gu(e.user);n&&(t=$n(t,n));let o=gu(e.project);o&&(t=$n(t,o));let r=_g();return t=$n(t,r),t}function Og(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function vg(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let o=n[t];if(typeof o=="object"&&o!==null){let r=o.enabled;if(typeof r=="boolean")return r}}return!0}async function Rg(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function Ig(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function yu(e,t){let n=ku(),o=Ir(e),r=Og(n),i=!0,s=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(vg(n,u.name)&&Ig(u.matcher,t.toolName))try{let d=await Rg(()=>u.handler({...t,toolInput:a,messages:l}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(i=!1,c=d.stopReason),d.message&&s.push(d.message),d.hookSpecificOutput?.additionalContext&&s.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(a=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:i,message:s.length>0?s.join(`
1443
+ Consider: delegate to subagent, break into smaller tasks.`}}return z(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}var pu=!1;function mu(){pu||(Ua(),Ka(),mc(),rl(),$l(),eu(),ou(),du(),fu(),pu=!0)}var Wn=require("fs"),_u=require("os"),Hn=require("path");function Fn(e,t=!1){let n=e.length,o=0,r="",i=0,s=16,c=0,a=0,l=0,u=0,d=0;function f(k,C){let L=0,I=0;for(;L<k||!C;){let _=e.charCodeAt(o);if(_>=48&&_<=57)I=I*16+_-48;else if(_>=65&&_<=70)I=I*16+_-65+10;else if(_>=97&&_<=102)I=I*16+_-97+10;else break;o++,L++}return L<k&&(I=-1),I}function g(k){o=k,r="",i=0,s=16,d=0}function m(){let k=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&yt(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&yt(e.charCodeAt(o)))for(o++;o<e.length&&yt(e.charCodeAt(o));)o++;else return d=3,e.substring(k,o);let C=o;if(o<e.length&&(e.charCodeAt(o)===69||e.charCodeAt(o)===101))if(o++,(o<e.length&&e.charCodeAt(o)===43||e.charCodeAt(o)===45)&&o++,o<e.length&&yt(e.charCodeAt(o))){for(o++;o<e.length&&yt(e.charCodeAt(o));)o++;C=o}else d=3;return e.substring(k,C)}function p(){let k="",C=o;for(;;){if(o>=n){k+=e.substring(C,o),d=2;break}let L=e.charCodeAt(o);if(L===34){k+=e.substring(C,o),o++;break}if(L===92){if(k+=e.substring(C,o),o++,o>=n){d=2;break}switch(e.charCodeAt(o++)){case 34:k+='"';break;case 92:k+="\\";break;case 47:k+="/";break;case 98:k+="\b";break;case 102:k+="\f";break;case 110:k+=`
1444
+ `;break;case 114:k+="\r";break;case 116:k+=" ";break;case 117:let _=f(4,!0);_>=0?k+=String.fromCharCode(_):d=4;break;default:d=5}C=o;continue}if(L>=0&&L<=31)if(Bt(L)){k+=e.substring(C,o),d=2;break}else d=6;o++}return k}function h(){if(r="",d=0,i=o,a=c,u=l,o>=n)return i=n,s=17;let k=e.charCodeAt(o);if(Cr(k)){do o++,r+=String.fromCharCode(k),k=e.charCodeAt(o);while(Cr(k));return s=15}if(Bt(k))return o++,r+=String.fromCharCode(k),k===13&&e.charCodeAt(o)===10&&(o++,r+=`
1445
+ `),c++,l=o,s=14;switch(k){case 123:return o++,s=1;case 125:return o++,s=2;case 91:return o++,s=3;case 93:return o++,s=4;case 58:return o++,s=6;case 44:return o++,s=5;case 34:return o++,r=p(),s=10;case 47:let C=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Bt(e.charCodeAt(o));)o++;return r=e.substring(C,o),s=12}if(e.charCodeAt(o+1)===42){o+=2;let L=n-1,I=!1;for(;o<L;){let _=e.charCodeAt(o);if(_===42&&e.charCodeAt(o+1)===47){o+=2,I=!0;break}o++,Bt(_)&&(_===13&&e.charCodeAt(o)===10&&o++,c++,l=o)}return I||(o++,d=1),r=e.substring(C,o),s=13}return r+=String.fromCharCode(k),o++,s=16;case 45:if(r+=String.fromCharCode(k),o++,o===n||!yt(e.charCodeAt(o)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=m(),s=11;default:for(;o<n&&y(k);)o++,k=e.charCodeAt(o);if(i!==o){switch(r=e.substring(i,o),r){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return r+=String.fromCharCode(k),o++,s=16}}function y(k){if(Cr(k)||Bt(k))return!1;switch(k){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function w(){let k;do k=h();while(k>=12&&k<=15);return k}return{setPosition:g,getPosition:()=>o,scan:t?w:h,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>o-i,getTokenStartLine:()=>a,getTokenStartCharacter:()=>i-u,getTokenError:()=>d}}function Cr(e){return e===32||e===9}function Bt(e){return e===10||e===13}function yt(e){return e>=48&&e<=57}var gu;(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"})(gu||(gu={}));var Eg=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),Et=200,Sg={" ":{"\n":new Array(Et).fill(0).map((e,t)=>`
1446
+ `+" ".repeat(t)),"\r":new Array(Et).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Et).fill(0).map((e,t)=>`\r
1447
+ `+" ".repeat(t))}," ":{"\n":new Array(Et).fill(0).map((e,t)=>`
1448
+ `+" ".repeat(t)),"\r":new Array(Et).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Et).fill(0).map((e,t)=>`\r
1449
+ `+" ".repeat(t))}};var Un;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Un||(Un={}));function hu(e,t=[],n=Un.DEFAULT){let o=null,r=[],i=[];function s(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return ku(e,{onObjectBegin:()=>{let a={};s(a),i.push(r),r=a,o=null},onObjectProperty:a=>{o=a},onObjectEnd:()=>{r=i.pop()},onArrayBegin:()=>{let a=[];s(a),i.push(r),r=a,o=null},onArrayEnd:()=>{r=i.pop()},onLiteralValue:s,onError:(a,l,u)=>{t.push({error:a,offset:l,length:u})}},n),r[0]}function ku(e,t,n=Un.DEFAULT){let o=Fn(e,!1),r=[],i=0;function s(S){return S?()=>i===0&&S(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(S){return S?O=>i===0&&S(O,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(S){return S?O=>i===0&&S(O,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(S){return S?()=>{i>0?i++:S(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(i=1)}:()=>!0}function u(S){return S?()=>{i>0&&i--,i===0&&S(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=a(t.onObjectProperty),g=u(t.onObjectEnd),m=l(t.onArrayBegin),p=u(t.onArrayEnd),h=a(t.onLiteralValue),y=c(t.onSeparator),w=s(t.onComment),k=c(t.onError),C=n&&n.disallowComments,L=n&&n.allowTrailingComma;function I(){for(;;){let S=o.scan();switch(o.getTokenError()){case 4:_(14);break;case 5:_(15);break;case 3:_(13);break;case 1:C||_(11);break;case 2:_(12);break;case 6:_(16);break}switch(S){case 12:case 13:C?_(10):w();break;case 16:_(1);break;case 15:case 14:break;default:return S}}}function _(S,O=[],x=[]){if(k(S),O.length+x.length>0){let N=o.getToken();for(;N!==17;){if(O.indexOf(N)!==-1){I();break}else if(x.indexOf(N)!==-1)break;N=I()}}}function ye(S){let O=o.getTokenValue();return S?h(O):(f(O),r.push(O)),I(),!0}function T(){switch(o.getToken()){case 11:let S=o.getTokenValue(),O=Number(S);isNaN(O)&&(_(2),O=0),h(O);break;case 7:h(null);break;case 8:h(!0);break;case 9:h(!1);break;default:return!1}return I(),!0}function A(){return o.getToken()!==10?(_(3,[],[2,5]),!1):(ye(!1),o.getToken()===6?(y(":"),I(),$()||_(4,[],[2,5])):_(5,[],[2,5]),r.pop(),!0)}function b(){d(),I();let S=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(S||_(4,[],[]),y(","),I(),o.getToken()===2&&L)break}else S&&_(6,[],[]);A()||_(4,[],[2,5]),S=!0}return g(),o.getToken()!==2?_(7,[2],[]):I(),!0}function j(){m(),I();let S=!0,O=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(O||_(4,[],[]),y(","),I(),o.getToken()===4&&L)break}else O&&_(6,[],[]);S?(r.push(0),S=!1):r[r.length-1]++,$()||_(4,[],[4,5]),O=!0}return p(),S||r.pop(),o.getToken()!==4?_(8,[4],[]):I(),!0}function $(){switch(o.getToken()){case 3:return j();case 1:return b();case 10:return ye(!0);default:return T()}}return I(),o.getToken()===17?n.allowEmptyContent?!0:(_(4,[],[]),!1):$()?(o.getToken()!==17&&_(9,[],[]),!0):(_(4,[],[]),!1)}var yu;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(yu||(yu={}));var Eu;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(Eu||(Eu={}));var Tu=hu;var Su;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(Su||(Su={}));var bg={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100},learning:{tokenMetrics:{enabled:!0,warningThreshold:1.5,minimumSamples:5,injectionTokenBudget:150,sessionBaseline:1e4}},pricing:{models:Ir,customPricing:[]}};function Cg(){return{user:(0,Hn.join)((0,_u.homedir)(),".claude","olympus","config.jsonc"),project:(0,Hn.join)(process.cwd(),".claude","olympus.jsonc")}}function wu(e){if(!(0,Wn.existsSync)(e))return null;try{let t=(0,Wn.readFileSync)(e,"utf-8"),n=[],o=Tu(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),o}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function jn(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?n[o]=jn(i,r):r!==void 0&&(n[o]=r)}return n}function Ag(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}if(process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),process.env.OLYMPUS_MAX_ASCENT_ITERATIONS){let t=parseInt(process.env.OLYMPUS_MAX_ASCENT_ITERATIONS,10);!isNaN(t)&&t>=10&&t<=1e3?e.ascent={...e.ascent,maxIterations:t}:isNaN(t)||console.warn(`Warning: OLYMPUS_MAX_ASCENT_ITERATIONS must be between 10 and 1000. Got: ${t}`)}return e}function Ou(){let e=Cg(),t={...bg},n=wu(e.user);n&&(t=jn(t,n));let o=wu(e.project);o&&(t=jn(t,o));let r=Ag();return t=jn(t,r),t}function Ng(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function Pg(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let o=n[t];if(typeof o=="object"&&o!==null){let r=o.enabled;if(typeof r=="boolean")return r}}return!0}async function xg(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function Dg(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function vu(e,t){let n=Ou(),o=Nr(e),r=Ng(n),i=!0,s=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(Pg(n,u.name)&&Dg(u.matcher,t.toolName))try{let d=await xg(()=>u.handler({...t,toolInput:a,messages:l}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(i=!1,c=d.stopReason),d.message&&s.push(d.message),d.hookSpecificOutput?.additionalContext&&s.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(a=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:i,message:s.length>0?s.join(`
1448
1450
 
1449
1451
  ---
1450
1452
 
1451
- `):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}au();async function Ag(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,o=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",r=>{n=!0,t.push(r)}),process.stdin.on("end",()=>{clearTimeout(o),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(o),e("{}")}),process.stdin.resume()})}async function Eu(){let t=process.argv.slice(2).find(s=>s.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],o=await Ag(),r;try{r=JSON.parse(o)}catch{r={}}let i=await yu(n,r);console.log(JSON.stringify(i)),process.exit(0)}var jn=process.argv[1]||"",bg=jn.endsWith("entry.ts")||jn.endsWith("entry.js")||jn.endsWith("olympus-hooks.mjs")||jn.includes("olympus-hooks");bg&&Eu().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
1453
+ `):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}mu();async function Lg(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,o=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",r=>{n=!0,t.push(r)}),process.stdin.on("end",()=>{clearTimeout(o),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(o),e("{}")}),process.stdin.resume()})}async function Ru(){let t=process.argv.slice(2).find(s=>s.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],o=await Lg(),r;try{let s=JSON.parse(o);r={...s,directory:s.cwd||s.directory,sessionId:s.session_id||s.sessionId}}catch{r={}}let i=await vu(n,r);console.log(JSON.stringify(i)),process.exit(0)}var Gn=process.argv[1]||"",Mg=Gn.endsWith("entry.ts")||Gn.endsWith("entry.js")||Gn.endsWith("olympus-hooks.mjs")||Gn.includes("olympus-hooks");Mg&&Ru().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});