olympus-ai 3.4.1 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +631 -630
- package/dist/__tests__/workflow-engine/checkpoint.test.d.ts +7 -0
- package/dist/__tests__/workflow-engine/checkpoint.test.d.ts.map +1 -0
- package/dist/__tests__/workflow-engine/checkpoint.test.js +373 -0
- package/dist/__tests__/workflow-engine/checkpoint.test.js.map +1 -0
- package/dist/agents/definitions.d.ts.map +1 -1
- package/dist/agents/definitions.js +8 -0
- package/dist/agents/definitions.js.map +1 -1
- package/dist/agents/idea-intake.d.ts +20 -0
- package/dist/agents/idea-intake.d.ts.map +1 -0
- package/dist/agents/idea-intake.js +255 -0
- package/dist/agents/idea-intake.js.map +1 -0
- package/dist/agents/index.d.ts +4 -0
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +4 -0
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/intent-generator.d.ts +19 -0
- package/dist/agents/intent-generator.d.ts.map +1 -0
- package/dist/agents/intent-generator.js +303 -0
- package/dist/agents/intent-generator.js.map +1 -0
- package/dist/agents/prd-writer.d.ts +19 -0
- package/dist/agents/prd-writer.d.ts.map +1 -0
- package/dist/agents/prd-writer.js +236 -0
- package/dist/agents/prd-writer.js.map +1 -0
- package/dist/agents/prometheus.d.ts.map +1 -1
- package/dist/agents/prometheus.js +96 -2
- package/dist/agents/prometheus.js.map +1 -1
- package/dist/agents/spec-writer.d.ts +19 -0
- package/dist/agents/spec-writer.d.ts.map +1 -0
- package/dist/agents/spec-writer.js +528 -0
- package/dist/agents/spec-writer.js.map +1 -0
- package/dist/features/index.d.ts +1 -0
- package/dist/features/index.d.ts.map +1 -1
- package/dist/features/index.js +6 -0
- package/dist/features/index.js.map +1 -1
- package/dist/features/workflow-engine/artifacts.d.ts +96 -0
- package/dist/features/workflow-engine/artifacts.d.ts.map +1 -0
- package/dist/features/workflow-engine/artifacts.js +399 -0
- package/dist/features/workflow-engine/artifacts.js.map +1 -0
- package/dist/features/workflow-engine/checkpoint.d.ts +67 -0
- package/dist/features/workflow-engine/checkpoint.d.ts.map +1 -0
- package/dist/features/workflow-engine/checkpoint.js +249 -0
- package/dist/features/workflow-engine/checkpoint.js.map +1 -0
- package/dist/features/workflow-engine/engine.d.ts +128 -0
- package/dist/features/workflow-engine/engine.d.ts.map +1 -0
- package/dist/features/workflow-engine/engine.js +600 -0
- package/dist/features/workflow-engine/engine.js.map +1 -0
- package/dist/features/workflow-engine/execution.d.ts +99 -0
- package/dist/features/workflow-engine/execution.d.ts.map +1 -0
- package/dist/features/workflow-engine/execution.js +493 -0
- package/dist/features/workflow-engine/execution.js.map +1 -0
- package/dist/features/workflow-engine/hooks.d.ts +78 -0
- package/dist/features/workflow-engine/hooks.d.ts.map +1 -0
- package/dist/features/workflow-engine/hooks.js +188 -0
- package/dist/features/workflow-engine/hooks.js.map +1 -0
- package/dist/features/workflow-engine/index.d.ts +17 -0
- package/dist/features/workflow-engine/index.d.ts.map +1 -0
- package/dist/features/workflow-engine/index.js +19 -0
- package/dist/features/workflow-engine/index.js.map +1 -0
- package/dist/features/workflow-engine/types.d.ts +220 -0
- package/dist/features/workflow-engine/types.d.ts.map +1 -0
- package/dist/features/workflow-engine/types.js +8 -0
- package/dist/features/workflow-engine/types.js.map +1 -0
- package/dist/features/workflow-engine/validation.d.ts +128 -0
- package/dist/features/workflow-engine/validation.d.ts.map +1 -0
- package/dist/features/workflow-engine/validation.js +746 -0
- package/dist/features/workflow-engine/validation.js.map +1 -0
- package/dist/hooks/ascent-verifier/index.d.ts +52 -0
- package/dist/hooks/ascent-verifier/index.d.ts.map +1 -1
- package/dist/hooks/ascent-verifier/index.js +146 -0
- package/dist/hooks/ascent-verifier/index.js.map +1 -1
- package/dist/hooks/registrations/learning-capture.d.ts.map +1 -1
- package/dist/hooks/registrations/learning-capture.js +32 -9
- package/dist/hooks/registrations/learning-capture.js.map +1 -1
- package/dist/hooks/registrations/user-prompt-submit.d.ts.map +1 -1
- package/dist/hooks/registrations/user-prompt-submit.js +85 -0
- package/dist/hooks/registrations/user-prompt-submit.js.map +1 -1
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +310 -1
- package/dist/installer/index.js.map +1 -1
- package/dist/learning/session-state.d.ts.map +1 -1
- package/dist/learning/session-state.js +17 -0
- package/dist/learning/session-state.js.map +1 -1
- package/dist/learning/types.d.ts +3 -0
- package/dist/learning/types.d.ts.map +1 -1
- package/dist/shared/types.d.ts +17 -0
- package/dist/shared/types.d.ts.map +1 -1
- package/package.json +3 -1
- package/scripts/dist/hooks/olympus-hooks.cjs +208 -97
- package/scripts/rebrand.mjs +0 -206
|
@@ -1,26 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
`)){let c=i.indexOf(":");if(c===-1)continue;let a=i.slice(0,c).trim(),l=i.slice(c+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[a]=l}return{data:s,body:r}}function fo(e,t){if(!(0,K.existsSync)(e))return[];let n;try{n=(0,K.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let s=(0,X.join)(e,r.name),i=(0,X.basename)(r.name,".md");try{let c=(0,K.readFileSync)(s,"utf-8"),{data:a,body:l}=go(c),u={name:i,description:a.description||"",argumentHint:a["argument-hint"],model:a.model,agent:a.agent};o.push({name:i,path:s,metadata:u,content:l,scope:t})}catch{continue}}return o}function Dt(){let e=(0,X.join)(po,"commands"),t=(0,X.join)(process.cwd(),".claude","commands"),n=(0,X.join)(po,"skills"),o=fo(e,"user"),r=fo(t,"project"),s=[];if((0,K.existsSync)(n))try{let i=(0,K.readdirSync)(n,{withFileTypes:!0});for(let c of i){if(!c.isDirectory())continue;let a=(0,X.join)(n,c.name,"SKILL.md");if((0,K.existsSync)(a))try{let l=(0,K.readFileSync)(a,"utf-8"),{data:u,body:d}=go(l),f={name:u.name||c.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||c.name,path:a,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...s]}function Qe(e){return Dt().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function ta(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function na(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
3
|
+
"use strict";var yu=Object.create;var Ht=Object.defineProperty;var Eu=Object.getOwnPropertyDescriptor;var Su=Object.getOwnPropertyNames;var Tu=Object.getPrototypeOf,wu=Object.prototype.hasOwnProperty;var O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_u=(e,t)=>{for(var n in t)Ht(e,n,{get:t[n],enumerable:!0})},Rr=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Su(t))!wu.call(e,r)&&r!==n&&Ht(e,r,{get:()=>t[r],enumerable:!(o=Eu(t,r))||o.enumerable});return e};var ie=(e,t,n)=>(n=e!=null?yu(Tu(e)):{},Rr(t||!e||!e.__esModule?Ht(n,"default",{value:e,enumerable:!0}):n,e)),Ou=e=>Rr(Ht({},"__esModule",{value:!0}),e);var H=O(Zn=>{"use strict";Zn.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})};Zn.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((Sh,Ri)=>{var Pe=require("constants"),zu=process.cwd,Vt=null,Qu=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Vt||(Vt=zu.call(process)),Vt};try{process.cwd()}catch{}typeof process.chdir=="function"&&(eo=process.chdir,process.chdir=function(e){Vt=null,eo.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,eo));var eo;Ri.exports=Zu;function Zu(e){Pe.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,f,d){d&&process.nextTick(d)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,f,d,p){p&&process.nextTick(p)},e.lchownSync=function(){}),Qu==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function f(d,p,m){var y=Date.now(),h=0;u(d,p,function k(_){if(_&&(_.code==="EACCES"||_.code==="EPERM"||_.code==="EBUSY")&&Date.now()-y<6e4){setTimeout(function(){e.stat(p,function(g,N){g&&g.code==="ENOENT"?u(d,p,k):m(_)})},h),h<100&&(h+=10);return}m&&m(_)})}return Object.setPrototypeOf&&Object.setPrototypeOf(f,u),f})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function f(d,p,m,y,h,k){var _;if(k&&typeof k=="function"){var g=0;_=function(N,L,I){if(N&&N.code==="EAGAIN"&&g<10)return g++,u.call(e,d,p,m,y,h,_);k.apply(this,arguments)}}return u.call(e,d,p,m,y,h,_)}return Object.setPrototypeOf&&Object.setPrototypeOf(f,u),f})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(f,d,p,m,y){for(var h=0;;)try{return u.call(e,f,d,p,m,y)}catch(k){if(k.code==="EAGAIN"&&h<10){h++;continue}throw k}}})(e.readSync);function t(u){u.lchmod=function(f,d,p){u.open(f,Pe.O_WRONLY|Pe.O_SYMLINK,d,function(m,y){if(m){p&&p(m);return}u.fchmod(y,d,function(h){u.close(y,function(k){p&&p(h||k)})})})},u.lchmodSync=function(f,d){var p=u.openSync(f,Pe.O_WRONLY|Pe.O_SYMLINK,d),m=!0,y;try{y=u.fchmodSync(p,d),m=!1}finally{if(m)try{u.closeSync(p)}catch{}else u.closeSync(p)}return y}}function n(u){Pe.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(f,d,p,m){u.open(f,Pe.O_SYMLINK,function(y,h){if(y){m&&m(y);return}u.futimes(h,d,p,function(k){u.close(h,function(_){m&&m(k||_)})})})},u.lutimesSync=function(f,d,p){var m=u.openSync(f,Pe.O_SYMLINK),y,h=!0;try{y=u.futimesSync(m,d,p),h=!1}finally{if(h)try{u.closeSync(m)}catch{}else u.closeSync(m)}return y}):u.futimes&&(u.lutimes=function(f,d,p,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function o(u){return u&&function(f,d,p){return u.call(e,f,d,function(m){l(m)&&(m=null),p&&p.apply(this,arguments)})}}function r(u){return u&&function(f,d){try{return u.call(e,f,d)}catch(p){if(!l(p))throw p}}}function i(u){return u&&function(f,d,p,m){return u.call(e,f,d,p,function(y){l(y)&&(y=null),m&&m.apply(this,arguments)})}}function s(u){return u&&function(f,d,p){try{return u.call(e,f,d,p)}catch(m){if(!l(m))throw m}}}function c(u){return u&&function(f,d,p){typeof d=="function"&&(p=d,d=null);function m(y,h){h&&(h.uid<0&&(h.uid+=4294967296),h.gid<0&&(h.gid+=4294967296)),p&&p.apply(this,arguments)}return d?u.call(e,f,d,m):u.call(e,f,m)}}function a(u){return u&&function(f,d){var p=d?u.call(e,f,d):u.call(e,f);return p&&(p.uid<0&&(p.uid+=4294967296),p.gid<0&&(p.gid+=4294967296)),p}}function l(u){if(!u||u.code==="ENOSYS")return!0;var f=!process.getuid||process.getuid()!==0;return!!(f&&(u.code==="EINVAL"||u.code==="EPERM"))}}});var Ci=O((Th,Ai)=>{var bi=require("stream").Stream;Ai.exports=ef;function ef(e){return{ReadStream:t,WriteStream:n};function t(o,r){if(!(this instanceof t))return new t(o,r);bi.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,f){if(u){i.emit("error",u),i.readable=!1;return}i.fd=f,i.emit("open",f),i._read()})}function n(o,r){if(!(this instanceof n))return new n(o,r);bi.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 xi=O((wh,Ni)=>{"use strict";Ni.exports=nf;var tf=Object.getPrototypeOf||function(e){return e.__proto__};function nf(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:tf(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var et=O((_h,oo)=>{var D=require("fs"),of=Ii(),rf=Ci(),sf=xi(),Kt=require("util"),q,Xt;typeof Symbol=="function"&&typeof Symbol.for=="function"?(q=Symbol.for("graceful-fs.queue"),Xt=Symbol.for("graceful-fs.previous")):(q="___graceful-fs.queue",Xt="___graceful-fs.previous");function af(){}function Li(e,t){Object.defineProperty(e,q,{get:function(){return t}})}var Ge=af;Kt.debuglog?Ge=Kt.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Ge=function(){var e=Kt.format.apply(Kt,arguments);e="GFS4: "+e.split(/\n/).join(`
|
|
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;
|
|
5
|
+
|
|
6
|
+
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:o,destStat:r}=await yt.checkPaths(e,t,"copy",n);if(await yt.checkParentPaths(e,o,t,"copy"),!await es(e,t,n))return;let s=kt.dirname(t);await _f(s)||await wf(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?V.stat:V.lstat)(t);if(i.isDirectory())return Cf(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return If(i,e,t,n,o);if(i.isSymbolicLink())return Nf(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 If(e,t,n,o,r){if(!t)return Zi(e,n,o,r);if(r.overwrite)return await V.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 V.copyFile(t,n),o.preserveTimestamps){bf(e.mode)&&await Af(n,e.mode);let r=await V.stat(t);await Of(n,r.atime,r.mtime)}return V.chmod(n,e.mode)}function bf(e){return(e&128)===0}function Af(e,t){return V.chmod(e,t|128)}async function Cf(e,t,n,o,r){t||await V.mkdir(o),await vf(await V.opendir(n),async i=>{let s=kt.join(n,i.name),c=kt.join(o,i.name);if(await es(s,c,r)){let{destStat:l}=await yt.checkPaths(s,c,"copy",r);await ts(l,s,c,r)}}),t||await V.chmod(o,e.mode)}async function Nf(e,t,n,o){let r=await V.readlink(t);if(o.dereference&&(r=kt.resolve(process.cwd(),r)),!e)return V.symlink(r,n);let i=null;try{i=await V.readlink(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return V.symlink(r,n);throw s}if(o.dereference&&(i=kt.resolve(process.cwd(),i)),r!==i){if(yt.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(yt.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return await V.unlink(n),V.symlink(r,n)}ns.exports=Rf});var cs=O((Ph,as)=>{"use strict";var z=et(),Et=require("path"),xf=pe().mkdirsSync,Pf=ao().utimesMillisSync,St=Be();function Df(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
|
+
|
|
8
|
+
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:o,destStat:r}=St.checkPathsSync(e,t,"copy",n);if(St.checkParentPathsSync(e,o,t,"copy"),n.filter&&!n.filter(e,t))return;let i=Et.dirname(t);return z.existsSync(i)||xf(i),rs(r,e,t,n)}function rs(e,t,n,o){let i=(o.dereference?z.statSync:z.lstatSync)(t);if(i.isDirectory())return Hf(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Lf(i,e,t,n,o);if(i.isSymbolicLink())return Bf(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 Lf(e,t,n,o,r){return t?Mf(e,n,o,r):is(e,n,o,r)}function Mf(e,t,n,o){if(o.overwrite)return z.unlinkSync(n),is(e,t,n,o);if(o.errorOnExist)throw new Error(`'${n}' already exists`)}function is(e,t,n,o){return z.copyFileSync(t,n),o.preserveTimestamps&&$f(e.mode,t,n),lo(n,e.mode)}function $f(e,t,n){return Ff(e)&&Uf(n,e),jf(t,n)}function Ff(e){return(e&128)===0}function Uf(e,t){return lo(e,t|128)}function lo(e,t){return z.chmodSync(e,t)}function jf(e,t){let n=z.statSync(e);return Pf(t,n.atime,n.mtime)}function Hf(e,t,n,o,r){return t?ss(n,o,r):Wf(e.mode,n,o,r)}function Wf(e,t,n,o){return z.mkdirSync(n),ss(t,n,o),lo(n,e)}function ss(e,t,n){let o=z.opendirSync(e);try{let r;for(;(r=o.readSync())!==null;)Gf(r.name,e,t,n)}finally{o.closeSync()}}function Gf(e,t,n,o){let r=Et.join(t,e),i=Et.join(n,e);if(o.filter&&!o.filter(r,i))return;let{destStat:s}=St.checkPathsSync(r,i,"copy",o);return rs(s,r,i,o)}function Bf(e,t,n,o){let r=z.readlinkSync(t);if(o.dereference&&(r=Et.resolve(process.cwd(),r)),e){let i;try{i=z.readlinkSync(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return z.symlinkSync(r,n);throw s}if(o.dereference&&(i=Et.resolve(process.cwd(),i)),r!==i){if(St.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(St.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return qf(r,n)}else return z.symlinkSync(r,n)}function qf(e,t){return z.unlinkSync(t),z.symlinkSync(e,t)}as.exports=Df});var Qt=O((Dh,ls)=>{"use strict";var Yf=H().fromPromise;ls.exports={copy:Yf(os()),copySync:cs()}});var Tt=O((Lh,fs)=>{"use strict";var us=et(),Vf=H().fromCallback;function Kf(e,t){us.rm(e,{recursive:!0,force:!0},t)}function Jf(e){us.rmSync(e,{recursive:!0,force:!0})}fs.exports={remove:Vf(Kf),removeSync:Jf}});var Es=O((Mh,ys)=>{"use strict";var Xf=H().fromPromise,ms=X(),gs=require("path"),hs=pe(),ks=Tt(),ds=Xf(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:ds,emptydir:ds}});var _s=O(($h,ws)=>{"use strict";var zf=H().fromPromise,Ss=require("path"),Oe=X(),Ts=pe();async function Qf(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 Zf(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:zf(Qf),createFileSync:Zf}});var bs=O((Fh,Is)=>{"use strict";var ed=H().fromPromise,Os=require("path"),Le=X(),vs=pe(),{pathExists:td}=De(),{areIdentical:Rs}=Be();async function nd(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 td(r)||await vs.mkdirs(r),await Le.link(e,t)}function od(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:ed(nd),createLinkSync:od}});var Cs=O((Uh,As)=>{"use strict";var Me=require("path"),wt=X(),{pathExists:rd}=De(),id=H().fromPromise;async function sd(e,t){if(Me.isAbsolute(e)){try{await wt.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 rd(o))return{toCwd:o,toDst:e};try{await wt.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:Me.relative(n,e)}}function ad(e,t){if(Me.isAbsolute(e)){if(!wt.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(wt.existsSync(o))return{toCwd:o,toDst:e};if(!wt.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:Me.relative(n,e)}}As.exports={symlinkPaths:id(sd),symlinkPathsSync:ad}});var Ps=O((jh,xs)=>{"use strict";var Ns=X(),cd=H().fromPromise;async function ld(e,t){if(t)return t;let n;try{n=await Ns.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function ud(e,t){if(t)return t;let n;try{n=Ns.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}xs.exports={symlinkType:cd(ld),symlinkTypeSync:ud}});var $s=O((Hh,Ms)=>{"use strict";var fd=H().fromPromise,Ds=require("path"),Se=X(),{mkdirs:dd,mkdirsSync:pd}=pe(),{symlinkPaths:md,symlinkPathsSync:gd}=Cs(),{symlinkType:hd,symlinkTypeSync:kd}=Ps(),{pathExists:yd}=De(),{areIdentical:Ls}=Be();async function Ed(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 md(e,t);e=r.toDst;let i=await hd(r.toCwd,n),s=Ds.dirname(t);return await yd(s)||await dd(s),Se.symlink(e,t,i)}function Sd(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=gd(e,t);e=r.toDst,n=kd(r.toCwd,n);let i=Ds.dirname(t);return Se.existsSync(i)||pd(i),Se.symlinkSync(e,t,n)}Ms.exports={createSymlink:fd(Ed),createSymlinkSync:Sd}});var qs=O((Wh,Bs)=>{"use strict";var{createFile:Fs,createFileSync:Us}=_s(),{createLink:js,createLinkSync:Hs}=bs(),{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 Zt=O((Gh,Ys)=>{function Td(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 wd(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}Ys.exports={stringify:Td,stripBom:wd}});var Xs=O((Bh,Js)=>{var ot;try{ot=et()}catch{ot=require("fs")}var en=H(),{stringify:Vs,stripBom:Ks}=Zt();async function _d(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||ot,o="throws"in t?t.throws:!0,r=await en.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 Od=en.fromPromise(_d);function vd(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||ot,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 Rd(e,t,n={}){let o=n.fs||ot,r=Vs(t,n);await en.fromCallback(o.writeFile)(e,r,n)}var Id=en.fromPromise(Rd);function bd(e,t,n={}){let o=n.fs||ot,r=Vs(t,n);return o.writeFileSync(e,r,n)}Js.exports={readFile:Od,readFileSync:vd,writeFile:Id,writeFileSync:bd}});var Qs=O((qh,zs)=>{"use strict";var tn=Xs();zs.exports={readJson:tn.readFile,readJsonSync:tn.readFileSync,writeJson:tn.writeFile,writeJsonSync:tn.writeFileSync}});var nn=O((Yh,ta)=>{"use strict";var Ad=H().fromPromise,uo=X(),Zs=require("path"),ea=pe(),Cd=De().pathExists;async function Nd(e,t,n="utf-8"){let o=Zs.dirname(e);return await Cd(o)||await ea.mkdirs(o),uo.writeFile(e,t,n)}function xd(e,...t){let n=Zs.dirname(e);uo.existsSync(n)||ea.mkdirsSync(n),uo.writeFileSync(e,...t)}ta.exports={outputFile:Ad(Nd),outputFileSync:xd}});var oa=O((Vh,na)=>{"use strict";var{stringify:Pd}=Zt(),{outputFile:Dd}=nn();async function Ld(e,t,n={}){let o=Pd(t,n);await Dd(e,o,n)}na.exports=Ld});var ia=O((Kh,ra)=>{"use strict";var{stringify:Md}=Zt(),{outputFileSync:$d}=nn();function Fd(e,t,n){let o=Md(t,n);$d(e,o,n)}ra.exports=Fd});var aa=O((Jh,sa)=>{"use strict";var Ud=H().fromPromise,Q=Qs();Q.outputJson=Ud(oa());Q.outputJsonSync=ia();Q.outputJSON=Q.outputJson;Q.outputJSONSync=Q.outputJsonSync;Q.writeJSON=Q.writeJson;Q.writeJSONSync=Q.writeJsonSync;Q.readJSON=Q.readJson;Q.readJSONSync=Q.readJsonSync;sa.exports=Q});var da=O((Xh,fa)=>{"use strict";var jd=X(),ca=require("path"),{copy:Hd}=Qt(),{remove:ua}=Tt(),{mkdirp:Wd}=pe(),{pathExists:Gd}=De(),la=Be();async function Bd(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 Wd(s),qd(e,t,o,i)}async function qd(e,t,n,o){if(!o){if(n)await ua(t);else if(await Gd(t))throw new Error("dest already exists.")}try{await jd.rename(e,t)}catch(r){if(r.code!=="EXDEV")throw r;await Yd(e,t,n)}}async function Yd(e,t,n){return await Hd(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ua(e)}fa.exports=Bd});var ka=O((zh,ha)=>{"use strict";var ma=et(),po=require("path"),Vd=Qt().copySync,ga=Tt().removeSync,Kd=pe().mkdirpSync,pa=Be();function Jd(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"),Xd(t)||Kd(po.dirname(t)),zd(e,t,o,i)}function Xd(e){let t=po.dirname(e);return po.parse(t).root===t}function zd(e,t,n,o){if(o)return fo(e,t,n);if(n)return ga(t),fo(e,t,n);if(ma.existsSync(t))throw new Error("dest already exists.");return fo(e,t,n)}function fo(e,t,n){try{ma.renameSync(e,t)}catch(o){if(o.code!=="EXDEV")throw o;return Qd(e,t,n)}}function Qd(e,t,n){return Vd(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ga(e)}ha.exports=Jd});var Ea=O((Qh,ya)=>{"use strict";var Zd=H().fromPromise;ya.exports={move:Zd(da()),moveSync:ka()}});var on=O((Zh,Sa)=>{"use strict";Sa.exports={...X(),...Qt(),...Es(),...qs(),...aa(),...pe(),...Ea(),...nn(),...De(),...Tt()}});var Ig={};_u(Ig,{main:()=>ku});module.exports=Ou(Ig);var Un=new Map;function v(e){let t=Un.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),Un.set(e.event,t)}function Ir(e){return Un.get(e)||[]}var vu={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},Ru=["ultrawork","ultrathink","olympus","search","analyze"];function br(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function Ar(e,t){let n=[];for(let o of Ru){let r=vu[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",Wt="<auto-slash-command>",Gt="</auto-slash-command>",Nr=/^\/([a-zA-Z][\w-]*)\s*(.*)/,xr=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Iu=/```[\s\S]*?```/g;function Pr(e){return e.replace(Iu,"")}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 xr.has(e.toLowerCase())}function jn(e){let n=Pr(e).trim();if(!n.startsWith("/"))return null;let o=Dr(n);return!o||Lr(o.command)?null:o}function Hn(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 Wn(){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:f}=Ur(l),d={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:d,content:f,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...i]}function Bt(e){return Wn().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function bu(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function Au(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
5
11
|
`),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
|
|
6
12
|
`),t&&n.push(`**Arguments**: ${t}
|
|
7
13
|
`),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
|
|
8
14
|
`),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
|
|
9
15
|
`),n.push(`**Scope**: ${e.scope}
|
|
10
16
|
`),n.push(`---
|
|
11
|
-
`);let o=
|
|
17
|
+
`);let o=bu(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
|
|
12
18
|
|
|
13
19
|
---
|
|
14
20
|
`),n.push(`## User Request
|
|
15
21
|
`),n.push(t)),n.join(`
|
|
16
|
-
`)}function
|
|
17
|
-
${
|
|
18
|
-
${
|
|
22
|
+
`)}function Gn(e){let t=Bt(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:Au(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function Bn(){return Wn().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var qt=new Set;function jr(){return{name:Cr,processMessage:(e,t)=>{let n=Hn(t);if(n.includes(Wt)||n.includes(Gt))return{detected:!1};let o=jn(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(qt.has(r))return{detected:!1};qt.add(r);let i=Gn(o);if(i.success&&i.replacementText){let c=`${Wt}
|
|
23
|
+
${i.replacementText}
|
|
24
|
+
${Gt}`;return{detected:!0,parsedCommand:o,injectedMessage:c}}let s=`${Wt}
|
|
19
25
|
[AUTO-SLASH-COMMAND ERROR]
|
|
20
|
-
${
|
|
26
|
+
${i.error}
|
|
21
27
|
|
|
22
28
|
Original input: ${o.raw}
|
|
23
|
-
${
|
|
29
|
+
${Gt}`;return{detected:!0,parsedCommand:o,injectedMessage:s}},listCommands:()=>Bn(),findCommand:e=>Bt(e),clearSession:e=>{let t=[];for(let n of qt)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)qt.delete(n)}}}var Cu=[/\bultrathink\b/i,/\bthink\b/i],Nu=["\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"],xu=Nu.map(e=>new RegExp(e,"i")),Pu=[...Cu,...xu],Du=/```[\s\S]*?```/g,Lu=/`[^`]+`/g;function Mu(e){return e.replace(Du,"").replace(Lu,"")}function Hr(e){let t=Mu(e);return Pu.some(n=>n.test(t))}function Wr(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function qn(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function Yn(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"}},$u={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=Yn(e),{prefix:n,base:o}=qn(t);if(Br.has(o)||o.endsWith("-high"))return null;let r=Gr[o];return r?n+r:null}function Vn(e){let t=Yn(e),{base:n}=qn(t);return Br.has(n)||n.endsWith("-high")}function Fu(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 Uu(e){return e in qr}function Vr(e,t){let n=Yn(t),{base:o}=qn(n);if(Vn(n))return null;let r=Fu(e,t);if(!Uu(r))return null;let i=qr[r],s=$u[r];if(!s)return null;let c=o.toLowerCase();return s.some(l=>c.includes(l.toLowerCase()))?i:null}var Ae=new Map;function ju(e){Ae.delete(e)}function Kr(){return{processChatParams:(e,t)=>{let n=Wr(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!Hr(n))return Ae.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,Vn(r.modelId)))return Ae.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),Ae.set(e,o),o},onSessionDeleted:e=>{Ae.delete(e)},isRequested:e=>Ae.get(e)?.requested??!1,getState:e=>Ae.get(e),clear:ju}}var U=require("fs"),Xe=require("path"),Kn=require("os");function Jn(e){let t=e||process.cwd(),n=(0,Xe.join)(t,".olympus");return(0,Xe.join)(n,"ultrawork-state.json")}function Xn(){return(0,Xe.join)((0,Kn.homedir)(),".claude","ultrawork-state.json")}function Hu(e){let t=e||process.cwd(),n=(0,Xe.join)(t,".olympus");(0,U.existsSync)(n)||(0,U.mkdirSync)(n,{recursive:!0})}function Wu(){let e=(0,Xe.join)((0,Kn.homedir)(),".claude");(0,U.existsSync)(e)||(0,U.mkdirSync)(e,{recursive:!0})}function He(e){let t=Jn(e);if((0,U.existsSync)(t))try{let o=(0,U.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Xn();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{Hu(t);let n=Jn(t);(0,U.writeFileSync)(n,JSON.stringify(e,null,2)),Wu();let o=Xn();return(0,U.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Xr(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 zr(e){let t=Jn(e);if((0,U.existsSync)(t))try{(0,U.unlinkSync)(t)}catch{}let n=Xn();if((0,U.existsSync)(n))try{return(0,U.unlinkSync)(n),!0}catch{return!1}return!0}function Qr(e){let t=He(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>
|
|
24
30
|
|
|
25
31
|
[ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
|
|
26
32
|
|
|
@@ -41,7 +47,7 @@ Original task: ${e.original_prompt}
|
|
|
41
47
|
|
|
42
48
|
---
|
|
43
49
|
|
|
44
|
-
`}var
|
|
50
|
+
`}var ei=require("os"),B=require("path");function Ee(){return process.platform==="win32"}function Gu(){return(0,B.join)((0,ei.homedir)(),".claude")}function Z(){return(0,B.join)(Gu(),"hooks")}var ti=`<ultrawork-mode>
|
|
45
51
|
|
|
46
52
|
**MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
|
|
47
53
|
|
|
@@ -132,7 +138,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
|
|
|
132
138
|
|
|
133
139
|
---
|
|
134
140
|
|
|
135
|
-
`,
|
|
141
|
+
`,ni=`<think-mode>
|
|
136
142
|
|
|
137
143
|
**ULTRATHINK MODE ENABLED** - Extended reasoning activated.
|
|
138
144
|
|
|
@@ -148,7 +154,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
|
|
|
148
154
|
|
|
149
155
|
---
|
|
150
156
|
|
|
151
|
-
`;var
|
|
157
|
+
`;var oi=`<search-mode>
|
|
152
158
|
MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
|
|
153
159
|
- explore agents (codebase patterns, file structures)
|
|
154
160
|
- librarian agents (remote repos, official docs, GitHub examples)
|
|
@@ -158,7 +164,7 @@ NEVER stop at first result - be exhaustive.
|
|
|
158
164
|
|
|
159
165
|
---
|
|
160
166
|
|
|
161
|
-
`,
|
|
167
|
+
`,ri=`<analyze-mode>
|
|
162
168
|
ANALYSIS MODE. Gather context before diving deep:
|
|
163
169
|
|
|
164
170
|
CONTEXT GATHERING (parallel):
|
|
@@ -174,16 +180,121 @@ SYNTHESIZE findings before proceeding.
|
|
|
174
180
|
|
|
175
181
|
---
|
|
176
182
|
|
|
177
|
-
`,
|
|
183
|
+
`,ii=`[SYSTEM REMINDER - TODO CONTINUATION]
|
|
178
184
|
|
|
179
185
|
Incomplete tasks remain in your todo list. Continue working on the next pending task.
|
|
180
186
|
|
|
181
187
|
- Proceed without asking for permission
|
|
182
188
|
- Mark each task complete when finished
|
|
183
|
-
- Do not stop until all tasks are done`;var
|
|
184
|
-
`).filter(r=>r.trim()).length;if(o>=t){let r=new Date().toISOString().replace(/[:.]/g,"-"),
|
|
185
|
-
`,"utf-8")}function
|
|
186
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n)):[]}function Fo(){return Ea()}function $o(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,s=n.filter(u=>u.event_type==="revision").length,i=n.filter(u=>u.event_type==="cancellation").length,c=o>0?r/o:0,a,l=n.filter(u=>Yt(u)!==null);if(l.length>0){let u=l.filter(h=>h.event_type==="success"),d=l.filter(h=>h.event_type==="revision"||h.event_type==="cancellation"),f=l.reduce((h,_)=>h+Te(_),0),E=u.reduce((h,_)=>h+Te(_),0),S=d.reduce((h,_)=>h+Te(_),0),O=u.length>0?E/u.length:0,R=d.length>0?S/d.length:0;if(a={avg_tokens_per_success:O,avg_tokens_per_failure:R,total_tokens:f,invocation_count:l.length,efficiency_score:O,trend:"insufficient_data"},l.length>=10){let h=Math.floor(l.length/2),_=l.slice(0,h),p=l.slice(h),I=_.reduce((ge,Ne)=>ge+Te(Ne),0)/_.length,y=p.reduce((ge,Ne)=>ge+Te(Ne),0)/p.length-I,m=I*.1;Math.abs(y)<m?a.trend="stable":y<0?a.trend="improving":a.trend="declining"}}return{agent_name:e,total_invocations:o,success_count:r,revision_count:s,cancellation_count:i,success_rate:c,failure_patterns:[],strong_areas:[],weak_areas:[],last_updated:new Date().toISOString(),token_efficiency:a}}function ke(e,t){if(!(0,A.existsSync)(e))return t;try{return JSON.parse((0,A.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function Ho(e,t){try{let n=(0,te.dirname)(e);n&&!(0,A.existsSync)(n)&&(0,A.mkdirSync)(n,{recursive:!0}),(0,A.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}var Yo=require("crypto");function le(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 ya=10,Sa=1800*1e3;function Wo(e){return(0,Bo.join)(e,".olympus","session-state.json")}function Go(e,t){let n=le(t);return{session_id:e||(0,Yo.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,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}}}function D(e,t){let n=Wo(e),o=ke(n,null);if(!o)return Go(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>Sa)return Go(t,e);if(!o.token_budget){let i=le(e);o.token_budget={session_baseline:i,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o}function P(e,t){let n=Wo(e);t.last_updated=new Date().toISOString(),Ho(n,t)}function Vo(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,ya),e.last_updated=new Date().toISOString(),e}function Ko(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function et(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 qo(e,t){let n=le(t);return e.token_budget={session_baseline:n,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function Jo(e,t){return e.token_budget||(e.token_budget={session_baseline:le(),current_usage: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 Xo(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function zo(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 Qo=require("crypto"),Oa={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 Wt(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Oa))for(let{regex:s,confidence:i}of r)s.test(t)&&(!n||i>n.confidence)&&(n={category:o,confidence:i});return n}async function Zo(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=D(n,o),s=Wt(t),i=Vo(r,t,s?.category);if(s&&et(r)){let c={id:(0,Qo.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:s.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:s.category,confidence:s.confidence};oe(c)}P(n,i)}var er=require("crypto");async function tr(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=D(n,o);if(!et(r))return;let s=Wt(t),i=s?.category==="praise"&&s.confidence>.7,c=_a(t,r.pending_completion?.task_description||"");if(i||c){let a={id:(0,er.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:i?"praise":"enhancement",confidence:i?s.confidence:.6};oe(a);let l=Ko(r);P(n,l)}}function _a(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),s=new Set([...o].filter(a=>r.has(a))),i=new Set([...o,...r]);return(i.size>0?s.size/i.size:0)<.2}function nr(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 or(){g({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=nr(e);if(!t)return{continue:!0};let n=oo(t),o=ro(n);if(o.length===0)return{continue:!0};let r=o.some(a=>a.type==="ultrawork"),s=o.some(a=>a.type==="ultrathink"),i=o.some(a=>a.type==="search"),c=o.some(a=>a.type==="analyze");return r?(Ao(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Co}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:xo}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Po}}:c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Lo}}:{continue:!0}}}),g({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=ho().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),g({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Ro(),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}}}),g({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=nr(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Zo({prompt:t,directory:e.directory,sessionId:e.sessionId}),await tr({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var ue=require("fs"),re=require("path"),rr=require("os");function Ra(e,t){let n=(0,re.join)((0,rr.homedir)(),".claude"),o=[];e&&(o.push((0,re.join)(n,"sessions",e,"todos.json")),o.push((0,re.join)(n,"todos",`${e}.json`))),t&&(o.push((0,re.join)(t,".olympus","todos.json")),o.push((0,re.join)(t,".claude","todos.json")));let r=(0,re.join)(n,"todos");if((0,ue.existsSync)(r))try{let s=(0,ue.readdirSync)(r);for(let i of s)i.endsWith(".json")&&o.push((0,re.join)(r,i))}catch{}return o}function Ia(e){try{let t=(0,ue.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 Aa(e){return e.status!=="completed"&&e.status!=="cancelled"}async function xe(e,t){let n=Ra(e,t),o=new Set,r=[],s=[];for(let i of n){if(!(0,ue.existsSync)(i))continue;let c=Ia(i);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),Aa(a)&&s.push(a))}}return{count:s.length,todos:s,total:r.length}}function sr(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var tt=require("path");function ir(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}var ar=500;function cr(e){let t=ke((0,tt.join)(ne(),"user-preferences.json"),null),n=ke((0,tt.join)(Ce(e),"patterns.json"),null),o=ke((0,tt.join)(ne(),"agent-performance.json"),{}),r=[];t&&ba(t)&&r.push(wa(t)),n&&n.conventions.length>0&&r.push(va(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(Na(t.recurring_corrections.slice(0,5)));let s=Object.values(o).filter(a=>a.weak_areas.length>0);s.length>0&&r.push(Ca(s));let i=xa(o);if(i&&r.push(i),r.length===0)return"";let c=`<learned-context>
|
|
189
|
+
- Do not stop until all tasks are done`;var th={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"'}]}]}},nh={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Ee()?`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:Ee()?`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:Ee()?`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:Ee()?`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:Ee()?`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:Ee()?`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:Ee()?`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,B.join)(Z(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};var pi=require("path");var si=require("os"),Ce=require("path"),$=require("fs"),Bu=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 qu=1e4;function Ne(){return(0,Ce.join)((0,si.homedir)(),".claude","olympus","learning")}function gt(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=gt(e);(0,$.existsSync)(n)||(0,$.mkdirSync)(n,{recursive:!0})}}function ci(e,t=qu){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 xe(e){ai();let t=(0,Ce.join)(Ne(),"feedback-log.jsonl");ci(t),(0,$.appendFileSync)(t,JSON.stringify(e)+`
|
|
191
|
+
`,"utf-8")}function Yu(){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 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 ho(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function ko(e){let t=new Map,n=e.split(`
|
|
194
|
+
`),o=null,r=[];for(let i of n){let s=i.match(/^##\s+(.+)$/);s?(o&&t.set(o,r.join(`
|
|
195
|
+
`)),o=s[1].trim(),r=[]):o&&r.push(i)}return o&&t.set(o,r.join(`
|
|
196
|
+
`)),t}function Ia(e){let t=e.split(`
|
|
197
|
+
`),n=0;for(let o of t)o.trim().match(/^[-*+]\s+/)&&n++;return n}async function ba(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,sn.readFileSync)(e,"utf-8")}catch(y){let h=y;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,sn.readFileSync)(t,"utf-8")}catch(y){let h=y;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=ho(i),a=ko(s).get("Constraints"),l=a?Ia(a):0,u=ho(r),f=ko(u),d=0;for(let y of u.split(`
|
|
198
|
+
`))y.match(/^###?\s+US-\d+/)&&d++;let p=f.has("Requirement Coverage"),m=l>0?Math.round(Math.min(d,l)/l*100):100;return d===0&&o.push("No user stories found in PRD"),p||o.push("Missing Requirement Coverage section"),m<90&&o.push(`Coverage only ${m}%, need at least 90% (${d}/${l} constraints addressed)`),{passed:o.length===0&&m>=90,coverage_percentage:m,blocking_issues:o,reviewer:"momus",timestamp:n}}var an=["idea","prd","spec","intents","complete"];function sp(e){let t=an.indexOf(e);return t===-1||t>=an.length-1?"complete":an[t+1]}var cn=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=sp(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 an){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(`
|
|
199
|
+
[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] Agent invocation: idea-intake (stub - would be invoked here)");let o=`# Feature Idea: ${this.featureName}
|
|
200
|
+
|
|
201
|
+
## Initial Prompt
|
|
202
|
+
${n}
|
|
203
|
+
|
|
204
|
+
## Summary
|
|
205
|
+
This is a placeholder idea document. The real idea-intake agent will generate
|
|
206
|
+
a proper analysis of the feature requirements.
|
|
207
|
+
|
|
208
|
+
## Key Requirements
|
|
209
|
+
- [To be filled by idea-intake agent]
|
|
210
|
+
|
|
211
|
+
## User Stories
|
|
212
|
+
- [To be filled by idea-intake agent]
|
|
213
|
+
|
|
214
|
+
## Acceptance Criteria
|
|
215
|
+
- [To be filled by idea-intake agent]
|
|
216
|
+
|
|
217
|
+
---
|
|
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
|
+
|
|
221
|
+
## Overview
|
|
222
|
+
This is a placeholder PRD document. The real prd-writer agent will generate
|
|
223
|
+
a comprehensive product requirements document.
|
|
224
|
+
|
|
225
|
+
## Business Requirements
|
|
226
|
+
- [To be filled by prd-writer agent]
|
|
227
|
+
|
|
228
|
+
## Functional Requirements
|
|
229
|
+
- [To be filled by prd-writer agent]
|
|
230
|
+
|
|
231
|
+
## Non-Functional Requirements
|
|
232
|
+
- [To be filled by prd-writer agent]
|
|
233
|
+
|
|
234
|
+
## Success Metrics
|
|
235
|
+
- [To be filled by prd-writer agent]
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
*Generated by WorkflowEngine (stub implementation)*
|
|
239
|
+
`;await rn(this.projectPath,this.workflowId,"prd",o);let r=Ot(this.projectPath,this.workflowId,"prd");console.log(`[WorkflowEngine] Validating PRD artifact at: ${r}`);let i=await ba(r,n);t.validation_results.prd=i,i.passed?(console.log("[WorkflowEngine] PRD validation passed"),console.log(`[WorkflowEngine] Coverage: ${i.coverage_percentage}%`)):(console.log("[WorkflowEngine] PRD validation failed:",i.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${i.coverage_percentage}%`))}async executeSpecStage(t){console.log("[WorkflowEngine] Executing SPEC stage (stub implementation)");let n=`# Technical Specification: ${this.featureName}
|
|
240
|
+
|
|
241
|
+
## Overview
|
|
242
|
+
This is a placeholder technical specification. The real spec-writer agent will
|
|
243
|
+
generate a detailed technical specification.
|
|
244
|
+
|
|
245
|
+
## Architecture
|
|
246
|
+
- [To be filled by spec-writer agent]
|
|
247
|
+
|
|
248
|
+
## Data Models
|
|
249
|
+
- [To be filled by spec-writer agent]
|
|
250
|
+
|
|
251
|
+
## API Design
|
|
252
|
+
- [To be filled by spec-writer agent]
|
|
253
|
+
|
|
254
|
+
## Implementation Notes
|
|
255
|
+
- [To be filled by spec-writer agent]
|
|
256
|
+
|
|
257
|
+
---
|
|
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
|
+
|
|
261
|
+
## Description
|
|
262
|
+
This is a placeholder intent file. The real intent-generator agent will
|
|
263
|
+
create detailed implementation intents.
|
|
264
|
+
|
|
265
|
+
## Tasks
|
|
266
|
+
- [ ] Task 1: [To be filled by intent-generator agent]
|
|
267
|
+
- [ ] Task 2: [To be filled by intent-generator agent]
|
|
268
|
+
- [ ] Task 3: [To be filled by intent-generator agent]
|
|
269
|
+
|
|
270
|
+
## Dependencies
|
|
271
|
+
- [To be filled by intent-generator agent]
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
*Generated by WorkflowEngine (stub implementation)*
|
|
275
|
+
`;await n.writeFile(o.join(r,"intent-001.md"),i,"utf-8")}};var Aa={idea:"idea-intake",prd:"prd-writer",spec:"spec-writer",intents:"intent-generator",complete:null};function Ca(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 Na(e,t){let n=Aa[t.current_stage],o=Ca(t.current_stage),r=`You are beginning a structured workflow for feature: ${e}
|
|
276
|
+
|
|
277
|
+
`;return r+=`Current stage: ${t.current_stage}
|
|
278
|
+
`,r+=`Status: ${t.status}
|
|
279
|
+
|
|
280
|
+
`,n?(r+=`Next step: Invoke the ${n} agent to ${o}
|
|
281
|
+
|
|
282
|
+
`,r+=`Use: Task(subagent_type="${n}", prompt="...")
|
|
283
|
+
`):r+=`Next step: ${o}
|
|
284
|
+
`,r}function xa(e,t){let n=Aa[t.current_stage],o=Ca(t.current_stage),r=`Resuming workflow for feature: ${e}
|
|
285
|
+
|
|
286
|
+
`;return r+=`You were interrupted during: ${t.current_stage}
|
|
287
|
+
`,r+=`Last update: ${t.updated_at}
|
|
288
|
+
|
|
289
|
+
`,t.resume_context?r+=`Resume context: ${JSON.stringify(t.resume_context,null,2)}
|
|
290
|
+
|
|
291
|
+
`:r+=`Resume context: No additional context available
|
|
292
|
+
|
|
293
|
+
`,n?(r+=`Continue from where you left off: Invoke the ${n} agent to ${o}
|
|
294
|
+
|
|
295
|
+
`,r+=`Use: Task(subagent_type="${n}", prompt="...")
|
|
296
|
+
`):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 Pa(){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 cn(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:Na(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:xa(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=br(t),o=Ar(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?(Xr(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 qe=require("fs"),Fe=require("path"),Da=require("os");function ap(e,t){let n=(0,Fe.join)((0,Da.homedir)(),".claude"),o=[];e&&(o.push((0,Fe.join)(n,"sessions",e,"todos.json")),o.push((0,Fe.join)(n,"todos",`${e}.json`))),t&&(o.push((0,Fe.join)(t,".olympus","todos.json")),o.push((0,Fe.join)(t,".claude","todos.json")));let r=(0,Fe.join)(n,"todos");if((0,qe.existsSync)(r))try{let i=(0,qe.readdirSync)(r);for(let s of i)s.endsWith(".json")&&o.push((0,Fe.join)(r,s))}catch{}return o}function cp(e){try{let t=(0,qe.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 lp(e){return e.status!=="completed"&&e.status!=="cancelled"}async function vt(e,t){let n=ap(e,t),o=new Set,r=[],i=[];for(let s of n){if(!(0,qe.existsSync)(s))continue;let c=cp(s);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),lp(a)&&i.push(a))}}return{count:i.length,todos:i,total:r.length}}function La(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var ln=require("path");function Ma(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}var $a=500;function Fa(e){let t=Qe((0,ln.join)(Ne(),"user-preferences.json"),null),n=Qe((0,ln.join)(gt(e),"patterns.json"),null),o=Qe((0,ln.join)(Ne(),"agent-performance.json"),{}),r=[];t&&up(t)&&r.push(fp(t)),n&&n.conventions.length>0&&r.push(dp(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(pp(t.recurring_corrections.slice(0,5)));let i=Object.values(o).filter(a=>a.weak_areas.length>0);i.length>0&&r.push(mp(i));let s=gp(o);if(s&&r.push(s),r.length===0)return"";let c=`<learned-context>
|
|
187
298
|
|
|
188
299
|
${r.join(`
|
|
189
300
|
|
|
@@ -193,21 +304,21 @@ ${r.join(`
|
|
|
193
304
|
|
|
194
305
|
---
|
|
195
306
|
|
|
196
|
-
`;return c.length
|
|
307
|
+
`;return c.length>$a*4?c.substring(0,$a*4)+`
|
|
197
308
|
...</learned-context>
|
|
198
309
|
|
|
199
310
|
---
|
|
200
311
|
|
|
201
|
-
`:c}function
|
|
202
|
-
`)}function
|
|
203
|
-
`)}function
|
|
204
|
-
`)}function
|
|
205
|
-
`)}function
|
|
206
|
-
`)}function
|
|
207
|
-
`)}var
|
|
208
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function
|
|
312
|
+
`:c}function up(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function fp(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(`
|
|
313
|
+
`)}function dp(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(`
|
|
314
|
+
`)}function pp(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
|
|
315
|
+
`)}function mp(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(`
|
|
316
|
+
`)}function gp(e){let t=Object.values(e).filter(c=>c.token_efficiency&&Ma(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)}`,d=c.success_rate>=.9&&c.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${c.agent_name}: ${a}%/${u}${d}`)}let o=We(),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(`
|
|
317
|
+
`)}function Ua(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(`
|
|
318
|
+
`)}var un=require("path"),Ye=require("fs"),hp=require("crypto");function kp(e){let t=(0,un.join)(Ne(),"discoveries.jsonl"),n=gt(e),o=(0,un.join)(n,"discoveries.jsonl"),r=ja(t),i=ja(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 Ha(e,t=10){let n=kp(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 ja(e){if(!(0,Ye.existsSync)(e))return[];try{return(0,Ye.readFileSync)(e,"utf-8").split(`
|
|
319
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function Wa(){v({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Fa(e.directory),n=Ha(e.directory,5),o=Ua(n),r=t+(o?`
|
|
209
320
|
|
|
210
|
-
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),
|
|
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=ee(n,t);s.token_budget||(yi(s,n),K(n,s))}catch(s){console.error("[Olympus Learning] Failed to initialize token budget:",s)}let r=He(n);r?.active&&o.push(`<session-restore>
|
|
211
322
|
|
|
212
323
|
[ULTRAWORK MODE RESTORED]
|
|
213
324
|
|
|
@@ -220,11 +331,11 @@ Continue working in ultrawork mode until all tasks are complete.
|
|
|
220
331
|
|
|
221
332
|
---
|
|
222
333
|
|
|
223
|
-
`);let
|
|
334
|
+
`);let i=await vt(t,n);return i.count>0&&o.push(`<session-restore>
|
|
224
335
|
|
|
225
336
|
[PENDING TASKS DETECTED]
|
|
226
337
|
|
|
227
|
-
You have ${
|
|
338
|
+
You have ${i.count} incomplete tasks from a previous session.
|
|
228
339
|
Please continue working on these tasks.
|
|
229
340
|
|
|
230
341
|
</session-restore>
|
|
@@ -232,7 +343,7 @@ Please continue working on these tasks.
|
|
|
232
343
|
---
|
|
233
344
|
|
|
234
345
|
`),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
|
|
235
|
-
`)}}:{continue:!0}}})}var
|
|
346
|
+
`)}}:{continue:!0}}})}var st=require("fs"),Re=require("path"),Io=require("os");var te=require("fs"),Ue=require("path"),Ga=require("os");function Eo(e){let t=(0,Ue.join)(e,".olympus");return(0,Ue.join)(t,"ascent-state.json")}function yp(e){let t=(0,Ue.join)(e,".olympus");(0,te.existsSync)(t)||(0,te.mkdirSync)(t,{recursive:!0})}function Rt(e){let t=Eo(e);if(!(0,te.existsSync)(t))return null;try{let n=(0,te.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Ep(e,t){try{yp(e);let n=Eo(e);return(0,te.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function fn(e){let t=Eo(e);if(!(0,te.existsSync)(t))return!0;try{return(0,te.unlinkSync)(t),!0}catch{return!1}}function Ba(e){let t=Rt(e);return!t||!t.active?null:(t.iteration+=1,Ep(e,t)?t:null)}function qa(e,t){let n=(0,Ue.join)((0,Ga.homedir)(),".claude"),o=[(0,Ue.join)(n,"sessions",e,"transcript.md"),(0,Ue.join)(n,"sessions",e,"messages.json"),(0,Ue.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,te.existsSync)(r))try{let i=(0,te.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${Sp(t)}\\s*</promise>`,"is").test(i))return!0}catch{continue}return!1}function Sp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ae=require("fs"),So=require("path"),Tp=3;function To(e){return(0,So.join)(e,".olympus","ascent-verification.json")}function bt(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 Ya(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 It(e){let t=To(e);if((0,ae.existsSync)(t))try{return(0,ae.unlinkSync)(t),!0}catch{return!1}return!0}function Va(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:Tp,requested_at:new Date().toISOString(),original_task:n};return Ya(e,o),o}function Ka(e,t,n){let o=bt(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(It(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(It(e),{...o,pending:!1}):(Ya(e,o),o)):null}function wo(e){return`<ascent-verification>
|
|
236
347
|
|
|
237
348
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
238
349
|
|
|
@@ -272,7 +383,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
272
383
|
|
|
273
384
|
---
|
|
274
385
|
|
|
275
|
-
`}function
|
|
386
|
+
`}function Ja(e){return`<ascent-continuation-after-rejection>
|
|
276
387
|
|
|
277
388
|
[ORACLE REJECTED - Continue Working]
|
|
278
389
|
|
|
@@ -297,7 +408,7 @@ Continue working now.
|
|
|
297
408
|
|
|
298
409
|
---
|
|
299
410
|
|
|
300
|
-
`}function
|
|
411
|
+
`}function Xa(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"),rt=require("path"),_o=require("os");function Oo(e){let t=e||process.cwd(),n=(0,rt.join)(t,".olympus");return(0,rt.join)(n,"olympus-state.json")}function vo(){return(0,rt.join)((0,_o.homedir)(),".claude","olympus-state.json")}function wp(e){let t=e||process.cwd(),n=(0,rt.join)(t,".olympus");(0,j.existsSync)(n)||(0,j.mkdirSync)(n,{recursive:!0})}function _p(){let e=(0,rt.join)((0,_o.homedir)(),".claude");(0,j.existsSync)(e)||(0,j.mkdirSync)(e,{recursive:!0})}function it(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 Qa(e,t){try{wp(t);let n=Oo(t);(0,j.writeFileSync)(n,JSON.stringify(e,null,2)),_p();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 Za(e){let t=it(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Qa(t,e)?t:null)}function ec(e){let t=it(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),Qa(t,e))}function tc(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
|
|
301
412
|
|
|
302
413
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
303
414
|
|
|
@@ -319,9 +430,9 @@ Original task: ${e.original_prompt}
|
|
|
319
430
|
|
|
320
431
|
---
|
|
321
432
|
|
|
322
|
-
`}function
|
|
433
|
+
`}function nc(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,st.existsSync)(o))try{let r=(0,st.readFileSync)(o,"utf-8");if(Xa(r))return!0}catch{continue}return!1}function Op(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,st.existsSync)(o))try{let r=(0,st.readFileSync)(o,"utf-8"),i=za(r);if(i.rejected)return i}catch{continue}return{rejected:!1,feedback:""}}async function vp(e,t){let n=t||process.cwd(),o=Rt(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=bt(n);if(r?.pending){if(e){if(nc(e))return It(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=Op(e);if(l.rejected){Ka(n,!1,l.feedback);let u=bt(n);if(u)return{shouldBlock:!0,message:Ja(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(qa(e||"",o.completion_promise)){Va(n,o.completion_promise,o.prompt);let a=bt(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),It(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=Ba(n);return s?{shouldBlock:!0,message:`<ascent-continuation>
|
|
323
434
|
|
|
324
|
-
[ASCENT LOOP - ITERATION ${
|
|
435
|
+
[ASCENT LOOP - ITERATION ${s.iteration}/${s.max_iterations}]
|
|
325
436
|
|
|
326
437
|
Your previous attempt did not output the completion promise. The work is NOT done yet.
|
|
327
438
|
|
|
@@ -329,16 +440,16 @@ CRITICAL INSTRUCTIONS:
|
|
|
329
440
|
1. Review your progress and the original task
|
|
330
441
|
2. Check your todo list - are ALL items marked complete?
|
|
331
442
|
3. Continue from where you left off
|
|
332
|
-
4. When FULLY complete, output: <promise>${
|
|
443
|
+
4. When FULLY complete, output: <promise>${s.completion_promise}</promise>
|
|
333
444
|
5. Do NOT stop until the task is truly done
|
|
334
445
|
|
|
335
|
-
${
|
|
446
|
+
${s.prompt?`Original task: ${s.prompt}`:""}
|
|
336
447
|
|
|
337
448
|
</ascent-continuation>
|
|
338
449
|
|
|
339
450
|
---
|
|
340
451
|
|
|
341
|
-
`,mode:"ascent",metadata:{iteration:
|
|
452
|
+
`,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function Rp(e,t,n){let o=He(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return zr(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 Ip(e,t,n){let o=it(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&&nc(e)?(ec(t),Ro(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
|
|
342
453
|
|
|
343
454
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
344
455
|
|
|
@@ -361,11 +472,11 @@ DO NOT stop until Oracle has approved.
|
|
|
361
472
|
|
|
362
473
|
---
|
|
363
474
|
|
|
364
|
-
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=
|
|
475
|
+
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=Za(t);return r?{shouldBlock:!0,message:tc(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function bp(e,t){let n=await vt(e,t);if(n.count===0)return null;let o=La(n),r=o?`
|
|
365
476
|
|
|
366
477
|
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
367
478
|
|
|
368
|
-
${
|
|
479
|
+
${ii}
|
|
369
480
|
|
|
370
481
|
[Status: ${n.count} of ${n.total} tasks remaining]${r}
|
|
371
482
|
|
|
@@ -373,20 +484,20 @@ ${Do}
|
|
|
373
484
|
|
|
374
485
|
---
|
|
375
486
|
|
|
376
|
-
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function
|
|
377
|
-
`),n={},o=0;for(;o<t.length;){let r=t[o],
|
|
487
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function oc(e,t){let n=t||process.cwd(),r=(await vt(e,n)).count>0,i=await vp(e,n);if(i?.shouldBlock)return i;let s=await Rp(e,n,r);if(s?.shouldBlock)return s;let c=await Ip(e,n,r);if(c?.shouldBlock)return c;if(r){let a=await bp(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function rc(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var at=require("fs"),bo=require("path"),ic=require("os");var sc=require("crypto");function Ap(){let e=(0,bo.join)((0,ic.homedir)(),".claude","todos");if(!(0,at.existsSync)(e))return 0;let t=0;try{let n=(0,at.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,at.readFileSync)((0,bo.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 ac(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=ee(t,n),r=Ap();if(r>0&&o.pending_completion){let i={id:(0,sc.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:t,event_type:"cancellation",original_task:o.pending_completion.task_description,agent_used:o.pending_completion.agent_used,user_message:`[Stopped with ${r} incomplete todos]`,feedback_category:"rejection",confidence:.7};xe(i)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},K(t,o)}function cc(){v({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await oc(t,n),r=rc(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 ac({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var Fo=require("fs"),Uo=require("os"),Ct=require("path");var ge=require("fs"),re=require("path");var Ao=require("path"),lc=require("os"),Cp=(0,Ao.join)((0,lc.homedir)(),".olympus"),dn=(0,Ao.join)(Cp,"rules-injector"),uc=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],fc=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],dc=[".github/copilot-instructions.md"],pc=/\.instructions\.md$/,mc=".claude/rules",gc=[".md",".mdc"],Co=["read","write","edit","multiedit"];function Np(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function xp(e,t){return Np(t)?pc.test(e):gc.some(n=>e.endsWith(n))}function Po(e){let t;try{t=(0,ge.statSync)(e).isDirectory()?e:(0,re.dirname)(e)}catch{t=(0,re.dirname)(e)}for(;;){for(let o of uc){let r=(0,re.join)(t,o);if((0,ge.existsSync)(r))return t}let n=(0,re.dirname)(t);if(n===t)return null;t=n}}function xo(e,t){if((0,ge.existsSync)(e))try{let n=(0,ge.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,re.join)(e,o.name);o.isDirectory()?xo(r,t):o.isFile()&&xp(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,re.dirname)(n),s=0;for(;;){for(let[u,f]of fc){let d=(0,re.join)(i,u,f),p=[];xo(d,p);for(let m of p){let y=No(m);r.has(y)||(r.add(y),o.push({path:m,realPath:y,isGlobal:!1,distance:s}))}}if(e&&i===e)break;let l=(0,re.dirname)(i);if(l===i)break;i=l,s++}if(e)for(let l of dc){let u=(0,re.join)(e,l);if((0,ge.existsSync)(u))try{if((0,ge.statSync)(u).isFile()){let d=No(u);r.has(d)||(r.add(d),o.push({path:u,realPath:d,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let c=(0,re.join)(t,mc),a=[];xo(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 hc=require("crypto"),kc=require("path");function Pp(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,kc.relative)(n,t):t).replace(/\\/g,"/");for(let c of r)if(Pp(c,s))return{applies:!0,reason:`glob: ${c}`};return{applies:!1}}function yc(e,t){return t.has(e)}function Ec(e){return(0,hc.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Sc(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:Dp(o),body:r}}catch{return{metadata:{},body:e}}}function Dp(e){let t=e.split(`
|
|
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=At(c);else if(s==="alwaysApply")n.alwaysApply=c==="true";else if(s==="globs"||s==="paths"||s==="applyTo"){let{value:a,consumed:l}=Lp(c,t,o);n.globs=$p(n.globs,a),o+=l;continue}o++}return n}function At(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function Lp(e,t,n){if(e.startsWith("["))return{value:Mp(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=At(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=At(e);return o.includes(",")?{value:o.split(",").map(i=>i.trim()).filter(i=>i.length>0),consumed:1}:{value:o,consumed:1}}function Mp(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(At(l)),o=""}else o+=a}let s=o.trim();return s&&n.push(At(s)),n}function $p(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"),Tc=require("path");function $o(e){return(0,Tc.join)(dn,`${e}.json`)}function wc(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 _c(e,t){(0,ce.existsSync)(dn)||(0,ce.mkdirSync)(dn,{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 Oc(e){let t=$o(e);(0,ce.existsSync)(t)&&(0,ce.unlinkSync)(t)}function vc(e){let t=new Map;function n(s){return t.has(s)||t.set(s,wc(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,Ct.resolve)(e,s):null}function r(s,c){let a=o(s);if(!a)return[];let l=Po(a),u=n(c),f=(0,Uo.homedir)(),d=Do(l,f,a),p=[];for(let m of d)if(!yc(m.realPath,u.realPaths))try{let y=(0,Fo.readFileSync)(m.path,"utf-8"),{metadata:h,body:k}=Mo(y),_;if(m.isSingleFile)_="copilot-instructions (always apply)";else{let L=Lo(h,a,l);if(!L.applies)continue;_=L.reason??"matched"}let g=Ec(k);if(Sc(g,u.contentHashes))continue;let N=l?(0,Ct.relative)(l,m.path):m.path;p.push({relativePath:N,matchReason:_,content:k,distance:m.distance}),u.realPaths.add(m.realPath),u.contentHashes.add(g)}catch{}return p.length>0&&(p.sort((m,y)=>m.distance-y.distance),_c(c,u)),p}function i(s){if(s.length===0)return"";let c="";for(let a of s)c+=`
|
|
378
489
|
|
|
379
490
|
[Rule: ${a.relativePath}]
|
|
380
491
|
[Match: ${a.matchReason}]
|
|
381
|
-
${a.content}`;return c}return{processToolExecution:(
|
|
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=Po(c),l=(0,Uo.homedir)(),u=Do(a,l,c),f=[];for(let d of u)try{let p=(0,Fo.readFileSync)(d.path,"utf-8"),{metadata:m,body:y}=Mo(p),h;if(d.isSingleFile)h="copilot-instructions (always apply)";else{let _=Lo(m,c,a);if(!_.applies)continue;h=_.reason??"matched"}let k=a?(0,Ct.relative)(a,d.path):d.path;f.push({relativePath:k,matchReason:h,content:y,distance:d.distance})}catch{}return f.sort((d,p)=>d.distance-p.distance)},clearSession:s=>{t.delete(s),Oc(s)},isTrackedTool:s=>Co.includes(s.toLowerCase())}}var mn=require("node:fs"),Ie=require("node:path");var le=require("node:fs"),bc=require("node:path");var jo=require("node:path"),Rc=require("node:os"),Fp=(0,jo.join)((0,Rc.homedir)(),".olympus"),pn=(0,jo.join)(Fp,"directory-readme"),Ic="README.md",Ho=["read","write","edit","multiedit"];function Wo(e){return(0,bc.join)(pn,`${e}.json`)}function Ac(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 Cc(e,t){(0,le.existsSync)(pn)||(0,le.mkdirSync)(pn,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,le.writeFileSync)(Wo(e),JSON.stringify(n,null,2))}function Nc(e){let t=Wo(e);(0,le.existsSync)(t)&&(0,le.unlinkSync)(t)}var xc=4,Up=5e3;function jp(e,t=Up){if(Math.ceil(e.length/xc)<=t)return{result:e,truncated:!1};let o=t*xc;return{result:e.slice(0,o),truncated:!0}}function Pc(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Ac(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,Ic);if((0,mn.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),f=r(l),d="";for(let p of f){let m=(0,Ie.dirname)(p);if(!u.has(m))try{let y=(0,mn.readFileSync)(p,"utf-8"),{result:h,truncated:k}=jp(y),_=k?`
|
|
382
493
|
|
|
383
|
-
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${
|
|
494
|
+
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${p}]`:"";d+=`
|
|
384
495
|
|
|
385
|
-
[Project README: ${
|
|
386
|
-
${
|
|
496
|
+
[Project README: ${p}]
|
|
497
|
+
${h}${_}`,u.add(m)}catch{}}return d&&Cc(c,u),d}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),Nc(s)},isTrackedTool:s=>Ho.includes(s.toLowerCase())}}var Dc="non-interactive-env",Lc={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
|
|
387
498
|
option1
|
|
388
499
|
option2
|
|
389
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
500
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Mc=Go.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function Hp(e){for(let t=0;t<Mc.length;t++)if(Mc[t].test(e))return Go.banned[t]}function Wp(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function Gp(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${Wp(o)}`).join(" ")};`}var Bo={name:Dc,async beforeCommand(e){let t=Hp(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${Gp(Lc)} ${e}`,warning:n}:{command:e,warning:n}}};var Yo=require("child_process");var $c="olympus-orchestrator",Fc=".olympus/",Uc=["Write","Edit","write","edit"],jc=`
|
|
390
501
|
|
|
391
502
|
---
|
|
392
503
|
|
|
@@ -412,7 +523,7 @@ You should NOT:
|
|
|
412
523
|
3. Verify the subagent's work after completion
|
|
413
524
|
|
|
414
525
|
---
|
|
415
|
-
`;var
|
|
526
|
+
`;var Hc=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
416
527
|
|
|
417
528
|
You have an active work plan with incomplete tasks. Continue working.
|
|
418
529
|
|
|
@@ -421,7 +532,7 @@ RULES:
|
|
|
421
532
|
- Mark each checkbox [x] in the plan file when done
|
|
422
533
|
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
423
534
|
- Do not stop until all tasks are complete
|
|
424
|
-
- If blocked, document the blocker and move to the next task`,
|
|
535
|
+
- If blocked, document the blocker and move to the next task`,Wc=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
425
536
|
|
|
426
537
|
Subagents FREQUENTLY claim completion when:
|
|
427
538
|
- Tests are actually FAILING
|
|
@@ -436,7 +547,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
436
547
|
3. Check build/typecheck - Must succeed
|
|
437
548
|
|
|
438
549
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
439
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
550
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Gc=`
|
|
440
551
|
|
|
441
552
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
442
553
|
|
|
@@ -459,7 +570,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
459
570
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
460
571
|
|
|
461
572
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
462
|
-
`,
|
|
573
|
+
`,Bc=`
|
|
463
574
|
|
|
464
575
|
================================================================================
|
|
465
576
|
HARD BLOCK: DELEGATION REQUIRED
|
|
@@ -498,41 +609,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
|
|
|
498
609
|
Delegate to a subagent to proceed.
|
|
499
610
|
|
|
500
611
|
================================================================================
|
|
501
|
-
`;var
|
|
502
|
-
`;(0,
|
|
503
|
-
`).length,
|
|
504
|
-
`).length;return Math.abs(
|
|
505
|
-
`).length:0}return 0}function
|
|
506
|
-
`)){if(!
|
|
507
|
-
`)){let i
|
|
612
|
+
`;var Nt=".olympus",gn="quest.json",Bp=`${Nt}/${gn}`,qc="notepads",qp=`${Nt}/${qc}`;var he=require("fs"),hn=require("path");function Yc(e){return(0,hn.join)(e,Nt,gn)}function kn(e){let t=Yc(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 yn(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 xt=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}},Zy=new xt;var Ve=require("fs"),qo=require("path");function Pt(e,t){let n=t||process.cwd(),o=(0,qo.join)(n,".olympus","logs"),r=(0,qo.join)(o,"hook-violations.jsonl");try{(0,Ve.existsSync)(o)||(0,Ve.mkdirSync)(o,{recursive:!0});let i=JSON.stringify(e)+`
|
|
613
|
+
`;(0,Ve.appendFileSync)(r,i,"utf-8")}catch(i){console.error("[Hook Logging] Failed to log violation:",i)}}var Vc=new xt;function Kc(e){return e?e.replace(/\\/g,"/").includes(Fc):!0}function Kp(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 Jp(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
|
+
`).length,i=o.split(`
|
|
615
|
+
`).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 Jc(e){return Uc.includes(e)}function Xp(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
|
+
`)){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),f=a==="-"?0:parseInt(a,10);r.push({path:l,added:u,removed:f,status:o.get(l)??"modified"})}return r}catch{return[]}}function zp(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
508
619
|
No file changes detected.
|
|
509
|
-
`;let t=e.filter(
|
|
510
|
-
`)}function
|
|
620
|
+
`;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 Xc(e){let t=Wc;return e&&(t+=`
|
|
511
622
|
|
|
512
623
|
---
|
|
513
624
|
|
|
514
625
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
515
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
626
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function Qp(e,t,n){let o=t.total-t.completed;return`
|
|
516
627
|
---
|
|
517
628
|
|
|
518
629
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
519
630
|
|
|
520
631
|
---
|
|
521
632
|
|
|
522
|
-
${
|
|
633
|
+
${Xc(n)}
|
|
523
634
|
|
|
524
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
635
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function Zp(e,t,n){return Hc.replace(/{PLAN_NAME}/g,e)+`
|
|
525
636
|
|
|
526
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
637
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function em(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!Jc(t))return{continue:!0};let i=n?.filePath??n?.path??n?.file;if(!i)return{continue:!0};let s=i.replace(/\\/g,"/");if(Kc(s))return Pt({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(Kp(s))return Pt({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let c=Jp(t,n);return Vc.isVerificationEdit(s,c)?(Pt({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}):(Pt({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:c,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:Bc})}function tm(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:i}=e,s=r||process.cwd();if(Jc(n)){let c=o?.filePath??o?.path??o?.file;if(c&&!Kc(c))return{continue:!0,modifiedOutput:t+jc}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let a=Xp(s),l=a.map(d=>d.path);Vc.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:i||`task-${Date.now()}`});let u=zp(a),f=kn(s);if(f){let d=yn(f.active_plan);return{continue:!0,modifiedOutput:`
|
|
527
638
|
## SUBAGENT WORK COMPLETED
|
|
528
639
|
|
|
529
640
|
${u}
|
|
530
641
|
<system-reminder>
|
|
531
|
-
${
|
|
642
|
+
${Qp(f.plan_name,d,i)}
|
|
532
643
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
533
644
|
<system-reminder>
|
|
534
|
-
${
|
|
535
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
645
|
+
${Xc(i)}
|
|
646
|
+
</system-reminder>`}}return{continue:!0}}function nm(e){let t=kn(e);if(!t)return{shouldContinue:!1};let n=yn(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:Zp(t.plan_name,o,n.total)}}function En(e){return{name:$c,preTool:(t,n)=>em({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>tm({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>nm(e),getSingleTaskDirective:()=>Gc}}function zc(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function Qc(){v({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=vc(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=Pc(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=>En(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var om=["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"],rm=`
|
|
536
647
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
537
648
|
|
|
538
649
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -543,7 +654,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
543
654
|
4. CONTINUE with corrected action based on the real file content
|
|
544
655
|
|
|
545
656
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
546
|
-
`;function
|
|
657
|
+
`;function im(e){let t=e.toLowerCase();return om.some(n=>t.includes(n.toLowerCase()))}function Zc(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:im(t.output)?{...t,output:t.output+rm}:t}}var nl=ie(require("fs"),1),Tn=ie(require("path"),1),ol=require("os");var Sn=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
|
|
547
658
|
|
|
548
659
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
549
660
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -581,13 +692,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
581
692
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
582
693
|
|
|
583
694
|
Detected comments/docstrings:
|
|
584
|
-
`,
|
|
585
|
-
`;
|
|
586
|
-
`);o.lastIndex=0;let
|
|
587
|
-
`).length,
|
|
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},Xo={".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 sm(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function am(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Sn){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>Sn.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function cm(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 lm(e){return{shouldSkip:!1}}function um(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 fm(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 dm=[sm,am,cm,um,fm,lm];function zo(e){return e.filter(t=>{for(let n of dm)if(n(t).shouldSkip)return!1;return!0})}var pm=process.env.COMMENT_CHECKER_DEBUG==="1",mm=Tn.join((0,ol.tmpdir)(),"comment-checker-debug.log");function Ke(...e){if(pm){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
696
|
+
`;nl.appendFileSync(mm,t)}}function gm(e){let t=Tn.extname(e).toLowerCase();return Xo[t]}function Qo(e,t){let n=gm(t);if(!n)return Ke("unsupported language for:",t),[];let o=Jo[n];if(!o)return Ke("no pattern for language:",n),[];let r=[],i=e.split(`
|
|
697
|
+
`);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,f="line",d=!1;a.startsWith("/*")||a.startsWith("<!--")?f="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(f="docstring",d=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:f,isDocstring:d})}return r}function hm(e,t){return Qo(e,t)}function el(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 km(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+=`
|
|
588
699
|
File: ${o}
|
|
589
|
-
`;for(let
|
|
590
|
-
`}}return n}function
|
|
700
|
+
`;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 ym(e,t,n,o,r){let i=[];if(t)i=hm(t,e);else if(o)i=el(o,e,n);else if(r&&r.length>0)for(let c of r){let a=el(c.new_string,e,c.old_string);i.push(...a)}let s=zo(i);return Ke(`found ${i.length} comments, ${s.length} flagged after filtering`),s.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:s.length,message:km(s),comments:s}}var Dt=new Map,Em=6e4;function Sm(){let e=Date.now();for(let[t,n]of Dt)e-n.timestamp>Em&&Dt.delete(t)}var tl=!1;function rl(e){return Ke("createCommentCheckerHook called",{config:e}),tl||(tl=!0,setInterval(Sm,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 Ke("registering pendingCall:",{callId:a,filePath:o,tool:n}),Dt.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 Dt)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&&Dt.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 Ke("skipping due to tool failure in response"),null}let i=ym(o.filePath,o.content,o.oldString,o.newString,o.edits);return i.hasComments&&i.message?(Ke("detected comments, returning message"),e?.customPrompt||i.message):null}}}var fl=ie(require("fs"),1),dl=ie(require("path"),1),pl=require("os");var sl=[/(\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],al=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],Tm=[/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],wm=/messages\.(\d+)/;function _m(e){return Tm.some(t=>t.test(e))}function Zo(e){for(let t of sl){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 il(e){let t=e.match(wm);if(t)return parseInt(t[1],10)}function ct(e){if(_m(e))return!1;let t=e.toLowerCase();return al.some(n=>t.includes(n.toLowerCase()))}function wn(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:il(e)};if(ct(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);ct(l)&&n.push(l)}catch{}let a=n.join(" ");if(!ct(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 f of l){let d=r.match(f);if(d)try{let p=JSON.parse(d[1]),m=p.error?.message||"",y=Zo(m);if(y)return{currentTokens:y.current,maxTokens:y.max,requestId:p.request_id,errorType:p.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&ct(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:il(a)}:ct(a)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function er(e){return ct(e)}var tr=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
591
702
|
|
|
592
703
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
593
704
|
|
|
@@ -612,7 +723,7 @@ Current Status:
|
|
|
612
723
|
- Context limit exceeded
|
|
613
724
|
- Further API calls will fail until context is reduced
|
|
614
725
|
- Action required before continuing
|
|
615
|
-
`,
|
|
726
|
+
`,nr="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",or=`API ERROR: Non-empty content validation failed.
|
|
616
727
|
|
|
617
728
|
This error typically occurs when:
|
|
618
729
|
- A message has empty text content
|
|
@@ -623,7 +734,7 @@ Suggested actions:
|
|
|
623
734
|
2. If the error persists, start a new session
|
|
624
735
|
|
|
625
736
|
The system will attempt automatic recovery.
|
|
626
|
-
`;var
|
|
737
|
+
`;var rr=`CONTEXT RECOVERY FAILED
|
|
627
738
|
|
|
628
739
|
All automatic recovery attempts have been exhausted.
|
|
629
740
|
Please start a new session to continue.
|
|
@@ -634,13 +745,13 @@ Before starting a new session:
|
|
|
634
745
|
3. Document the current state of the task
|
|
635
746
|
|
|
636
747
|
You can copy this conversation summary to continue in a new session.
|
|
637
|
-
`;var
|
|
638
|
-
`;
|
|
748
|
+
`;var ir={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var Om=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",vm=dl.join((0,pl.tmpdir)(),"context-limit-recovery-debug.log");function _n(...e){if(Om){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
749
|
+
`;fl.appendFileSync(vm,t)}}var On=new Map,ml=3e5;function cl(e){let t=On.get(e),n=Date.now();return t&&n-t.lastErrorTime>ml&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},On.set(e,t)),t}function Rm(){let e=Date.now();for(let[t,n]of On)e-n.lastErrorTime>ml&&On.delete(t)}var ll=!1;function gl(e){return _n("createContextLimitRecoveryHook called",{config:e}),ll||(ll=!0,setInterval(Rm,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=wn(t.tool_response);if(!n&&!er(t.tool_response))return null;_n("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=cl(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=ul(n,o,e);return r.message?(_n("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=wn(t.error);if(!n)return{attempted:!1,success:!1};_n("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=cl(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=ul(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function ul(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+=`
|
|
639
750
|
Token Details:
|
|
640
751
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
641
752
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
642
753
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
643
|
-
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:
|
|
754
|
+
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:nr,errorType:e?.errorType||"token_limit_exceeded"}}var hl=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,Im=/exceeds maximum allowed tokens/i;function bm(e){let t=e.match(hl);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Am(e,t){return e.toLowerCase()==="read"&&(hl.test(t)||Im.test(t))}function Cm(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
|
|
644
755
|
|
|
645
756
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
646
757
|
|
|
@@ -670,7 +781,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
670
781
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
671
782
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
672
783
|
|
|
673
|
-
Proceed with one of these strategies.`.trim()}function
|
|
784
|
+
Proceed with one of these strategies.`.trim()}function kl(){return{postToolUse:e=>{if(!e.tool_response||!Am(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=bm(e.tool_response);return Cm(t,n||void 0)}}}var _l=ie(require("fs"),1),Ol=ie(require("path"),1),vl=require("os");var sr=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,vn=4,ar=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
674
785
|
|
|
675
786
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
676
787
|
|
|
@@ -690,7 +801,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
|
|
|
690
801
|
|
|
691
802
|
Current Status: Context usage is high but recoverable.
|
|
692
803
|
Action recommended: Use /compact when convenient.
|
|
693
|
-
`,
|
|
804
|
+
`,cr=`CRITICAL: CONTEXT WINDOW ALMOST FULL
|
|
694
805
|
|
|
695
806
|
Your context usage is critically high. Immediate action required:
|
|
696
807
|
|
|
@@ -709,8 +820,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
709
820
|
|
|
710
821
|
WARNING: Further messages may fail if context is not reduced.
|
|
711
822
|
Action required: Run /compact now.
|
|
712
|
-
`;var
|
|
713
|
-
`;
|
|
823
|
+
`;var Nm=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",xm=Ol.join((0,vl.tmpdir)(),"preemptive-compaction-debug.log");function lt(...e){if(Nm){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
824
|
+
`;_l.appendFileSync(xm,t)}}var Rn=new Map;function Pm(){let e=Date.now(),t=1800*1e3;for(let[n,o]of Rn)e-o.lastWarningTime>t&&Rn.delete(n)}var yl=!1;function Rl(e){return Math.ceil(e.length/vn)}function Dm(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=sr,i=Rl(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 In(e){let t=Rn.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},Rn.set(e,t)),t}function Lm(e,t){let n=In(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,i=Date.now();return i-n.lastWarningTime<o?(lt("skipping warning - cooldown active",{sessionId:e,elapsed:i-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(lt("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Mm(e){let t=In(e);t.lastWarningTime=Date.now(),t.warningCount++}function Il(e){return lt("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(yl||(yl=!0,setInterval(Pm,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=Rl(t.tool_response),i=In(t.session_id);i.estimatedTokens+=r,lt("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:i.estimatedTokens});let s=Dm("x".repeat(i.estimatedTokens*vn),e);return!s.isWarning||!Lm(t.session_id,e)?null:(Mm(t.session_id),lt("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=In(t.session_id);return n.warningCount>0&&(lt("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var ue=require("fs"),Al=require("path");var lr=require("path"),bl=require("os"),$m=(0,lr.join)((0,bl.homedir)(),".olympus"),bn=(0,lr.join)($m,"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"]),fr=new Set(["task","call_omo_agent","olympus_task"]),dr=`
|
|
714
825
|
[Agent Usage Reminder]
|
|
715
826
|
|
|
716
827
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -734,7 +845,7 @@ WHY:
|
|
|
734
845
|
- Reduces context window usage in main session
|
|
735
846
|
|
|
736
847
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
737
|
-
`;function
|
|
848
|
+
`;function pr(e){return(0,Al.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 An(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 Fm(e){let t=e||process.cwd();return Rt(t)?.active?{active:!0,mode:"ascent"}:it(t)?.active?{active:!0,mode:"olympus"}:He(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function Um(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function jm(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
|
|
738
849
|
|
|
739
850
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
740
851
|
|
|
@@ -760,27 +871,27 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
760
871
|
|
|
761
872
|
---
|
|
762
873
|
|
|
763
|
-
`}function
|
|
764
|
-
`;(0,fi.appendFileSync)(si,t)}}function mi(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 gi(e){let n=mi(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function hi(e){let t=mi(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 ll(e){return hi(e)!==null}function ul(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function dl(e,t){x("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=J(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let o=ul(n);return o.length===0?(x("No tool_use IDs found"),!1):(x("Found tool_use IDs to inject results for",o),!0)}async function pl(e,t,n){x("recoverThinkingBlockOrder",{sessionID:e});let o=gi(n);if(o!==null){let i=pi(e,o);if(i)return x("Found target message by index",{targetIndex:o,targetMessageID:i}),Kn(e,i)}let r=Vn(e);if(r.length===0)return x("No orphan thinking messages found"),!1;x("Found orphan thinking messages",r);let s=!1;for(let i of r)Kn(e,i)&&(s=!0);return s}async function fl(e,t){x("recoverThinkingDisabledViolation",{sessionID:e});let n=Wn(e);if(n.length===0)return x("No messages with thinking blocks found"),!1;x("Found messages with thinking blocks",n);let o=!1;for(let r of n)ui(r)&&(o=!0);return o}async function ml(e,t,n){x("recoverEmptyContentMessage",{sessionID:e});let o=gi(n),r=t.info?.id,s=!1,i=di(e);for(let l of i)Ye(l,B)&&(s=!0);let c=li(e);for(let l of c)Be(e,l,B)&&(s=!0);if(o!==null){let l=ci(e,o);if(l&&(Ye(l,B)||Be(e,l,B)))return!0}if(r&&(Ye(r,B)||Be(e,r,B)))return!0;let a=Yn(e);for(let l of a)Ye(l,B)&&(s=!0),Be(e,l,B)&&(s=!0);return s}async function gl(e,t,n,o){x("handleSessionRecovery",{sessionID:e,error:t});let r=hi(t);if(!r)return x("Not a recoverable error"),{attempted:!1,success:!1};x("Detected recoverable error type",r);try{let s=!1,i=n||{info:{},parts:[]};switch(r){case"tool_result_missing":s=await dl(e,i);break;case"thinking_block_order":s=await pl(e,i,t);break;case"thinking_disabled_violation":s=await fl(e,i);break;case"empty_content":s=await ml(e,i,t);break}x("Recovery result",{errorType:r,success:s});let c=o?.customMessages?.[r]||_t[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?c:void 0,errorType:r}}catch(s){return x("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function Ti(e){return x("createSessionRecoveryHook",{config:e}),{onError:async t=>gl(t.session_id,t.error,t.message,e),isRecoverable:t=>ll(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||_t[t]?.message}}}function ki(){let e=Ti();g({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 Y=require("fs"),Rt=require("path"),Ei=require("os");var We=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 s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s: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 s=this.queues.get(t)??[];s.push(r),this.queues.set(t,s)})}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 hl=1800*1e3,be=(0,Rt.join)((0,Ei.homedir)(),".claude",".olympus","background-tasks"),It=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new We(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,Y.existsSync)(be)||(0,Y.mkdirSync)(be,{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,Rt.join)(be,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,Y.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,Y.existsSync)(n)&&(0,Y.unlinkSync)(n)}loadPersistedTasks(){if((0,Y.existsSync)(be))try{let{readdirSync:t}=require("fs"),n=t(be);for(let o of n)if(o.endsWith(".json"))try{let r=(0,Rt.join)(be,o),s=(0,Y.readFileSync)(r,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}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??hl;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 s=r.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(o):s.length!==r.length&&this.notifications.set(o,s)}}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 s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,c={id:s,sessionId:i,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(s,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 s=this.tasks.get(t);s&&(s.status=n,o&&(s.result=o),r&&(s.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}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(s=>s.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),s=Math.floor(r/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${r%60}s`:s>0?`${s}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 s=this.formatDuration(r.startedAt,r.completedAt),i=r.status.toUpperCase(),c=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${c}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
765
|
-
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},
|
|
766
|
-
`)}function
|
|
874
|
+
`}function Cl(){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(),An(l)}function r(a){e.delete(a),gr(a),t.delete(a)}function i(a,l,u){let f=t.get(a)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:a};return l.toLowerCase()==="task"?(f.consecutiveCount=0,t.set(a,f),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(f.consecutiveCount++,f.lastToolName=l,f.lastFilePath=u,t.set(a,f)),f.consecutiveCount)}return{"tool.execute.after":async(a,l)=>{let{tool:u,sessionID:f}=a,d=u.toLowerCase();if(fr.has(d)){o(f),i(f,d,"");return}let p=a.properties||{},m=Um(p),y=i(f,d,m||""),h=Fm();if(h.active){let _=jm(y,h.mode);if(_){l.output=_+l.output;return}}if(!ur.has(d))return;let k=n(f);k.agentUsed||(l.output+=dr,k.reminderCount++,k.updatedAt=Date.now(),An(k))},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 Nl(){let e=process.cwd(),t=Zc();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=rl();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=gl();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=kl();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=Il();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=Cl();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=En(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 Gl=require("node:fs");var C=require("node:fs"),ne=require("node:path");var ut=require("node:path"),Cn=require("node:os");function Hm(){return process.env.XDG_DATA_HOME??(0,ut.join)((0,Cn.homedir)(),".local","share")}function Wm(){return(0,ut.join)(Hm(),"claude-code","storage")}var xl=Wm(),Lt=(0,ut.join)(xl,"message"),ft=(0,ut.join)(xl,"part"),je=new Set(["thinking","redacted_thinking","reasoning"]),Pl=new Set(["step-start","step-finish"]);var fe="[user interrupted]",Nn={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 Dl=process.env.SESSION_RECOVERY_DEBUG==="1",Ll=(0,ut.join)((0,Cn.tmpdir)(),"session-recovery-debug.log");function Gm(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function Bm(e){if(!(0,C.existsSync)(Lt))return"";let t=(0,ne.join)(Lt,e);if((0,C.existsSync)(t))return t;for(let n of(0,C.readdirSync)(Lt)){let o=(0,ne.join)(Lt,n,e);if((0,C.existsSync)(o))return o}return""}function be(e){let t=Bm(e);if(!t||!(0,C.existsSync)(t))return[];let n=[];for(let o of(0,C.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,C.readFileSync)((0,ne.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,ne.join)(ft,e);if(!(0,C.existsSync)(t))return[];let n=[];for(let o of(0,C.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,C.readFileSync)((0,ne.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Ml(e){return je.has(e.type)||Pl.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function $l(e){return Te(e).some(Ml)}function Mt(e,t,n){let o=(0,ne.join)(ft,t);(0,C.existsSync)(o)||(0,C.mkdirSync)(o,{recursive:!0});let r=Gm(),i={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,C.writeFileSync)((0,ne.join)(o,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function hr(e){let t=be(e),n=[];for(let o of t)$l(o.id)||n.push(o.id);return n}function Fl(e,t){let n=be(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(!$l(i.id))return i.id}return null}function kr(e){let t=be(e),n=[];for(let o of t){if(o.role!=="assistant")continue;Te(o.id).some(s=>je.has(s.type))&&n.push(o.id)}return n}function Ul(e){let t=be(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=>je.has(c.type)),s=r.some(Ml);i&&!s&&n.push(o.id)}return n}function yr(e){let t=be(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];je.has(s.type)||n.push(o.id)}return n}function qm(e,t){let n=be(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(je.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,ne.join)(ft,t);(0,C.existsSync)(n)||(0,C.mkdirSync)(n,{recursive:!0});let o=qm(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,C.writeFileSync)((0,ne.join)(n,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function jl(e){let t=(0,ne.join)(ft,e);if(!(0,C.existsSync)(t))return!1;let n=!1;for(let o of(0,C.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,ne.join)(t,o),i=(0,C.readFileSync)(r,"utf-8"),s=JSON.parse(i);je.has(s.type)&&((0,C.unlinkSync)(r),n=!0)}catch{continue}return n}function $t(e,t=fe){let n=(0,ne.join)(ft,e);if(!(0,C.existsSync)(n))return!1;let o=!1;for(let r of(0,C.readdirSync)(n))if(r.endsWith(".json"))try{let i=(0,ne.join)(n,r),s=(0,C.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,C.writeFileSync)(i,JSON.stringify(a,null,2)),o=!0)}}catch{continue}return o}function Hl(e){let t=be(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 Wl(e,t){let n=be(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 je.has(s.type)?null:o.id}function Y(...e){if(Dl){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
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 Pn(e)),Sr}function eg(e){let t=e.status.toUpperCase(),n=tg(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(`
|
|
877
|
+
`)}function tg(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 ng(e){if(e.length===0)return"";let t=e.length===1?`
|
|
767
878
|
[BACKGROUND TASK COMPLETED]
|
|
768
879
|
`:`
|
|
769
880
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
770
|
-
`,n=e.map(o=>
|
|
881
|
+
`,n=e.map(o=>eg(o)).join(`
|
|
771
882
|
|
|
772
883
|
`);return`${t}
|
|
773
884
|
${n}
|
|
774
|
-
`}function
|
|
885
|
+
`}function og(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let i=(n?.formatNotification??ng)(o);return{hasNotifications:!0,tasks:o,message:i}}function Xl(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Tr(),r=og(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 Xl(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var _r=null,wr=!1;async function rg(){if(!wr)try{let{encode:e}=await import("gpt-tokenizer");_r=e,wr=!0}catch{wr=!0}}function ig(e){return Math.ceil(e.length/4)}async function Je(e){if(!e||e.length===0)return 0;await rg();try{if(_r)return _r(e).length}catch{}return ig(e)}async function Ql(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return Je(n.content);if("output"in n&&typeof n.output=="string")return Je(n.output);if("text"in n&&typeof n.text=="string")return Je(n.text);if("result"in n&&typeof n.result=="string")return Je(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return Je(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 Zl(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 tu=require("crypto");function sg(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 ag(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function eu(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 nu(){v({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=sg(e);if(!t)return{continue:!0};let n=await Je(t),o=ee(e.directory,e.sessionId);eu(o);let r=ag(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,K(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 Ql(e.toolOutput):0,n=ee(e.directory,e.sessionId);eu(n),n.token_budget&&(n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,K(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=ee(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=Zl(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,tu.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(xe(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,K(e.directory,t)}catch(t){console.error("[Olympus Learning Capture] Error in stop handler:",t)}return{continue:!0}}})}function ou(){v({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=ee(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),K(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${s}x baseline of ${i}k).
|
|
775
886
|
This is informational - continue if task requires it.
|
|
776
|
-
Consider: delegate to subagent, break into smaller tasks.`}}return
|
|
777
|
-
`;break;case 114:
|
|
778
|
-
`),c++,l=o,
|
|
779
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
780
|
-
`+" ".repeat(t))}," ":{"\n":new Array(
|
|
781
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
782
|
-
`+" ".repeat(t))}};var bt;(function(e){e.DEFAULT={allowTrailingComma:!1}})(bt||(bt={}));function Ci(e,t=[],n=bt.DEFAULT){let o=null,r=[],s=[];function i(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return xi(e,{onObjectBegin:()=>{let a={};i(a),s.push(r),r=a,o=null},onObjectProperty:a=>{o=a},onObjectEnd:()=>{r=s.pop()},onArrayBegin:()=>{let a=[];i(a),s.push(r),r=a,o=null},onArrayEnd:()=>{r=s.pop()},onLiteralValue:i,onError:(a,l,u)=>{t.push({error:a,offset:l,length:u})}},n),r[0]}function xi(e,t,n=bt.DEFAULT){let o=At(e,!1),r=[],s=0;function i(T){return T?()=>s===0&&T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(T){return T?b=>s===0&&T(b,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(T){return T?b=>s===0&&T(b,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(T){return T?()=>{s>0?s++:T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(s=1)}:()=>!0}function u(T){return T?()=>{s>0&&s--,s===0&&T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=a(t.onObjectProperty),E=u(t.onObjectEnd),S=l(t.onArrayBegin),O=u(t.onArrayEnd),R=a(t.onLiteralValue),h=c(t.onSeparator),_=i(t.onComment),p=c(t.onError),I=n&&n.disallowComments,N=n&&n.allowTrailingComma;function y(){for(;;){let T=o.scan();switch(o.getTokenError()){case 4:m(14);break;case 5:m(15);break;case 3:m(13);break;case 1:I||m(11);break;case 2:m(12);break;case 6:m(16);break}switch(T){case 12:case 13:I?m(10):_();break;case 16:m(1);break;case 15:case 14:break;default:return T}}}function m(T,b=[],eo=[]){if(p(T),b.length+eo.length>0){let qe=o.getToken();for(;qe!==17;){if(b.indexOf(qe)!==-1){y();break}else if(eo.indexOf(qe)!==-1)break;qe=y()}}}function ge(T){let b=o.getTokenValue();return T?R(b):(f(b),r.push(b)),y(),!0}function Ne(){switch(o.getToken()){case 11:let T=o.getTokenValue(),b=Number(T);isNaN(b)&&(m(2),b=0),R(b);break;case 7:R(null);break;case 8:R(!0);break;case 9:R(!1);break;default:return!1}return y(),!0}function Gi(){return o.getToken()!==10?(m(3,[],[2,5]),!1):(ge(!1),o.getToken()===6?(h(":"),y(),Ct()||m(4,[],[2,5])):m(5,[],[2,5]),r.pop(),!0)}function Bi(){d(),y();let T=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(T||m(4,[],[]),h(","),y(),o.getToken()===2&&N)break}else T&&m(6,[],[]);Gi()||m(4,[],[2,5]),T=!0}return E(),o.getToken()!==2?m(7,[2],[]):y(),!0}function Yi(){S(),y();let T=!0,b=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(b||m(4,[],[]),h(","),y(),o.getToken()===4&&N)break}else b&&m(6,[],[]);T?(r.push(0),T=!1):r[r.length-1]++,Ct()||m(4,[],[4,5]),b=!0}return O(),T||r.pop(),o.getToken()!==4?m(8,[4],[]):y(),!0}function Ct(){switch(o.getToken()){case 3:return Yi();case 1:return Bi();case 10:return ge(!0);default:return Ne()}}return y(),o.getToken()===17?n.allowEmptyContent?!0:(m(4,[],[]),!1):Ct()?(o.getToken()!==17&&m(9,[],[]),!0):(m(4,[],[]),!1)}var Pi;(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"})(Pi||(Pi={}));var Li;(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"})(Li||(Li={}));var Mi=Ci;var Di;(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"})(Di||(Di={}));var Ll={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:Qn,customPricing:[]}};function Dl(){let e=process.env.XDG_CONFIG_HOME??(0,Ke.join)((0,ji.homedir)(),".config");return{user:(0,Ke.join)(e,"claude-olympus","config.jsonc"),project:(0,Ke.join)(process.cwd(),".claude","olympus.jsonc")}}function Ui(e){if(!(0,vt.existsSync)(e))return null;try{let t=(0,vt.readFileSync)(e,"utf-8"),n=[],o=Mi(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 wt(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],s=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[o]=wt(s,r):r!==void 0&&(n[o]=r)}return n}function Ml(){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 Fi(){let e=Dl(),t={...Ll},n=Ui(e.user);n&&(t=wt(t,n));let o=Ui(e.project);o&&(t=wt(t,o));let r=Ml();return t=wt(t,r),t}function Ul(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function jl(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 Fl(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function $l(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function $i(e,t){let n=Fi(),o=no(e),r=Ul(n),s=!0,i=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(jl(n,u.name)&&$l(u.matcher,t.toolName))try{let d=await Fl(()=>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||(s=!1,c=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.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:s,message:i.length>0?i.join(`
|
|
887
|
+
Consider: delegate to subagent, break into smaller tasks.`}}return K(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}var ru=!1;function iu(){ru||(Pa(),Wa(),cc(),Qc(),Nl(),Kl(),zl(),nu(),ou(),ru=!0)}var $n=require("fs"),mu=require("os"),jt=require("path");function Dn(e,t=!1){let n=e.length,o=0,r="",i=0,s=16,c=0,a=0,l=0,u=0,f=0;function d(g,N){let L=0,I=0;for(;L<g||!N;){let T=e.charCodeAt(o);if(T>=48&&T<=57)I=I*16+T-48;else if(T>=65&&T<=70)I=I*16+T-65+10;else if(T>=97&&T<=102)I=I*16+T-97+10;else break;o++,L++}return L<g&&(I=-1),I}function p(g){o=g,r="",i=0,s=16,f=0}function m(){let g=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&pt(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&pt(e.charCodeAt(o)))for(o++;o<e.length&&pt(e.charCodeAt(o));)o++;else return f=3,e.substring(g,o);let N=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&&pt(e.charCodeAt(o))){for(o++;o<e.length&&pt(e.charCodeAt(o));)o++;N=o}else f=3;return e.substring(g,N)}function y(){let g="",N=o;for(;;){if(o>=n){g+=e.substring(N,o),f=2;break}let L=e.charCodeAt(o);if(L===34){g+=e.substring(N,o),o++;break}if(L===92){if(g+=e.substring(N,o),o++,o>=n){f=2;break}switch(e.charCodeAt(o++)){case 34:g+='"';break;case 92:g+="\\";break;case 47:g+="/";break;case 98:g+="\b";break;case 102:g+="\f";break;case 110:g+=`
|
|
888
|
+
`;break;case 114:g+="\r";break;case 116:g+=" ";break;case 117:let T=d(4,!0);T>=0?g+=String.fromCharCode(T):f=4;break;default:f=5}N=o;continue}if(L>=0&&L<=31)if(Ut(L)){g+=e.substring(N,o),f=2;break}else f=6;o++}return g}function h(){if(r="",f=0,i=o,a=c,u=l,o>=n)return i=n,s=17;let g=e.charCodeAt(o);if(vr(g)){do o++,r+=String.fromCharCode(g),g=e.charCodeAt(o);while(vr(g));return s=15}if(Ut(g))return o++,r+=String.fromCharCode(g),g===13&&e.charCodeAt(o)===10&&(o++,r+=`
|
|
889
|
+
`),c++,l=o,s=14;switch(g){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=y(),s=10;case 47:let N=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Ut(e.charCodeAt(o));)o++;return r=e.substring(N,o),s=12}if(e.charCodeAt(o+1)===42){o+=2;let L=n-1,I=!1;for(;o<L;){let T=e.charCodeAt(o);if(T===42&&e.charCodeAt(o+1)===47){o+=2,I=!0;break}o++,Ut(T)&&(T===13&&e.charCodeAt(o)===10&&o++,c++,l=o)}return I||(o++,f=1),r=e.substring(N,o),s=13}return r+=String.fromCharCode(g),o++,s=16;case 45:if(r+=String.fromCharCode(g),o++,o===n||!pt(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&&k(g);)o++,g=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(g),o++,s=16}}function k(g){if(vr(g)||Ut(g))return!1;switch(g){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function _(){let g;do g=h();while(g>=12&&g<=15);return g}return{setPosition:p,getPosition:()=>o,scan:t?_:h,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>o-i,getTokenStartLine:()=>a,getTokenStartCharacter:()=>i-u,getTokenError:()=>f}}function vr(e){return e===32||e===9}function Ut(e){return e===10||e===13}function pt(e){return e>=48&&e<=57}var su;(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"})(su||(su={}));var lg=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),mt=200,ug={" ":{"\n":new Array(mt).fill(0).map((e,t)=>`
|
|
890
|
+
`+" ".repeat(t)),"\r":new Array(mt).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(mt).fill(0).map((e,t)=>`\r
|
|
891
|
+
`+" ".repeat(t))}," ":{"\n":new Array(mt).fill(0).map((e,t)=>`
|
|
892
|
+
`+" ".repeat(t)),"\r":new Array(mt).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(mt).fill(0).map((e,t)=>`\r
|
|
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(`
|
|
783
894
|
|
|
784
895
|
---
|
|
785
896
|
|
|
786
|
-
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}
|
|
897
|
+
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}iu();async function vg(){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 ku(){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 vg(),r;try{r=JSON.parse(o)}catch{r={}}let i=await hu(n,r);console.log(JSON.stringify(i)),process.exit(0)}var Fn=process.argv[1]||"",Rg=Fn.endsWith("entry.ts")||Fn.endsWith("entry.js")||Fn.endsWith("olympus-hooks.mjs")||Fn.includes("olympus-hooks");Rg&&ku().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|