olympus-ai 3.5.0 → 3.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +11 -2
- package/dist/config/loader.d.ts +1 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +2 -3
- package/dist/config/loader.js.map +1 -1
- package/dist/features/workflow-engine/engine.d.ts +11 -14
- package/dist/features/workflow-engine/engine.d.ts.map +1 -1
- package/dist/features/workflow-engine/engine.js +876 -122
- package/dist/features/workflow-engine/engine.js.map +1 -1
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +34 -12
- package/dist/installer/index.js.map +1 -1
- package/package.json +1 -1
- package/scripts/dist/hooks/olympus-hooks.cjs +686 -132
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
GFS4: `),console.error(e)});D[q]||(Pi=global[q]||[],Li(D,Pi),D.close=(function(e){function t(n,o){return e.call(D,n,function(r){r||Di(),typeof o=="function"&&o.apply(this,arguments)})}return Object.defineProperty(t,Xt,{value:e}),t})(D.close),D.closeSync=(function(e){function t(n){e.apply(D,arguments),Di()}return Object.defineProperty(t,Xt,{value:e}),t})(D.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Ge(D[q]),require("assert").equal(D[q].length,0)}));var Pi;global[q]||Li(global,D[q]);oo.exports=to(sf(D));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!D.__patched&&(oo.exports=to(D),D.__patched=!0);function to(e){of(e),e.gracefulify=to,e.createReadStream=L,e.createWriteStream=I;var t=e.readFile;e.readFile=n;function n(S,b,R){return typeof b=="function"&&(R=b,b=null),F(S,b,R);function F(M,E,w,x){return t(M,E,function(A){A&&(A.code==="EMFILE"||A.code==="ENFILE")?Ze([F,[M,E,w],A,x||Date.now(),Date.now()]):typeof w=="function"&&w.apply(this,arguments)})}}var o=e.writeFile;e.writeFile=r;function r(S,b,R,F){return typeof R=="function"&&(F=R,R=null),M(S,b,R,F);function M(E,w,x,A,G){return o(E,w,x,function(P){P&&(P.code==="EMFILE"||P.code==="ENFILE")?Ze([M,[E,w,x,A],P,G||Date.now(),Date.now()]):typeof A=="function"&&A.apply(this,arguments)})}}var i=e.appendFile;i&&(e.appendFile=s);function s(S,b,R,F){return typeof R=="function"&&(F=R,R=null),M(S,b,R,F);function M(E,w,x,A,G){return i(E,w,x,function(P){P&&(P.code==="EMFILE"||P.code==="ENFILE")?Ze([M,[E,w,x,A],P,G||Date.now(),Date.now()]):typeof A=="function"&&A.apply(this,arguments)})}}var c=e.copyFile;c&&(e.copyFile=a);function a(S,b,R,F){return typeof R=="function"&&(F=R,R=0),M(S,b,R,F);function M(E,w,x,A,G){return c(E,w,x,function(P){P&&(P.code==="EMFILE"||P.code==="ENFILE")?Ze([M,[E,w,x,A],P,G||Date.now(),Date.now()]):typeof A=="function"&&A.apply(this,arguments)})}}var l=e.readdir;e.readdir=f;var u=/^v[0-5]\./;function f(S,b,R){typeof b=="function"&&(R=b,b=null);var F=u.test(process.version)?function(w,x,A,G){return l(w,M(w,x,A,G))}:function(w,x,A,G){return l(w,x,M(w,x,A,G))};return F(S,b,R);function M(E,w,x,A){return function(G,P){G&&(G.code==="EMFILE"||G.code==="ENFILE")?Ze([F,[E,w,x],G,A||Date.now(),Date.now()]):(P&&P.sort&&P.sort(),typeof x=="function"&&x.call(this,G,P))}}}if(process.version.substr(0,4)==="v0.8"){var d=rf(e);k=d.ReadStream,g=d.WriteStream}var p=e.ReadStream;p&&(k.prototype=Object.create(p.prototype),k.prototype.open=_);var m=e.WriteStream;m&&(g.prototype=Object.create(m.prototype),g.prototype.open=N),Object.defineProperty(e,"ReadStream",{get:function(){return k},set:function(S){k=S},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return g},set:function(S){g=S},enumerable:!0,configurable:!0});var y=k;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(S){y=S},enumerable:!0,configurable:!0});var h=g;Object.defineProperty(e,"FileWriteStream",{get:function(){return h},set:function(S){h=S},enumerable:!0,configurable:!0});function k(S,b){return this instanceof k?(p.apply(this,arguments),this):k.apply(Object.create(k.prototype),arguments)}function _(){var S=this;ke(S.path,S.flags,S.mode,function(b,R){b?(S.autoClose&&S.destroy(),S.emit("error",b)):(S.fd=R,S.emit("open",R),S.read())})}function g(S,b){return this instanceof g?(m.apply(this,arguments),this):g.apply(Object.create(g.prototype),arguments)}function N(){var S=this;ke(S.path,S.flags,S.mode,function(b,R){b?(S.destroy(),S.emit("error",b)):(S.fd=R,S.emit("open",R))})}function L(S,b){return new e.ReadStream(S,b)}function I(S,b){return new e.WriteStream(S,b)}var T=e.open;e.open=ke;function ke(S,b,R,F){return typeof R=="function"&&(F=R,R=null),M(S,b,R,F);function M(E,w,x,A,G){return T(E,w,x,function(P,bg){P&&(P.code==="EMFILE"||P.code==="ENFILE")?Ze([M,[E,w,x,A],P,G||Date.now(),Date.now()]):typeof A=="function"&&A.apply(this,arguments)})}}return e}function Ze(e){Ge("ENQUEUE",e[0].name,e[1]),D[q].push(e),no()}var Jt;function Di(){for(var e=Date.now(),t=0;t<D[q].length;++t)D[q][t].length>2&&(D[q][t][3]=e,D[q][t][4]=e);no()}function no(){if(clearTimeout(Jt),Jt=void 0,D[q].length!==0){var e=D[q].shift(),t=e[0],n=e[1],o=e[2],r=e[3],i=e[4];if(r===void 0)Ge("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-r>=6e4){Ge("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?(Ge("RETRY",t.name,n),t.apply(null,n.concat([r]))):D[q].push(e)}Jt===void 0&&(Jt=setTimeout(no,0))}}});var X=O(_e=>{"use strict";var Mi=H().fromCallback,J=et(),cf=["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 J[e]=="function");Object.assign(_e,J);cf.forEach(e=>{_e[e]=Mi(J[e])});_e.exists=function(e,t){return typeof t=="function"?J.exists(e,t):new Promise(n=>J.exists(e,n))};_e.read=function(e,t,n,o,r,i){return typeof i=="function"?J.read(e,t,n,o,r,i):new Promise((s,c)=>{J.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"?J.write(e,t,...n):new Promise((o,r)=>{J.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"?J.readv(e,t,...n):new Promise((o,r)=>{J.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"?J.writev(e,t,...n):new Promise((o,r)=>{J.writev(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesWritten:s,buffers:c})})})};typeof J.realpath.native=="function"?_e.realpath.native=Mi(J.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Fi=O((vh,$i)=>{"use strict";var lf=require("path");$i.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(lf.parse(t).root,""))){let o=new Error(`Path contains invalid characters: ${t}`);throw o.code="EINVAL",o}}});var Wi=O((Rh,ro)=>{"use strict";var Ui=X(),{checkPath:ji}=Fi(),Hi=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};ro.exports.makeDir=async(e,t)=>(ji(e),Ui.mkdir(e,{mode:Hi(t),recursive:!0}));ro.exports.makeDirSync=(e,t)=>(ji(e),Ui.mkdirSync(e,{mode:Hi(t),recursive:!0}))});var pe=O((Ih,Gi)=>{"use strict";var uf=H().fromPromise,{makeDir:ff,makeDirSync:io}=Wi(),so=uf(ff);Gi.exports={mkdirs:so,mkdirsSync:io,mkdirp:so,mkdirpSync:io,ensureDir:so,ensureDirSync:io}});var De=O((bh,qi)=>{"use strict";var df=H().fromPromise,Bi=X();function pf(e){return Bi.access(e).then(()=>!0).catch(()=>!1)}qi.exports={pathExists:df(pf),pathExistsSync:Bi.existsSync}});var ao=O((Ah,Yi)=>{"use strict";var tt=X(),mf=H().fromPromise;async function gf(e,t,n){let o=await tt.open(e,"r+"),r=null;try{await tt.futimes(o,t,n)}finally{try{await tt.close(o)}catch(i){r=i}}if(r)throw r}function hf(e,t,n){let o=tt.openSync(e,"r+");return tt.futimesSync(o,t,n),tt.closeSync(o)}Yi.exports={utimesMillis:mf(gf),utimesMillisSync:hf}});var Be=O((Ch,Xi)=>{"use strict";var nt=X(),W=require("path"),Vi=H().fromPromise;function kf(e,t,n){let o=n.dereference?r=>nt.stat(r,{bigint:!0}):r=>nt.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 yf(e,t,n){let o,r=n.dereference?s=>nt.statSync(s,{bigint:!0}):s=>nt.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 Ef(e,t,n,o){let{srcStat:r,destStat:i}=await kf(e,t,o);if(i){if(ht(r,i)){let s=W.basename(e),c=W.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()&&co(e,t))throw new Error(zt(e,t,n));return{srcStat:r,destStat:i}}function Sf(e,t,n,o){let{srcStat:r,destStat:i}=yf(e,t,o);if(i){if(ht(r,i)){let s=W.basename(e),c=W.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()&&co(e,t))throw new Error(zt(e,t,n));return{srcStat:r,destStat:i}}async function Ki(e,t,n,o){let r=W.resolve(W.dirname(e)),i=W.resolve(W.dirname(n));if(i===r||i===W.parse(i).root)return;let s;try{s=await nt.stat(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(ht(t,s))throw new Error(zt(e,n,o));return Ki(e,t,i,o)}function Ji(e,t,n,o){let r=W.resolve(W.dirname(e)),i=W.resolve(W.dirname(n));if(i===r||i===W.parse(i).root)return;let s;try{s=nt.statSync(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(ht(t,s))throw new Error(zt(e,n,o));return Ji(e,t,i,o)}function ht(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function co(e,t){let n=W.resolve(e).split(W.sep).filter(r=>r),o=W.resolve(t).split(W.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}'.`}Xi.exports={checkPaths:Vi(Ef),checkPathsSync:Sf,checkParentPaths:Vi(Ki),checkParentPathsSync:Ji,isSrcSubdir:co,areIdentical:ht}});var Qi=O((Nh,zi)=>{"use strict";async function Tf(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})))}zi.exports={asyncIteratorConcurrentProcess:Tf}});var os=O((xh,ns)=>{"use strict";var V=X(),kt=require("path"),{mkdirs:wf}=pe(),{pathExists:_f}=De(),{utimesMillis:Of}=ao(),yt=Be(),{asyncIteratorConcurrentProcess:vf}=Qi();async function Rf(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 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;
|
|
5
5
|
|
|
6
|
-
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:o,destStat:r}=await
|
|
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;
|
|
7
7
|
|
|
8
|
-
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:o,destStat:r}=
|
|
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
|
|
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
|
|
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>
|
|
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=
|
|
17
|
+
`);let o=Cu(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
|
|
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}
|
|
23
23
|
${i.replacementText}
|
|
24
|
-
${
|
|
24
|
+
${qt}`;return{detected:!0,parsedCommand:o,injectedMessage:c}}let s=`${Bt}
|
|
25
25
|
[AUTO-SLASH-COMMAND ERROR]
|
|
26
26
|
${i.error}
|
|
27
27
|
|
|
28
28
|
Original input: ${o.raw}
|
|
29
|
-
${
|
|
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>
|
|
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"),
|
|
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>
|
|
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
|
|
|
@@ -186,93 +186,647 @@ Incomplete tasks remain in your todo list. Continue working on the next pending
|
|
|
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
|
|
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
|
|
191
|
-
`,"utf-8")}function
|
|
192
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n)):[]}function li(){return Yu()}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(k=>k.event_type==="success"),f=l.filter(k=>k.event_type==="revision"||k.event_type==="cancellation"),d=l.reduce((k,_)=>k+ze(_),0),p=u.reduce((k,_)=>k+ze(_),0),m=f.reduce((k,_)=>k+ze(_),0),y=u.length>0?p/u.length:0,h=f.length>0?m/f.length:0;if(a={avg_tokens_per_success:y,avg_tokens_per_failure:h,total_tokens:d,invocation_count:l.length,efficiency_score:y,trend:"insufficient_data"},l.length>=10){let k=Math.floor(l.length/2),_=l.slice(0,k),g=l.slice(k),N=_.reduce((ke,S)=>ke+ze(S),0)/_.length,I=g.reduce((ke,S)=>ke+ze(S),0)/g.length-N,T=N*.1;Math.abs(I)<T?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 Qe(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 fi(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 We(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 Vu=10,Ku=1800*1e3;function gi(e){return(0,pi.join)(e,".olympus","session-state.json")}function di(e,t){let n=We(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 ee(e,t){let n=gi(e),o=Qe(n,null);if(!o)return di(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>Ku)return di(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=We(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 K(e,t){let n=gi(e);t.last_updated=new Date().toISOString(),fi(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,Vu),e.last_updated=new Date().toISOString(),e}function ki(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Yt(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=We(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:We(),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"),Ju={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 Qn(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Ju))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=ee(n,o),i=Qn(t),s=hi(r,t,i?.category);if(i&&Yt(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};xe(c)}K(n,s)}var Oi=require("crypto");async function vi(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=ee(n,o);if(!Yt(r))return;let i=Qn(t),s=i?.category==="praise"&&i.confidence>.7,c=Xu(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};xe(a);let l=ki(r);K(n,l)}}function Xu(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 oe=ie(on(),1),_t=require("path"),go=".olympus/workflow",Ta="checkpoint.json",mo=new Map,ep=5e3;function wa(e,t){return`${e}:${t}`}function tp(e){return Date.now()-e.timestamp<ep}async function $e(e,t){let n=(0,_t.join)(e,go,t.workflow_id),o=(0,_t.join)(n,Ta);try{if(t.updated_at=new Date().toISOString(),await oe.ensureDir(n),JSON.stringify(t).length>1e4){let c=JSON.stringify(t);await oe.writeFile(o,c,"utf-8")}else await oe.writeJson(o,t,{spaces:2});let s=wa(e,t.workflow_id);mo.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=mo.get(n);if(o&&tp(o))return{...o.checkpoint};let r=(0,_t.join)(e,go,t,Ta);try{let i=await oe.readFile(r,"utf-8"),s=JSON.parse(i);return s.schema_version?(mo.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,_t.join)(e,go);try{return await oe.pathExists(t)?(await oe.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=ie(require("path"),1),se=ie(on(),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 Ot(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 rn(e,t,n,o){if(n==="intents")throw new Error("Cannot write single artifact for intents stage. Use writeIntentFile() instead.");let r=Ot(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 sn=require("fs"),va=new Map,np=1e4;function op(e){let t=va.get(e);if(t&&Date.now()-t.timestamp<np)return t.content;let n=(0,sn.readFileSync)(e,"utf-8");return va.set(e,{content:n,timestamp:Date.now()}),n}var rp=["Problem Statement","Business Context","Success Metrics","Constraints","Solution Approach"];async function Ra(e){let t=new Date().toISOString(),n=[],o;try{o=op(e)}catch(f){let d=f;return d.code==="ENOENT"?(console.error(`[Validation] IDEA artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):d.code==="EACCES"||d.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: ${d.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${d.message}`],timestamp:t})}let r=ip(o);(!r||!r.risk_tier)&&n.push("Risk tier not specified in frontmatter");let i=ho(o),s=ko(i),c=[()=>{let f=s.get("Problem Statement");return!f||f.trim().length===0?"Missing problem statement section":null},()=>{let f=s.get("Business Context");return!f||f.trim().length===0?"Business context section is empty":null},()=>{let f=s.get("Success Metrics");if(f){let d=Ia(f);if(d<2)return`Only ${d} success metric found, need at least 2`}else return"Missing success metrics section";return null},()=>{let f=s.get("Constraints");return!f||f.trim().length===0?"Constraints section missing":null},()=>{let f=[];for(let d of rp)s.has(d)||f.push(`Missing required section: ${d}`);return f.length>0?f.join("; "):null}];for(let f of c){let d=f();d&&n.push(d)}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 ip(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
|
|
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(`
|
|
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
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
|
|
198
|
-
`))
|
|
199
|
-
|
|
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=`---
|
|
202
|
+
id: ${o}
|
|
203
|
+
feature: ${this.workflowId}
|
|
204
|
+
feature_name: ${this.featureName}
|
|
205
|
+
created: ${r}
|
|
206
|
+
risk_tier: 2
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## Problem Statement
|
|
210
|
+
|
|
211
|
+
**Feature**: ${this.featureName}
|
|
200
212
|
|
|
201
|
-
## Initial Prompt
|
|
202
213
|
${n}
|
|
203
214
|
|
|
204
|
-
|
|
205
|
-
This is a placeholder idea document. The real idea-intake agent will generate
|
|
206
|
-
a proper analysis of the feature requirements.
|
|
215
|
+
This feature addresses a specific need identified by stakeholders. The goal is to implement a solution that meets user requirements while maintaining system quality and performance standards.
|
|
207
216
|
|
|
208
|
-
##
|
|
209
|
-
- [To be filled by idea-intake agent]
|
|
217
|
+
## Business Context
|
|
210
218
|
|
|
211
|
-
|
|
212
|
-
- [To be filled by idea-intake agent]
|
|
219
|
+
This feature will benefit end users by providing new functionality that enhances their workflow. The implementation aligns with our strategic goals of improving user experience and system capabilities.
|
|
213
220
|
|
|
214
|
-
|
|
215
|
-
|
|
221
|
+
**Target Users**: Primary users who will directly interact with this feature
|
|
222
|
+
**Expected Impact**: Improved user satisfaction and operational efficiency
|
|
223
|
+
**Strategic Alignment**: Supports product roadmap and business objectives
|
|
224
|
+
|
|
225
|
+
## Success Metrics
|
|
226
|
+
|
|
227
|
+
- **Metric 1**: Successful implementation with all acceptance criteria met (target: 100% completion)
|
|
228
|
+
- **Metric 2**: Zero critical bugs in production within first 30 days (target: 0 P0/P1 issues)
|
|
229
|
+
- **Metric 3**: Positive user feedback and adoption rate (target: >80% user satisfaction)
|
|
230
|
+
|
|
231
|
+
## Constraints
|
|
232
|
+
|
|
233
|
+
- **Technical**: Must integrate with existing system architecture and maintain compatibility
|
|
234
|
+
- **Timeline**: Development should follow standard sprint cycles and delivery timelines
|
|
235
|
+
- **Budget**: Implementation within allocated development resources and infrastructure costs
|
|
236
|
+
- **Resources**: Available team capacity and technical expertise
|
|
237
|
+
- **Policy**: Compliance with security standards, data privacy regulations, and coding best practices
|
|
238
|
+
|
|
239
|
+
## Solution Approach
|
|
216
240
|
|
|
241
|
+
The proposed solution will follow a phased implementation approach:
|
|
242
|
+
|
|
243
|
+
1. **Phase 1 - Planning**: Define detailed requirements, technical design, and implementation plan
|
|
244
|
+
2. **Phase 2 - Development**: Implement core functionality with iterative testing
|
|
245
|
+
3. **Phase 3 - Validation**: Comprehensive testing, security review, and performance validation
|
|
246
|
+
4. **Phase 4 - Deployment**: Staged rollout with monitoring and support
|
|
247
|
+
|
|
248
|
+
**Key Considerations**:
|
|
249
|
+
- Maintain backward compatibility where applicable
|
|
250
|
+
- Ensure scalability and performance
|
|
251
|
+
- Implement proper error handling and logging
|
|
252
|
+
- Follow established coding standards and patterns
|
|
253
|
+
|
|
254
|
+
## Risk Assessment
|
|
255
|
+
|
|
256
|
+
**Risk Tier**: 2 (Medium)
|
|
257
|
+
|
|
258
|
+
**Justification**: This is a standard feature implementation with moderate complexity. While there are some unknowns in requirements and integration points, the domain is well-understood and the impact is manageable with proper testing and validation.
|
|
259
|
+
|
|
260
|
+
**Key Risks**:
|
|
261
|
+
- **Integration Complexity**: May encounter challenges integrating with existing systems
|
|
262
|
+
- **Scope Creep**: Requirements may evolve during implementation
|
|
263
|
+
- **Resource Availability**: Team capacity constraints could impact timeline
|
|
264
|
+
- **Technical Debt**: Need to balance new features with code quality and maintainability
|
|
265
|
+
|
|
266
|
+
**Mitigation Strategies**:
|
|
267
|
+
- Early prototyping to validate integration approach
|
|
268
|
+
- Regular stakeholder communication to manage scope
|
|
269
|
+
- Incremental delivery to reduce risk
|
|
270
|
+
- Comprehensive testing and code review processes
|
|
271
|
+
|
|
272
|
+
---
|
|
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=`---
|
|
275
|
+
id: ${o}
|
|
276
|
+
feature: ${this.workflowId}
|
|
277
|
+
created: ${r}
|
|
278
|
+
based_on: IDEA-001
|
|
217
279
|
---
|
|
218
|
-
*Generated by WorkflowEngine (stub implementation)*
|
|
219
|
-
`;await rn(this.projectPath,this.workflowId,"idea",o);let r=Ot(this.projectPath,this.workflowId,"idea");console.log(`[WorkflowEngine] Validating IDEA artifact at: ${r}`);let i=await Ra(r);t.validation_results.idea=i,i.passed?console.log("[WorkflowEngine] IDEA validation passed"):(console.log("[WorkflowEngine] IDEA validation failed:",i.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${i.coverage_percentage}%`))}async executePrdStage(t){console.log(`[WorkflowEngine] Executing PRD stage for feature: ${this.featureName}`);let n=Ot(this.projectPath,this.workflowId,"idea");console.log("[WorkflowEngine] Agent invocation: prd-writer (stub - would be invoked here)"),console.log(`[WorkflowEngine] Input IDEA artifact: ${n}`);let o=`# Product Requirements Document: ${this.featureName}
|
|
220
280
|
|
|
221
281
|
## Overview
|
|
222
|
-
This is a placeholder PRD document. The real prd-writer agent will generate
|
|
223
|
-
a comprehensive product requirements document.
|
|
224
282
|
|
|
225
|
-
|
|
226
|
-
- [To be filled by prd-writer agent]
|
|
283
|
+
This PRD defines the product requirements for ${this.featureName}. It translates the strategic vision from the IDEA artifact into actionable user stories with clear acceptance criteria.
|
|
227
284
|
|
|
228
|
-
##
|
|
229
|
-
- [To be filled by prd-writer agent]
|
|
285
|
+
## User Stories
|
|
230
286
|
|
|
231
|
-
|
|
232
|
-
|
|
287
|
+
### US-001: Core Feature Implementation
|
|
288
|
+
**As a** user
|
|
289
|
+
**I want** to use ${this.featureName}
|
|
290
|
+
**So that** I can benefit from the new functionality
|
|
291
|
+
|
|
292
|
+
**Acceptance Criteria:**
|
|
293
|
+
- [ ] Feature is accessible through the standard user interface
|
|
294
|
+
- [ ] Feature functions according to specification
|
|
295
|
+
- [ ] Feature integrates with existing system components
|
|
296
|
+
- [ ] Feature handles error cases gracefully
|
|
297
|
+
|
|
298
|
+
**Technical Notes:**
|
|
299
|
+
- Must maintain compatibility with existing architecture
|
|
300
|
+
- Follow established coding patterns and standards
|
|
301
|
+
|
|
302
|
+
### US-002: Technical Integration
|
|
303
|
+
**As a** developer
|
|
304
|
+
**I want** the feature to integrate seamlessly with existing systems
|
|
305
|
+
**So that** we maintain system stability and consistency
|
|
306
|
+
|
|
307
|
+
**Acceptance Criteria:**
|
|
308
|
+
- [ ] All API contracts are maintained
|
|
309
|
+
- [ ] Integration tests pass successfully
|
|
310
|
+
- [ ] No breaking changes to existing functionality
|
|
311
|
+
- [ ] Performance metrics remain within acceptable bounds
|
|
312
|
+
|
|
313
|
+
**Technical Notes:**
|
|
314
|
+
- Requires review of existing integration points
|
|
315
|
+
- May need adapter patterns for legacy components
|
|
316
|
+
|
|
317
|
+
### US-003: Resource Management
|
|
318
|
+
**As a** system administrator
|
|
319
|
+
**I want** the feature to operate within resource constraints
|
|
320
|
+
**So that** system performance and costs remain optimal
|
|
321
|
+
|
|
322
|
+
**Acceptance Criteria:**
|
|
323
|
+
- [ ] Resource usage stays within budget constraints
|
|
324
|
+
- [ ] Scaling strategy is defined and documented
|
|
325
|
+
- [ ] Monitoring and alerting are configured
|
|
326
|
+
- [ ] Capacity planning is completed
|
|
327
|
+
|
|
328
|
+
**Technical Notes:**
|
|
329
|
+
- Consider horizontal scaling for high-load scenarios
|
|
330
|
+
- Implement resource pooling where appropriate
|
|
331
|
+
|
|
332
|
+
### US-004: Timeline Delivery
|
|
333
|
+
**As a** project stakeholder
|
|
334
|
+
**I want** the feature delivered according to schedule
|
|
335
|
+
**So that** we meet business commitments and milestones
|
|
336
|
+
|
|
337
|
+
**Acceptance Criteria:**
|
|
338
|
+
- [ ] Implementation follows defined sprint cycles
|
|
339
|
+
- [ ] Key milestones are tracked and met
|
|
340
|
+
- [ ] Blockers are identified and resolved promptly
|
|
341
|
+
- [ ] Regular status updates are provided
|
|
342
|
+
|
|
343
|
+
**Technical Notes:**
|
|
344
|
+
- Use iterative development approach
|
|
345
|
+
- Prioritize MVP features first
|
|
346
|
+
|
|
347
|
+
### US-005: Compliance and Security
|
|
348
|
+
**As a** compliance officer
|
|
349
|
+
**I want** the feature to meet security and policy requirements
|
|
350
|
+
**So that** we maintain regulatory compliance and protect user data
|
|
351
|
+
|
|
352
|
+
**Acceptance Criteria:**
|
|
353
|
+
- [ ] Security review completed and approved
|
|
354
|
+
- [ ] Data privacy requirements satisfied
|
|
355
|
+
- [ ] Access controls properly implemented
|
|
356
|
+
- [ ] Audit logging in place
|
|
357
|
+
|
|
358
|
+
**Technical Notes:**
|
|
359
|
+
- Follow OWASP security guidelines
|
|
360
|
+
- Implement principle of least privilege
|
|
361
|
+
|
|
362
|
+
## Requirement Coverage
|
|
363
|
+
|
|
364
|
+
| IDEA Constraint | PRD User Story | Coverage |
|
|
365
|
+
|-----------------|----------------|----------|
|
|
366
|
+
| Technical constraints | US-001, US-002 | \u2713 |
|
|
367
|
+
| Timeline constraints | US-004 | \u2713 |
|
|
368
|
+
| Budget constraints | US-003 | \u2713 |
|
|
369
|
+
| Resource constraints | US-003 | \u2713 |
|
|
370
|
+
| Policy constraints | US-005 | \u2713 |
|
|
371
|
+
|
|
372
|
+
**Coverage Summary:**
|
|
373
|
+
- Total constraints: 5
|
|
374
|
+
- Covered: 5 (100%)
|
|
375
|
+
- Uncovered: None
|
|
376
|
+
|
|
377
|
+
## Out of Scope
|
|
378
|
+
|
|
379
|
+
The following items are explicitly excluded from this PRD:
|
|
380
|
+
- Future enhancements not included in initial requirements
|
|
381
|
+
- Integration with systems outside the current scope
|
|
382
|
+
- Features that require additional budget allocation
|
|
383
|
+
- Changes to unrelated system components
|
|
384
|
+
|
|
385
|
+
## Dependencies
|
|
386
|
+
|
|
387
|
+
**External Dependencies:**
|
|
388
|
+
- Existing system infrastructure and services
|
|
389
|
+
- Third-party libraries and frameworks (as needed)
|
|
390
|
+
- Development and testing environments
|
|
391
|
+
|
|
392
|
+
**Internal Dependencies:**
|
|
393
|
+
- Team availability and resource allocation
|
|
394
|
+
- Completion of prerequisite tasks or features
|
|
395
|
+
- Access to necessary systems and data
|
|
396
|
+
|
|
397
|
+
## Risks
|
|
398
|
+
|
|
399
|
+
**Technical Risks:**
|
|
400
|
+
- Integration complexity may require additional investigation
|
|
401
|
+
- Performance requirements may need optimization iterations
|
|
402
|
+
- Technical debt may need to be addressed during implementation
|
|
403
|
+
|
|
404
|
+
**Mitigation:**
|
|
405
|
+
- Early prototyping and proof-of-concept work
|
|
406
|
+
- Regular technical reviews and architecture discussions
|
|
407
|
+
- Incremental delivery with continuous testing
|
|
408
|
+
|
|
409
|
+
**Schedule Risks:**
|
|
410
|
+
- Resource constraints could impact delivery timeline
|
|
411
|
+
- Unexpected technical challenges may arise
|
|
412
|
+
- Scope creep from evolving requirements
|
|
413
|
+
|
|
414
|
+
**Mitigation:**
|
|
415
|
+
- Maintain clear scope boundaries
|
|
416
|
+
- Regular stakeholder communication
|
|
417
|
+
- Buffer time for contingencies
|
|
233
418
|
|
|
234
419
|
## Success Metrics
|
|
235
|
-
|
|
420
|
+
|
|
421
|
+
Success will be measured using the following criteria from the IDEA artifact:
|
|
422
|
+
- **Implementation Completeness**: All acceptance criteria met (target: 100%)
|
|
423
|
+
- **Quality**: Zero critical defects in production (target: 0 P0/P1 issues)
|
|
424
|
+
- **User Satisfaction**: Positive feedback and adoption (target: >80% satisfaction)
|
|
236
425
|
|
|
237
426
|
---
|
|
238
|
-
*Generated by WorkflowEngine
|
|
239
|
-
`;await
|
|
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(`
|
|
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
|
+
id: ${c}
|
|
431
|
+
feature: ${this.workflowId}
|
|
432
|
+
created: ${a}
|
|
433
|
+
based_on: IDEA-001
|
|
434
|
+
prd_id: PRD-001
|
|
435
|
+
---
|
|
240
436
|
|
|
241
437
|
## Overview
|
|
242
|
-
This is a placeholder technical specification. The real spec-writer agent will
|
|
243
|
-
generate a detailed technical specification.
|
|
244
438
|
|
|
245
|
-
|
|
246
|
-
|
|
439
|
+
This technical specification defines the architecture, data models, and implementation approach for ${this.featureName}. It translates the product requirements from the PRD into concrete technical designs.
|
|
440
|
+
|
|
441
|
+
## Components
|
|
442
|
+
|
|
443
|
+
### Frontend Components
|
|
444
|
+
|
|
445
|
+
**User Interface Layer**
|
|
446
|
+
- Main feature UI component with state management
|
|
447
|
+
- Form validation and input handling
|
|
448
|
+
- Error boundary and fallback UI
|
|
449
|
+
- Responsive layout adapters
|
|
450
|
+
|
|
451
|
+
**Technical Requirements:**
|
|
452
|
+
- Component library: React/Vue/Angular (as per stack)
|
|
453
|
+
- State management: Redux/Context API/Vuex
|
|
454
|
+
- Styling: CSS modules or styled-components
|
|
455
|
+
- Accessibility: WCAG 2.1 AA compliance
|
|
456
|
+
|
|
457
|
+
### Backend Services
|
|
458
|
+
|
|
459
|
+
**API Service**
|
|
460
|
+
- RESTful API endpoints for feature operations
|
|
461
|
+
- Request validation middleware
|
|
462
|
+
- Business logic layer
|
|
463
|
+
- Data access layer
|
|
464
|
+
|
|
465
|
+
**Technical Requirements:**
|
|
466
|
+
- Framework: Express/FastAPI/Spring Boot (as per stack)
|
|
467
|
+
- Validation: Joi/Pydantic/Bean Validation
|
|
468
|
+
- ORM: TypeORM/SQLAlchemy/JPA
|
|
469
|
+
- Logging: Winston/Python logging/SLF4J
|
|
470
|
+
|
|
471
|
+
### Database Components
|
|
472
|
+
|
|
473
|
+
**Data Storage**
|
|
474
|
+
- Primary database tables/collections
|
|
475
|
+
- Indexing strategy for performance
|
|
476
|
+
- Migration scripts
|
|
477
|
+
- Backup procedures
|
|
478
|
+
|
|
479
|
+
**Technical Requirements:**
|
|
480
|
+
- Database: PostgreSQL/MySQL/MongoDB (as per stack)
|
|
481
|
+
- Connection pooling: pgbouncer/connection pool
|
|
482
|
+
- Replication: Primary-replica setup
|
|
483
|
+
- Backup: Daily automated backups
|
|
484
|
+
|
|
485
|
+
### Infrastructure Components
|
|
486
|
+
|
|
487
|
+
**Deployment Architecture**
|
|
488
|
+
- Application server configuration
|
|
489
|
+
- Load balancer setup
|
|
490
|
+
- CDN integration for static assets
|
|
491
|
+
- Monitoring and alerting
|
|
492
|
+
|
|
493
|
+
**Technical Requirements:**
|
|
494
|
+
- Container: Docker
|
|
495
|
+
- Orchestration: Kubernetes/Docker Compose
|
|
496
|
+
- CI/CD: GitHub Actions/Jenkins/GitLab CI
|
|
497
|
+
- Monitoring: Prometheus/Grafana/Datadog
|
|
498
|
+
|
|
499
|
+
## Database Schema
|
|
500
|
+
|
|
501
|
+
### Tables/Collections
|
|
502
|
+
|
|
503
|
+
**feature_data**
|
|
504
|
+
- id: UUID PRIMARY KEY
|
|
505
|
+
- user_id: UUID NOT NULL FOREIGN KEY \u2192 users.id
|
|
506
|
+
- feature_name: VARCHAR(255) NOT NULL
|
|
507
|
+
- data_payload: JSONB
|
|
508
|
+
- status: VARCHAR(50) NOT NULL
|
|
509
|
+
- created_at: TIMESTAMP NOT NULL DEFAULT NOW()
|
|
510
|
+
- updated_at: TIMESTAMP NOT NULL DEFAULT NOW()
|
|
511
|
+
|
|
512
|
+
**Indexes:**
|
|
513
|
+
- idx_feature_data_user_id ON feature_data(user_id)
|
|
514
|
+
- idx_feature_data_status ON feature_data(status)
|
|
515
|
+
- idx_feature_data_created_at ON feature_data(created_at)
|
|
516
|
+
|
|
517
|
+
**feature_audit_log**
|
|
518
|
+
- id: UUID PRIMARY KEY
|
|
519
|
+
- feature_data_id: UUID NOT NULL FOREIGN KEY \u2192 feature_data.id
|
|
520
|
+
- action: VARCHAR(50) NOT NULL
|
|
521
|
+
- actor_id: UUID NOT NULL FOREIGN KEY \u2192 users.id
|
|
522
|
+
- changes: JSONB
|
|
523
|
+
- timestamp: TIMESTAMP NOT NULL DEFAULT NOW()
|
|
524
|
+
|
|
525
|
+
**Indexes:**
|
|
526
|
+
- idx_feature_audit_feature_id ON feature_audit_log(feature_data_id)
|
|
527
|
+
- idx_feature_audit_timestamp ON feature_audit_log(timestamp)
|
|
528
|
+
|
|
529
|
+
## API Endpoints
|
|
530
|
+
|
|
531
|
+
### POST /api/v1/feature
|
|
532
|
+
Create new feature instance
|
|
533
|
+
|
|
534
|
+
**Request:**
|
|
535
|
+
\`\`\`json
|
|
536
|
+
{
|
|
537
|
+
"feature_name": "string",
|
|
538
|
+
"data_payload": {},
|
|
539
|
+
"user_id": "uuid"
|
|
540
|
+
}
|
|
541
|
+
\`\`\`
|
|
542
|
+
|
|
543
|
+
**Response (201 Created):**
|
|
544
|
+
\`\`\`json
|
|
545
|
+
{
|
|
546
|
+
"id": "uuid",
|
|
547
|
+
"feature_name": "string",
|
|
548
|
+
"status": "active",
|
|
549
|
+
"created_at": "timestamp"
|
|
550
|
+
}
|
|
551
|
+
\`\`\`
|
|
552
|
+
|
|
553
|
+
**Authentication:** Bearer token required
|
|
554
|
+
**Rate Limit:** 100 requests/minute per user
|
|
555
|
+
|
|
556
|
+
### GET /api/v1/feature/:id
|
|
557
|
+
Retrieve feature instance by ID
|
|
558
|
+
|
|
559
|
+
**Response (200 OK):**
|
|
560
|
+
\`\`\`json
|
|
561
|
+
{
|
|
562
|
+
"id": "uuid",
|
|
563
|
+
"feature_name": "string",
|
|
564
|
+
"data_payload": {},
|
|
565
|
+
"status": "active",
|
|
566
|
+
"created_at": "timestamp",
|
|
567
|
+
"updated_at": "timestamp"
|
|
568
|
+
}
|
|
569
|
+
\`\`\`
|
|
570
|
+
|
|
571
|
+
**Authentication:** Bearer token required
|
|
572
|
+
**Rate Limit:** 1000 requests/minute per user
|
|
573
|
+
|
|
574
|
+
### PUT /api/v1/feature/:id
|
|
575
|
+
Update feature instance
|
|
576
|
+
|
|
577
|
+
**Request:**
|
|
578
|
+
\`\`\`json
|
|
579
|
+
{
|
|
580
|
+
"data_payload": {},
|
|
581
|
+
"status": "active" | "inactive"
|
|
582
|
+
}
|
|
583
|
+
\`\`\`
|
|
584
|
+
|
|
585
|
+
**Response (200 OK):**
|
|
586
|
+
\`\`\`json
|
|
587
|
+
{
|
|
588
|
+
"id": "uuid",
|
|
589
|
+
"feature_name": "string",
|
|
590
|
+
"data_payload": {},
|
|
591
|
+
"status": "active",
|
|
592
|
+
"updated_at": "timestamp"
|
|
593
|
+
}
|
|
594
|
+
\`\`\`
|
|
595
|
+
|
|
596
|
+
**Authentication:** Bearer token required
|
|
597
|
+
**Rate Limit:** 100 requests/minute per user
|
|
598
|
+
|
|
599
|
+
### DELETE /api/v1/feature/:id
|
|
600
|
+
Delete feature instance (soft delete)
|
|
601
|
+
|
|
602
|
+
**Response (204 No Content)**
|
|
603
|
+
|
|
604
|
+
**Authentication:** Bearer token required
|
|
605
|
+
**Rate Limit:** 50 requests/minute per user
|
|
606
|
+
|
|
607
|
+
## Authentication/Authorization
|
|
608
|
+
|
|
609
|
+
### Authentication Mechanism
|
|
610
|
+
|
|
611
|
+
**JWT Token-Based Authentication**
|
|
612
|
+
- Tokens issued on successful login
|
|
613
|
+
- Token expiry: 24 hours
|
|
614
|
+
- Refresh token rotation enabled
|
|
615
|
+
- Token blacklist for logout
|
|
616
|
+
|
|
617
|
+
**Implementation:**
|
|
618
|
+
\`\`\`typescript
|
|
619
|
+
middleware.authenticate = (req, res, next) => {
|
|
620
|
+
const token = extractToken(req);
|
|
621
|
+
const payload = verifyJWT(token);
|
|
622
|
+
req.user = payload;
|
|
623
|
+
next();
|
|
624
|
+
};
|
|
625
|
+
\`\`\`
|
|
626
|
+
|
|
627
|
+
### Authorization Model
|
|
628
|
+
|
|
629
|
+
**Role-Based Access Control (RBAC)**
|
|
630
|
+
- Roles: admin, user, guest
|
|
631
|
+
- Permissions: create, read, update, delete
|
|
632
|
+
- Resource-level permissions
|
|
633
|
+
|
|
634
|
+
**Permission Matrix:**
|
|
635
|
+
| Role | Create | Read | Update | Delete |
|
|
636
|
+
|------|--------|------|--------|--------|
|
|
637
|
+
| Admin | \u2713 | \u2713 | \u2713 | \u2713 |
|
|
638
|
+
| User | \u2713 | \u2713 (own) | \u2713 (own) | \u2713 (own) |
|
|
639
|
+
| Guest | \u2717 | \u2713 (public) | \u2717 | \u2717 |
|
|
640
|
+
|
|
641
|
+
### Token Management
|
|
642
|
+
|
|
643
|
+
**Token Storage:**
|
|
644
|
+
- Access token: HTTP-only cookie or localStorage
|
|
645
|
+
- Refresh token: HTTP-only cookie (secure flag)
|
|
646
|
+
|
|
647
|
+
**Token Refresh Flow:**
|
|
648
|
+
1. Client detects expired access token
|
|
649
|
+
2. Send refresh token to /api/v1/auth/refresh
|
|
650
|
+
3. Server validates refresh token
|
|
651
|
+
4. Issue new access token and refresh token pair
|
|
652
|
+
5. Client updates stored tokens
|
|
653
|
+
|
|
654
|
+
## Error Handling
|
|
655
|
+
|
|
656
|
+
### Error Types
|
|
657
|
+
|
|
658
|
+
**Client Errors (4xx)**
|
|
659
|
+
- 400 Bad Request: Invalid input data
|
|
660
|
+
- 401 Unauthorized: Missing or invalid authentication
|
|
661
|
+
- 403 Forbidden: Insufficient permissions
|
|
662
|
+
- 404 Not Found: Resource does not exist
|
|
663
|
+
- 409 Conflict: Resource conflict (duplicate entry)
|
|
664
|
+
- 422 Unprocessable Entity: Validation errors
|
|
665
|
+
- 429 Too Many Requests: Rate limit exceeded
|
|
666
|
+
|
|
667
|
+
**Server Errors (5xx)**
|
|
668
|
+
- 500 Internal Server Error: Unexpected error
|
|
669
|
+
- 502 Bad Gateway: Upstream service failure
|
|
670
|
+
- 503 Service Unavailable: Temporary unavailability
|
|
671
|
+
- 504 Gateway Timeout: Upstream timeout
|
|
672
|
+
|
|
673
|
+
### Error Response Format
|
|
674
|
+
|
|
675
|
+
\`\`\`json
|
|
676
|
+
{
|
|
677
|
+
"error": {
|
|
678
|
+
"code": "VALIDATION_ERROR",
|
|
679
|
+
"message": "Invalid input data",
|
|
680
|
+
"details": [
|
|
681
|
+
{
|
|
682
|
+
"field": "feature_name",
|
|
683
|
+
"message": "Feature name is required"
|
|
684
|
+
}
|
|
685
|
+
],
|
|
686
|
+
"request_id": "uuid"
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
\`\`\`
|
|
690
|
+
|
|
691
|
+
### Logging Strategy
|
|
692
|
+
|
|
693
|
+
**Log Levels:**
|
|
694
|
+
- ERROR: Critical failures requiring immediate attention
|
|
695
|
+
- WARN: Non-critical issues that should be investigated
|
|
696
|
+
- INFO: General operational events
|
|
697
|
+
- DEBUG: Detailed diagnostic information
|
|
698
|
+
|
|
699
|
+
**Log Format (JSON):**
|
|
700
|
+
\`\`\`json
|
|
701
|
+
{
|
|
702
|
+
"timestamp": "ISO8601",
|
|
703
|
+
"level": "ERROR",
|
|
704
|
+
"service": "feature-api",
|
|
705
|
+
"message": "Database connection failed",
|
|
706
|
+
"context": {
|
|
707
|
+
"request_id": "uuid",
|
|
708
|
+
"user_id": "uuid",
|
|
709
|
+
"error": "Connection timeout"
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
\`\`\`
|
|
713
|
+
|
|
714
|
+
**Log Aggregation:**
|
|
715
|
+
- Centralized logging: ELK Stack/Splunk/CloudWatch
|
|
716
|
+
- Log retention: 30 days for INFO, 90 days for ERROR
|
|
717
|
+
- Alert triggers: Error rate > 1% over 5 minutes
|
|
718
|
+
|
|
719
|
+
## Performance Considerations
|
|
720
|
+
|
|
721
|
+
### Caching Strategy
|
|
722
|
+
|
|
723
|
+
**Application-Level Caching**
|
|
724
|
+
- Cache frequently accessed data (user profiles, feature metadata)
|
|
725
|
+
- Cache TTL: 5 minutes for dynamic data, 1 hour for static data
|
|
726
|
+
- Cache invalidation on data mutation
|
|
727
|
+
|
|
728
|
+
**Implementation:**
|
|
729
|
+
\`\`\`typescript
|
|
730
|
+
cache.get('feature:' + id, async () => {
|
|
731
|
+
return await database.getFeature(id);
|
|
732
|
+
}, { ttl: 300 });
|
|
733
|
+
\`\`\`
|
|
734
|
+
|
|
735
|
+
**CDN Caching**
|
|
736
|
+
- Static assets: max-age=31536000 (1 year)
|
|
737
|
+
- API responses: Cache-Control: no-cache for authenticated endpoints
|
|
738
|
+
- Public data: Cache-Control: public, max-age=300
|
|
739
|
+
|
|
740
|
+
### Database Optimization
|
|
741
|
+
|
|
742
|
+
**Query Optimization**
|
|
743
|
+
- Use prepared statements to prevent SQL injection
|
|
744
|
+
- Index foreign keys and frequently queried columns
|
|
745
|
+
- Use connection pooling (min: 10, max: 50 connections)
|
|
746
|
+
- Implement query timeouts (5 seconds)
|
|
247
747
|
|
|
248
|
-
|
|
249
|
-
-
|
|
748
|
+
**Database Scaling:**
|
|
749
|
+
- Read replicas for heavy read workloads
|
|
750
|
+
- Partitioning for large tables (by date/user_id)
|
|
751
|
+
- Query result pagination (max 100 records per page)
|
|
250
752
|
|
|
251
|
-
|
|
252
|
-
- [To be filled by spec-writer agent]
|
|
753
|
+
### Rate Limiting
|
|
253
754
|
|
|
254
|
-
|
|
255
|
-
-
|
|
755
|
+
**Implementation:**
|
|
756
|
+
- Token bucket algorithm
|
|
757
|
+
- Per-user limits stored in Redis
|
|
758
|
+
- Rate limit headers in response:
|
|
759
|
+
- X-RateLimit-Limit: Maximum requests
|
|
760
|
+
- X-RateLimit-Remaining: Remaining requests
|
|
761
|
+
- X-RateLimit-Reset: Reset timestamp
|
|
256
762
|
|
|
763
|
+
**Limits by Endpoint:**
|
|
764
|
+
- POST /api/v1/feature: 100/min
|
|
765
|
+
- GET /api/v1/feature: 1000/min
|
|
766
|
+
- PUT /api/v1/feature: 100/min
|
|
767
|
+
- DELETE /api/v1/feature: 50/min
|
|
768
|
+
|
|
769
|
+
## PRD Coverage
|
|
770
|
+
|
|
771
|
+
This specification addresses all user stories from PRD-001:
|
|
772
|
+
|
|
773
|
+
| PRD User Story | SPEC Coverage |
|
|
774
|
+
|----------------|---------------|${i.map(f=>`
|
|
775
|
+
| ${f} | Components, API Endpoints, Database Schema |`).join("")}
|
|
776
|
+
|
|
777
|
+
**Coverage Summary:**
|
|
778
|
+
- Total user stories: ${i.length}
|
|
779
|
+
- Covered: ${i.length} (100%)
|
|
780
|
+
- Uncovered: None
|
|
781
|
+
|
|
782
|
+
---
|
|
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(`
|
|
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
|
+
id: ${p.id}
|
|
787
|
+
feature: ${this.workflowId}
|
|
788
|
+
created: ${u}
|
|
789
|
+
based_on: SPEC-001
|
|
790
|
+
status: pending
|
|
791
|
+
estimated_effort: ${p.effort}
|
|
792
|
+
dependencies: ${JSON.stringify(p.dependencies)}
|
|
257
793
|
---
|
|
258
|
-
*Generated by WorkflowEngine (stub implementation)*
|
|
259
|
-
`;await rn(this.projectPath,this.workflowId,"spec",n)}async executeIntentsStage(t){console.log("[WorkflowEngine] Executing INTENTS stage (stub implementation)");let n=await Promise.resolve().then(()=>ie(on(),1)),o=await import("path"),r=o.join(this.projectPath,".olympus","workflow",this.workflowId,"intents");await n.ensureDir(r);let i=`# Intent: Implement ${this.featureName}
|
|
260
794
|
|
|
261
|
-
|
|
262
|
-
This is a placeholder intent file. The real intent-generator agent will
|
|
263
|
-
create detailed implementation intents.
|
|
795
|
+
# Task: ${p.title}
|
|
264
796
|
|
|
265
|
-
##
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
797
|
+
## Goal
|
|
798
|
+
|
|
799
|
+
${p.goal}
|
|
800
|
+
|
|
801
|
+
## Component
|
|
802
|
+
|
|
803
|
+
${p.component}
|
|
804
|
+
|
|
805
|
+
## Acceptance Criteria
|
|
806
|
+
|
|
807
|
+
${p.acceptanceCriteria.map(y=>`- [ ] ${y}`).join(`
|
|
808
|
+
`)}
|
|
809
|
+
|
|
810
|
+
## Implementation Steps
|
|
811
|
+
|
|
812
|
+
${p.steps.map((y,T)=>`${T+1}. ${y}`).join(`
|
|
813
|
+
`)}
|
|
814
|
+
|
|
815
|
+
## Technical Notes
|
|
816
|
+
|
|
817
|
+
${p.technicalNotes}
|
|
269
818
|
|
|
270
819
|
## Dependencies
|
|
271
|
-
|
|
820
|
+
|
|
821
|
+
${p.dependencies.length>0?p.dependencies.join(", "):"None"}
|
|
822
|
+
|
|
823
|
+
## Estimated Effort
|
|
824
|
+
|
|
825
|
+
${p.effort}h
|
|
272
826
|
|
|
273
827
|
---
|
|
274
|
-
*Generated by WorkflowEngine
|
|
275
|
-
`;await
|
|
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}
|
|
276
830
|
|
|
277
831
|
`;return r+=`Current stage: ${t.current_stage}
|
|
278
832
|
`,r+=`Status: ${t.status}
|
|
@@ -281,7 +835,7 @@ create detailed implementation intents.
|
|
|
281
835
|
|
|
282
836
|
`,r+=`Use: Task(subagent_type="${n}", prompt="...")
|
|
283
837
|
`):r+=`Next step: ${o}
|
|
284
|
-
`,r}function
|
|
838
|
+
`,r}function Da(e,t){let n=Na[t.current_stage],o=Pa(t.current_stage),r=`Resuming workflow for feature: ${e}
|
|
285
839
|
|
|
286
840
|
`;return r+=`You were interrupted during: ${t.current_stage}
|
|
287
841
|
`,r+=`Last update: ${t.updated_at}
|
|
@@ -294,7 +848,7 @@ create detailed implementation intents.
|
|
|
294
848
|
|
|
295
849
|
`,r+=`Use: Task(subagent_type="${n}", prompt="...")
|
|
296
850
|
`):r+=`Continue from where you left off: ${o}
|
|
297
|
-
`,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
|
|
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>
|
|
298
852
|
|
|
299
853
|
${r.join(`
|
|
300
854
|
|
|
@@ -304,21 +858,21 @@ ${r.join(`
|
|
|
304
858
|
|
|
305
859
|
---
|
|
306
860
|
|
|
307
|
-
`;return c.length
|
|
861
|
+
`;return c.length>Ua*4?c.substring(0,Ua*4)+`
|
|
308
862
|
...</learned-context>
|
|
309
863
|
|
|
310
864
|
---
|
|
311
865
|
|
|
312
|
-
`:c}function
|
|
313
|
-
`)}function
|
|
314
|
-
`)}function
|
|
315
|
-
`)}function
|
|
316
|
-
`)}function
|
|
317
|
-
`)}function
|
|
318
|
-
`)}var
|
|
319
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function
|
|
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?`
|
|
320
874
|
|
|
321
|
-
`+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=
|
|
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>
|
|
322
876
|
|
|
323
877
|
[ULTRAWORK MODE RESTORED]
|
|
324
878
|
|
|
@@ -331,7 +885,7 @@ Continue working in ultrawork mode until all tasks are complete.
|
|
|
331
885
|
|
|
332
886
|
---
|
|
333
887
|
|
|
334
|
-
`);let i=await
|
|
888
|
+
`);let i=await At(t,n);return i.count>0&&o.push(`<session-restore>
|
|
335
889
|
|
|
336
890
|
[PENDING TASKS DETECTED]
|
|
337
891
|
|
|
@@ -343,7 +897,7 @@ Please continue working on these tasks.
|
|
|
343
897
|
---
|
|
344
898
|
|
|
345
899
|
`),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
|
|
346
|
-
`)}}:{continue:!0}}})}var
|
|
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>
|
|
347
901
|
|
|
348
902
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
349
903
|
|
|
@@ -383,7 +937,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
383
937
|
|
|
384
938
|
---
|
|
385
939
|
|
|
386
|
-
`}function
|
|
940
|
+
`}function Xa(e){return`<ascent-continuation-after-rejection>
|
|
387
941
|
|
|
388
942
|
[ORACLE REJECTED - Continue Working]
|
|
389
943
|
|
|
@@ -408,7 +962,7 @@ Continue working now.
|
|
|
408
962
|
|
|
409
963
|
---
|
|
410
964
|
|
|
411
|
-
`}function
|
|
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?`
|
|
412
966
|
|
|
413
967
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
414
968
|
|
|
@@ -430,7 +984,7 @@ Original task: ${e.original_prompt}
|
|
|
430
984
|
|
|
431
985
|
---
|
|
432
986
|
|
|
433
|
-
`}function
|
|
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>
|
|
434
988
|
|
|
435
989
|
[ASCENT LOOP - ITERATION ${s.iteration}/${s.max_iterations}]
|
|
436
990
|
|
|
@@ -449,7 +1003,7 @@ ${s.prompt?`Original task: ${s.prompt}`:""}
|
|
|
449
1003
|
|
|
450
1004
|
---
|
|
451
1005
|
|
|
452
|
-
`,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function
|
|
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>
|
|
453
1007
|
|
|
454
1008
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
455
1009
|
|
|
@@ -472,7 +1026,7 @@ DO NOT stop until Oracle has approved.
|
|
|
472
1026
|
|
|
473
1027
|
---
|
|
474
1028
|
|
|
475
|
-
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=
|
|
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?`
|
|
476
1030
|
|
|
477
1031
|
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
478
1032
|
|
|
@@ -484,20 +1038,20 @@ ${ii}
|
|
|
484
1038
|
|
|
485
1039
|
---
|
|
486
1040
|
|
|
487
|
-
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function
|
|
488
|
-
`),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=
|
|
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+=`
|
|
489
1043
|
|
|
490
1044
|
[Rule: ${a.relativePath}]
|
|
491
1045
|
[Match: ${a.matchReason}]
|
|
492
|
-
${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=
|
|
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?`
|
|
493
1047
|
|
|
494
|
-
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${
|
|
1048
|
+
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${g}]`:"";f+=`
|
|
495
1049
|
|
|
496
|
-
[Project README: ${
|
|
497
|
-
${h}${
|
|
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
|
|
498
1052
|
option1
|
|
499
1053
|
option2
|
|
500
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
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=`
|
|
501
1055
|
|
|
502
1056
|
---
|
|
503
1057
|
|
|
@@ -523,7 +1077,7 @@ You should NOT:
|
|
|
523
1077
|
3. Verify the subagent's work after completion
|
|
524
1078
|
|
|
525
1079
|
---
|
|
526
|
-
`;var
|
|
1080
|
+
`;var Gc=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
527
1081
|
|
|
528
1082
|
You have an active work plan with incomplete tasks. Continue working.
|
|
529
1083
|
|
|
@@ -532,7 +1086,7 @@ RULES:
|
|
|
532
1086
|
- Mark each checkbox [x] in the plan file when done
|
|
533
1087
|
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
534
1088
|
- Do not stop until all tasks are complete
|
|
535
|
-
- If blocked, document the blocker and move to the next task`,
|
|
1089
|
+
- If blocked, document the blocker and move to the next task`,Bc=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
536
1090
|
|
|
537
1091
|
Subagents FREQUENTLY claim completion when:
|
|
538
1092
|
- Tests are actually FAILING
|
|
@@ -547,7 +1101,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
547
1101
|
3. Check build/typecheck - Must succeed
|
|
548
1102
|
|
|
549
1103
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
550
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
1104
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,qc=`
|
|
551
1105
|
|
|
552
1106
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
553
1107
|
|
|
@@ -570,7 +1124,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
570
1124
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
571
1125
|
|
|
572
1126
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
573
|
-
`,
|
|
1127
|
+
`,Yc=`
|
|
574
1128
|
|
|
575
1129
|
================================================================================
|
|
576
1130
|
HARD BLOCK: DELEGATION REQUIRED
|
|
@@ -609,41 +1163,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
|
|
|
609
1163
|
Delegate to a subagent to proceed.
|
|
610
1164
|
|
|
611
1165
|
================================================================================
|
|
612
|
-
`;var
|
|
613
|
-
`;(0,
|
|
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(`
|
|
614
1168
|
`).length,i=o.split(`
|
|
615
1169
|
`).length;return Math.abs(i-r)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
|
|
616
|
-
`).length:0}return 0}function
|
|
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(`
|
|
617
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(`
|
|
618
|
-
`)){let s=i.split(" ");if(s.length<3)continue;let[c,a,l]=s,u=c==="-"?0:parseInt(c,10),
|
|
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]
|
|
619
1173
|
No file changes detected.
|
|
620
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(`
|
|
621
|
-
`)}function
|
|
1175
|
+
`)}function Qc(e){let t=Bc;return e&&(t+=`
|
|
622
1176
|
|
|
623
1177
|
---
|
|
624
1178
|
|
|
625
1179
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
626
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
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`
|
|
627
1181
|
---
|
|
628
1182
|
|
|
629
1183
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
630
1184
|
|
|
631
1185
|
---
|
|
632
1186
|
|
|
633
|
-
${
|
|
1187
|
+
${Qc(n)}
|
|
634
1188
|
|
|
635
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
1189
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function nm(e,t,n){return Gc.replace(/{PLAN_NAME}/g,e)+`
|
|
636
1190
|
|
|
637
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
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:`
|
|
638
1192
|
## SUBAGENT WORK COMPLETED
|
|
639
1193
|
|
|
640
1194
|
${u}
|
|
641
1195
|
<system-reminder>
|
|
642
|
-
${
|
|
1196
|
+
${tm(d.plan_name,f,i)}
|
|
643
1197
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
644
1198
|
<system-reminder>
|
|
645
|
-
${
|
|
646
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
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=`
|
|
647
1201
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
648
1202
|
|
|
649
1203
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -654,7 +1208,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
654
1208
|
4. CONTINUE with corrected action based on the real file content
|
|
655
1209
|
|
|
656
1210
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
657
|
-
`;function
|
|
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
|
|
658
1212
|
|
|
659
1213
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
660
1214
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -692,13 +1246,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
692
1246
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
693
1247
|
|
|
694
1248
|
Detected comments/docstrings:
|
|
695
|
-
`,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},
|
|
696
|
-
`;
|
|
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(`
|
|
697
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(`
|
|
698
|
-
`).length,
|
|
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+=`
|
|
699
1253
|
File: ${o}
|
|
700
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?"...":""}
|
|
701
|
-
`}}return n}function
|
|
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
|
|
702
1256
|
|
|
703
1257
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
704
1258
|
|
|
@@ -745,13 +1299,13 @@ Before starting a new session:
|
|
|
745
1299
|
3. Document the current state of the task
|
|
746
1300
|
|
|
747
1301
|
You can copy this conversation summary to continue in a new session.
|
|
748
|
-
`;var ir={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var
|
|
749
|
-
`;
|
|
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+=`
|
|
750
1304
|
Token Details:
|
|
751
1305
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
752
1306
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
753
1307
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
754
|
-
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:nr,errorType:e?.errorType||"token_limit_exceeded"}}var
|
|
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]
|
|
755
1309
|
|
|
756
1310
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
757
1311
|
|
|
@@ -781,7 +1335,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
781
1335
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
782
1336
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
783
1337
|
|
|
784
|
-
Proceed with one of these strategies.`.trim()}function
|
|
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
|
|
785
1339
|
|
|
786
1340
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
787
1341
|
|
|
@@ -820,8 +1374,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
820
1374
|
|
|
821
1375
|
WARNING: Further messages may fail if context is not reduced.
|
|
822
1376
|
Action required: Run /compact now.
|
|
823
|
-
`;var
|
|
824
|
-
`;
|
|
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=`
|
|
825
1379
|
[Agent Usage Reminder]
|
|
826
1380
|
|
|
827
1381
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -845,7 +1399,7 @@ WHY:
|
|
|
845
1399
|
- Reduces context window usage in main session
|
|
846
1400
|
|
|
847
1401
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
848
|
-
`;function pr(e){return(0,
|
|
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}">
|
|
849
1403
|
|
|
850
1404
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
851
1405
|
|
|
@@ -871,27 +1425,27 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
871
1425
|
|
|
872
1426
|
---
|
|
873
1427
|
|
|
874
|
-
`}function
|
|
875
|
-
`;(0,Gl.appendFileSync)(Ll,t)}}function Bl(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 ql(e){let n=Bl(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Yl(e){let t=Bl(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 Ym(e){return Yl(e)!==null}function Vm(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Km(e,t){Y("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=Vm(n);return o.length===0?(Y("No tool_use IDs found"),!1):(Y("Found tool_use IDs to inject results for",o),!0)}async function Jm(e,t,n){Y("recoverThinkingBlockOrder",{sessionID:e});let o=ql(n);if(o!==null){let s=Wl(e,o);if(s)return Y("Found target message by index",{targetIndex:o,targetMessageID:s}),Er(e,s)}let r=yr(e);if(r.length===0)return Y("No orphan thinking messages found"),!1;Y("Found orphan thinking messages",r);let i=!1;for(let s of r)Er(e,s)&&(i=!0);return i}async function Xm(e,t){Y("recoverThinkingDisabledViolation",{sessionID:e});let n=kr(e);if(n.length===0)return Y("No messages with thinking blocks found"),!1;Y("Found messages with thinking blocks",n);let o=!1;for(let r of n)jl(r)&&(o=!0);return o}async function zm(e,t,n){Y("recoverEmptyContentMessage",{sessionID:e});let o=ql(n),r=t.info?.id,i=!1,s=Hl(e);for(let l of s)$t(l,fe)&&(i=!0);let c=Ul(e);for(let l of c)Mt(e,l,fe)&&(i=!0);if(o!==null){let l=Fl(e,o);if(l&&($t(l,fe)||Mt(e,l,fe)))return!0}if(r&&($t(r,fe)||Mt(e,r,fe)))return!0;let a=hr(e);for(let l of a)$t(l,fe)&&(i=!0),Mt(e,l,fe)&&(i=!0);return i}async function Qm(e,t,n,o){Y("handleSessionRecovery",{sessionID:e,error:t});let r=Yl(t);if(!r)return Y("Not a recoverable error"),{attempted:!1,success:!1};Y("Detected recoverable error type",r);try{let i=!1,s=n||{info:{},parts:[]};switch(r){case"tool_result_missing":i=await Km(e,s);break;case"thinking_block_order":i=await Jm(e,s,t);break;case"thinking_disabled_violation":i=await Xm(e,s);break;case"empty_content":i=await zm(e,s,t);break}Y("Recovery result",{errorType:r,success:i});let c=o?.customMessages?.[r]||Nn[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:i,message:i?c:void 0,errorType:r}}catch(i){return Y("Recovery failed with error",i),{attempted:!0,success:!1,errorType:r}}}function Vl(e){return Y("createSessionRecoveryHook",{config:e}),{onError:async t=>Qm(t.session_id,t.error,t.message,e),isRecoverable:t=>Ym(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Nn[t]?.message}}}function Kl(){let e=Vl();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 de=require("fs"),xn=require("path"),Jl=require("os");var Ft=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 Zm=1800*1e3,dt=(0,xn.join)((0,Jl.homedir)(),".claude",".olympus","background-tasks"),Pn=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Ft(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,de.existsSync)(dt)||(0,de.mkdirSync)(dt,{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)(dt,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,de.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,de.existsSync)(n)&&(0,de.unlinkSync)(n)}loadPersistedTasks(){if((0,de.existsSync)(dt))try{let{readdirSync:t}=require("fs"),n=t(dt);for(let o of n)if(o.endsWith(".json"))try{let r=(0,xn.join)(dt,o),i=(0,de.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??Zm;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(`
|
|
876
|
-
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},Sr;function Tr(e){return Sr||(Sr=new
|
|
877
|
-
`)}function
|
|
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?`
|
|
878
1432
|
[BACKGROUND TASK COMPLETED]
|
|
879
1433
|
`:`
|
|
880
1434
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
881
|
-
`,n=e.map(o=>
|
|
1435
|
+
`,n=e.map(o=>og(o)).join(`
|
|
882
1436
|
|
|
883
1437
|
`);return`${t}
|
|
884
1438
|
${n}
|
|
885
|
-
`}function
|
|
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).
|
|
886
1440
|
This is informational - continue if task requires it.
|
|
887
|
-
Consider: delegate to subagent, break into smaller tasks.`}}return
|
|
888
|
-
`;break;case 114:
|
|
889
|
-
`),c++,l=o,s=14;switch(
|
|
890
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
891
|
-
`+" ".repeat(t))}," ":{"\n":new Array(
|
|
892
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
893
|
-
`+" ".repeat(t))}};var Ln;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Ln||(Ln={}));function au(e,t=[],n=Ln.DEFAULT){let o=null,r=[],i=[];function s(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return cu(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 cu(e,t,n=Ln.DEFAULT){let o=Dn(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?w=>i===0&&E(w,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(E){return E?w=>i===0&&E(w,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 f=l(t.onObjectBegin),d=a(t.onObjectProperty),p=u(t.onObjectEnd),m=l(t.onArrayBegin),y=u(t.onArrayEnd),h=a(t.onLiteralValue),k=c(t.onSeparator),_=s(t.onComment),g=c(t.onError),N=n&&n.disallowComments,L=n&&n.allowTrailingComma;function I(){for(;;){let E=o.scan();switch(o.getTokenError()){case 4:T(14);break;case 5:T(15);break;case 3:T(13);break;case 1:N||T(11);break;case 2:T(12);break;case 6:T(16);break}switch(E){case 12:case 13:N?T(10):_();break;case 16:T(1);break;case 15:case 14:break;default:return E}}}function T(E,w=[],x=[]){if(g(E),w.length+x.length>0){let A=o.getToken();for(;A!==17;){if(w.indexOf(A)!==-1){I();break}else if(x.indexOf(A)!==-1)break;A=I()}}}function ke(E){let w=o.getTokenValue();return E?h(w):(d(w),r.push(w)),I(),!0}function S(){switch(o.getToken()){case 11:let E=o.getTokenValue(),w=Number(E);isNaN(w)&&(T(2),w=0),h(w);break;case 7:h(null);break;case 8:h(!0);break;case 9:h(!1);break;default:return!1}return I(),!0}function b(){return o.getToken()!==10?(T(3,[],[2,5]),!1):(ke(!1),o.getToken()===6?(k(":"),I(),M()||T(4,[],[2,5])):T(5,[],[2,5]),r.pop(),!0)}function R(){f(),I();let E=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(E||T(4,[],[]),k(","),I(),o.getToken()===2&&L)break}else E&&T(6,[],[]);b()||T(4,[],[2,5]),E=!0}return p(),o.getToken()!==2?T(7,[2],[]):I(),!0}function F(){m(),I();let E=!0,w=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(w||T(4,[],[]),k(","),I(),o.getToken()===4&&L)break}else w&&T(6,[],[]);E?(r.push(0),E=!1):r[r.length-1]++,M()||T(4,[],[4,5]),w=!0}return y(),E||r.pop(),o.getToken()!==4?T(8,[4],[]):I(),!0}function M(){switch(o.getToken()){case 3:return F();case 1:return R();case 10:return ke(!0);default:return S()}}return I(),o.getToken()===17?n.allowEmptyContent?!0:(T(4,[],[]),!1):M()?(o.getToken()!==17&&T(9,[],[]),!0):(T(4,[],[]),!1)}var lu;(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"})(lu||(lu={}));var uu;(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"})(uu||(uu={}));var du=au;var fu;(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"})(fu||(fu={}));var yg={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 Eg(){let e=process.env.XDG_CONFIG_HOME??(0,jt.join)((0,mu.homedir)(),".config");return{user:(0,jt.join)(e,"claude-olympus","config.jsonc"),project:(0,jt.join)(process.cwd(),".claude","olympus.jsonc")}}function pu(e){if(!(0,$n.existsSync)(e))return null;try{let t=(0,$n.readFileSync)(e,"utf-8"),n=[],o=du(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 Mn(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]=Mn(i,r):r!==void 0&&(n[o]=r)}return n}function Sg(){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 gu(){let e=Eg(),t={...yg},n=pu(e.user);n&&(t=Mn(t,n));let o=pu(e.project);o&&(t=Mn(t,o));let r=Sg();return t=Mn(t,r),t}function Tg(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function wg(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 _g(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function Og(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function hu(e,t){let n=gu(),o=Ir(e),r=Tg(n),i=!0,s=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(wg(n,u.name)&&Og(u.matcher,t.toolName))try{let f=await _g(()=>u.handler({...t,toolInput:a,messages:l}),r);if(f===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}f.continue||(i=!1,c=f.stopReason),f.message&&s.push(f.message),f.hookSpecificOutput?.additionalContext&&s.push(f.hookSpecificOutput.additionalContext),f.modifiedInput!==void 0&&(a=f.modifiedInput),f.modifiedMessages!==void 0&&(l=f.modifiedMessages)}catch(f){console.error(`[hook-router] ${u.name} error:`,f)}return{continue:i,message:s.length>0?s.join(`
|
|
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(`
|
|
894
1448
|
|
|
895
1449
|
---
|
|
896
1450
|
|
|
897
|
-
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}
|
|
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});
|