olympus-ai 2.7.4 → 3.2.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/.claude/.olympus-version.json +6 -0
- package/.claude/CLAUDE.md +84 -61
- package/.claude/agents/document-writer.md +152 -0
- package/.claude/agents/explore-medium.md +25 -0
- package/.claude/agents/explore.md +86 -0
- package/.claude/agents/frontend-engineer-high.md +17 -0
- package/.claude/agents/frontend-engineer-low.md +17 -0
- package/.claude/agents/frontend-engineer.md +80 -0
- package/.claude/agents/librarian-low.md +22 -0
- package/.claude/agents/librarian.md +70 -0
- package/.claude/agents/metis.md +85 -0
- package/.claude/agents/momus.md +97 -0
- package/.claude/agents/multimodal-looker.md +39 -0
- package/.claude/agents/olympian-high.md +32 -0
- package/.claude/agents/olympian-low.md +22 -0
- package/.claude/agents/olympian.md +78 -0
- package/.claude/agents/oracle-low.md +23 -0
- package/.claude/agents/oracle-medium.md +28 -0
- package/.claude/agents/oracle.md +77 -0
- package/.claude/agents/prometheus.md +125 -0
- package/.claude/agents/qa-tester.md +220 -0
- package/.claude/commands/analyze/skill.md +14 -0
- package/.claude/commands/ascent/skill.md +152 -0
- package/.claude/commands/cancel-ascent.md +9 -0
- package/.claude/commands/complete-plan.md +101 -0
- package/.claude/commands/deepsearch/skill.md +15 -0
- package/.claude/commands/olympus/skill.md +82 -0
- package/.claude/commands/olympus-default.md +26 -0
- package/.claude/commands/plan.md +71 -0
- package/.claude/commands/prometheus/skill.md +38 -0
- package/.claude/commands/review/skill.md +34 -0
- package/.claude/commands/ultrawork/skill.md +90 -0
- package/.claude/commands/update.md +38 -0
- package/.claude-plugin/plugin.json +1 -1
- package/COPYRIGHT +22 -0
- package/LICENSE +1 -1
- package/NOTICE +24 -0
- package/README.md +376 -10
- package/dist/__tests__/installer.test.js +1 -1
- package/dist/__tests__/learning/cleanup.test.d.ts +2 -0
- package/dist/__tests__/learning/cleanup.test.d.ts.map +1 -0
- package/dist/__tests__/learning/cleanup.test.js +122 -0
- package/dist/__tests__/learning/cleanup.test.js.map +1 -0
- package/dist/__tests__/learning/storage.test.d.ts +2 -0
- package/dist/__tests__/learning/storage.test.d.ts.map +1 -0
- package/dist/__tests__/learning/storage.test.js +75 -0
- package/dist/__tests__/learning/storage.test.js.map +1 -0
- package/dist/agents/definitions.d.ts.map +1 -1
- package/dist/agents/definitions.js +22 -6
- package/dist/agents/definitions.js.map +1 -1
- package/dist/agents/olympian.d.ts.map +1 -1
- package/dist/agents/olympian.js +23 -7
- package/dist/agents/olympian.js.map +1 -1
- package/dist/agents/orchestrator-olympus.js +1 -1
- package/dist/cli/index.js +128 -9
- package/dist/cli/index.js.map +1 -1
- package/dist/hooks/context-window-limit-recovery/index.d.ts +2 -3
- package/dist/hooks/context-window-limit-recovery/index.d.ts.map +1 -1
- package/dist/hooks/context-window-limit-recovery/index.js +2 -3
- package/dist/hooks/context-window-limit-recovery/index.js.map +1 -1
- package/dist/hooks/olympus-orchestrator/constants.d.ts +3 -3
- package/dist/hooks/olympus-orchestrator/constants.d.ts.map +1 -1
- package/dist/hooks/olympus-orchestrator/constants.js +3 -3
- package/dist/hooks/preemptive-compaction/index.d.ts +2 -3
- package/dist/hooks/preemptive-compaction/index.d.ts.map +1 -1
- package/dist/hooks/preemptive-compaction/index.js +2 -3
- package/dist/hooks/preemptive-compaction/index.js.map +1 -1
- package/dist/installer/index.d.ts +2 -2
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +114 -30
- package/dist/installer/index.js.map +1 -1
- package/dist/learning/cleanup.d.ts +18 -0
- package/dist/learning/cleanup.d.ts.map +1 -0
- package/dist/learning/cleanup.js +160 -0
- package/dist/learning/cleanup.js.map +1 -0
- package/dist/learning/discovery.d.ts.map +1 -1
- package/dist/learning/discovery.js +3 -1
- package/dist/learning/discovery.js.map +1 -1
- package/dist/learning/pattern-extractor.d.ts +1 -1
- package/dist/learning/pattern-extractor.d.ts.map +1 -1
- package/dist/learning/pattern-extractor.js +4 -2
- package/dist/learning/pattern-extractor.js.map +1 -1
- package/dist/learning/stats.d.ts +28 -0
- package/dist/learning/stats.d.ts.map +1 -0
- package/dist/learning/stats.js +112 -0
- package/dist/learning/stats.js.map +1 -0
- package/dist/learning/storage.d.ts +4 -0
- package/dist/learning/storage.d.ts.map +1 -1
- package/dist/learning/storage.js +26 -1
- package/dist/learning/storage.js.map +1 -1
- package/package.json +9 -4
- package/{dist → scripts/dist}/hooks/olympus-hooks.cjs +70 -69
- package/scripts/esbuild.hooks.mjs +67 -0
- package/scripts/generate-logo-hybrid-v2.mjs +213 -0
- package/scripts/generate-logo-hybrid.mjs +209 -0
- package/scripts/generate-logo-infinity.mjs +239 -0
- package/scripts/generate-logo-mythology.mjs +190 -0
- package/scripts/generate-logo-orchestration.mjs +228 -0
- package/scripts/generate-logo-recraft.mjs +147 -0
- package/scripts/generate-logo-simple.mjs +154 -0
- package/scripts/generate-logo.mjs +117 -0
- package/scripts/install.sh +4 -7
- package/scripts/rebrand.mjs +206 -0
- package/.claude-plugin/nul +0 -3
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
`)){let l=i.indexOf(":");if(l===-1)continue;let a=i.slice(0,l).trim(),c=i.slice(l+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),s[a]=c}return{data:s,body:r}}function eo(e,t){if(!(0,W.existsSync)(e))return[];let n;try{n=(0,W.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let s=(0,q.join)(e,r.name),i=(0,q.basename)(r.name,".md");try{let l=(0,W.readFileSync)(s,"utf-8"),{data:a,body:c}=no(l),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:c,scope:t})}catch{continue}}return o}function Nt(){let e=(0,q.join)(Zn,"commands"),t=(0,q.join)(process.cwd(),".claude","commands"),n=(0,q.join)(Zn,"skills"),o=eo(e,"user"),r=eo(t,"project"),s=[];if((0,W.existsSync)(n))try{let i=(0,W.readdirSync)(n,{withFileTypes:!0});for(let l of i){if(!l.isDirectory())continue;let a=(0,q.join)(n,l.name,"SKILL.md");if((0,W.existsSync)(a))try{let c=(0,W.readFileSync)(a,"utf-8"),{data:u,body:d}=no(c),m={name:u.name||l.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||l.name,path:a,metadata:m,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...s]}function Ye(e){return Nt().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function
|
|
3
|
+
"use strict";var Si=Object.create;var He=Object.defineProperty;var yi=Object.getOwnPropertyDescriptor;var Oi=Object.getOwnPropertyNames;var Ri=Object.getPrototypeOf,Ii=Object.prototype.hasOwnProperty;var _i=(e,t)=>{for(var n in t)He(e,n,{get:t[n],enumerable:!0})},Bn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Oi(t))!Ii.call(e,r)&&r!==n&&He(e,r,{get:()=>t[r],enumerable:!(o=yi(t,r))||o.enumerable});return e};var ce=(e,t,n)=>(n=e!=null?Si(Ri(e)):{},Bn(t||!e||!e.__esModule?He(n,"default",{value:e,enumerable:!0}):n,e)),Ai=e=>Bn(He({},"__esModule",{value:!0}),e);var dl={};_i(dl,{main:()=>gi});module.exports=Ai(dl);var It=new Map;function T(e){let t=It.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),It.set(e.event,t)}function Yn(e){return It.get(e)||[]}var Ni={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},wi=["ultrawork","ultrathink","olympus","search","analyze"];function Wn(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function Vn(e,t){let n=[];for(let o of wi){let r=Ni[o],s=e.match(r);s&&s.index!==void 0&&n.push({type:o,keyword:s[0],position:s.index})}return n}var Kn="auto-slash-command",Ge="<auto-slash-command>",Be="</auto-slash-command>",qn=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Jn=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var vi=/```[\s\S]*?```/g;function Xn(e){return e.replace(vi,"")}function zn(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(qn);if(!n)return null;let[o,r,s]=n;return{command:r.toLowerCase(),args:s.trim(),raw:o}}function Qn(e){return Jn.has(e.toLowerCase())}function _t(e){let n=Xn(e).trim();if(!n.startsWith("/"))return null;let o=zn(n);return!o||Qn(o.command)?null:o}function At(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var W=require("fs"),q=require("path"),to=require("os"),Zn=(0,q.join)((0,to.homedir)(),".claude");function no(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,s={};for(let i of o.split(`
|
|
4
|
+
`)){let l=i.indexOf(":");if(l===-1)continue;let a=i.slice(0,l).trim(),c=i.slice(l+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),s[a]=c}return{data:s,body:r}}function eo(e,t){if(!(0,W.existsSync)(e))return[];let n;try{n=(0,W.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let s=(0,q.join)(e,r.name),i=(0,q.basename)(r.name,".md");try{let l=(0,W.readFileSync)(s,"utf-8"),{data:a,body:c}=no(l),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:c,scope:t})}catch{continue}}return o}function Nt(){let e=(0,q.join)(Zn,"commands"),t=(0,q.join)(process.cwd(),".claude","commands"),n=(0,q.join)(Zn,"skills"),o=eo(e,"user"),r=eo(t,"project"),s=[];if((0,W.existsSync)(n))try{let i=(0,W.readdirSync)(n,{withFileTypes:!0});for(let l of i){if(!l.isDirectory())continue;let a=(0,q.join)(n,l.name,"SKILL.md");if((0,W.existsSync)(a))try{let c=(0,W.readFileSync)(a,"utf-8"),{data:u,body:d}=no(c),m={name:u.name||l.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||l.name,path:a,metadata:m,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...s]}function Ye(e){return Nt().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function xi(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function bi(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
5
5
|
`),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
|
|
6
6
|
`),t&&n.push(`**Arguments**: ${t}
|
|
7
7
|
`),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
|
|
8
8
|
`),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
|
|
9
9
|
`),n.push(`**Scope**: ${e.scope}
|
|
10
10
|
`),n.push(`---
|
|
11
|
-
`);let o=
|
|
11
|
+
`);let o=xi(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
|
|
12
12
|
|
|
13
13
|
---
|
|
14
14
|
`),n.push(`## User Request
|
|
15
15
|
`),n.push(t)),n.join(`
|
|
16
|
-
`)}function wt(e){let t=Ye(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:
|
|
16
|
+
`)}function wt(e){let t=Ye(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:bi(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function vt(){return Nt().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var We=new Set;function oo(){return{name:Kn,processMessage:(e,t)=>{let n=At(t);if(n.includes(Ge)||n.includes(Be))return{detected:!1};let o=_t(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(We.has(r))return{detected:!1};We.add(r);let s=wt(o);if(s.success&&s.replacementText){let l=`${Ge}
|
|
17
17
|
${s.replacementText}
|
|
18
18
|
${Be}`;return{detected:!0,parsedCommand:o,injectedMessage:l}}let i=`${Ge}
|
|
19
19
|
[AUTO-SLASH-COMMAND ERROR]
|
|
20
20
|
${s.error}
|
|
21
21
|
|
|
22
22
|
Original input: ${o.raw}
|
|
23
|
-
${Be}`;return{detected:!0,parsedCommand:o,injectedMessage:i}},listCommands:()=>vt(),findCommand:e=>Ye(e),clearSession:e=>{let t=[];for(let n of We)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)We.delete(n)}}}var
|
|
23
|
+
${Be}`;return{detected:!0,parsedCommand:o,injectedMessage:i}},listCommands:()=>vt(),findCommand:e=>Ye(e),clearSession:e=>{let t=[];for(let n of We)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)We.delete(n)}}}var Ci=[/\bultrathink\b/i,/\bthink\b/i],Pi=["\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"],Li=Pi.map(e=>new RegExp(e,"i")),Di=[...Ci,...Li],Mi=/```[\s\S]*?```/g,Ui=/`[^`]+`/g;function ji(e){return e.replace(Mi,"").replace(Ui,"")}function ro(e){let t=ji(e);return Di.some(n=>n.test(t))}function so(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function xt(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function bt(e){return e.replace(/\.(\d+)/g,"-$1")}var io={"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"},ao=new Set(Object.values(io)),co={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"}},$i={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 lo(e){let t=bt(e),{prefix:n,base:o}=xt(t);if(ao.has(o)||o.endsWith("-high"))return null;let r=io[o];return r?n+r:null}function Ct(e){let t=bt(e),{base:n}=xt(t);return ao.has(n)||n.endsWith("-high")}function Fi(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 Hi(e){return e in co}function uo(e,t){let n=bt(t),{base:o}=xt(n);if(Ct(n))return null;let r=Fi(e,t);if(!Hi(r))return null;let s=co[r],i=$i[r];if(!i)return null;let l=o.toLowerCase();return i.some(c=>l.includes(c.toLowerCase()))?s:null}var Q=new Map;function Gi(e){Q.delete(e)}function po(){return{processChatParams:(e,t)=>{let n=so(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!ro(n))return Q.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,Ct(r.modelId)))return Q.set(e,o),o;let s=lo(r.modelId),i=uo(r.providerId,r.modelId);return s&&(t.message.model={providerId:r.providerId,modelId:s},o.modelSwitched=!0),i&&(Object.assign(t.message,i),o.thinkingConfigInjected=!0),Q.set(e,o),o},onSessionDeleted:e=>{Q.delete(e)},isRequested:e=>Q.get(e)?.requested??!1,getState:e=>Q.get(e),clear:Gi}}var I=require("fs"),le=require("path"),Pt=require("os");function Lt(e){let t=e||process.cwd(),n=(0,le.join)(t,".olympus");return(0,le.join)(n,"ultrawork-state.json")}function Dt(){return(0,le.join)((0,Pt.homedir)(),".claude","ultrawork-state.json")}function Bi(e){let t=e||process.cwd(),n=(0,le.join)(t,".olympus");(0,I.existsSync)(n)||(0,I.mkdirSync)(n,{recursive:!0})}function Yi(){let e=(0,le.join)((0,Pt.homedir)(),".claude");(0,I.existsSync)(e)||(0,I.mkdirSync)(e,{recursive:!0})}function ne(e){let t=Lt(e);if((0,I.existsSync)(t))try{let o=(0,I.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Dt();if((0,I.existsSync)(n))try{let o=(0,I.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function fo(e,t){try{Bi(t);let n=Lt(t);(0,I.writeFileSync)(n,JSON.stringify(e,null,2)),Yi();let o=Dt();return(0,I.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function mo(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 fo(o,n)}function go(e){let t=Lt(e);if((0,I.existsSync)(t))try{(0,I.unlinkSync)(t)}catch{}let n=Dt();if((0,I.existsSync)(n))try{return(0,I.unlinkSync)(n),!0}catch{return!1}return!0}function ho(e){let t=ne(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),fo(t,e)?t:null)}function To(e){return`<ultrawork-persistence>
|
|
24
24
|
|
|
25
25
|
[ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
|
|
26
26
|
|
|
@@ -41,7 +41,7 @@ Original task: ${e.original_prompt}
|
|
|
41
41
|
|
|
42
42
|
---
|
|
43
43
|
|
|
44
|
-
`}var Eo=require("os"),
|
|
44
|
+
`}var Eo=require("os"),x=require("path");function V(){return process.platform==="win32"}function Wi(){return(0,x.join)((0,Eo.homedir)(),".claude")}function P(){return(0,x.join)(Wi(),"hooks")}var ko=`<ultrawork-mode>
|
|
45
45
|
|
|
46
46
|
**MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
|
|
47
47
|
|
|
@@ -180,8 +180,9 @@ Incomplete tasks remain in your todo list. Continue working on the next pending
|
|
|
180
180
|
|
|
181
181
|
- Proceed without asking for permission
|
|
182
182
|
- Mark each task complete when finished
|
|
183
|
-
- Do not stop until all tasks are done`;var
|
|
184
|
-
|
|
183
|
+
- Do not stop until all tasks are done`;var jl={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:V()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:V()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:V()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},$l={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:V()?`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:V()?`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:V()?`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:V()?`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:V()?`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:V()?`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:V()?`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,x.join)(P(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};var vo=require("path");var Io=require("os"),oe=require("path"),_=require("fs"),Vi=require("crypto"),Ki=1e4;function re(){return(0,oe.join)((0,Io.homedir)(),".claude","olympus","learning")}function _e(e){return(0,oe.join)(e,".olympus","learning")}function _o(e){let t=re();if((0,_.existsSync)(t)||(0,_.mkdirSync)(t,{recursive:!0}),e){let n=_e(e);(0,_.existsSync)(n)||(0,_.mkdirSync)(n,{recursive:!0})}}function Ao(e,t=Ki){if((0,_.existsSync)(e))try{let o=(0,_.readFileSync)(e,"utf-8").split(`
|
|
184
|
+
`).filter(r=>r.trim()).length;if(o>=t){let r=new Date().toISOString().replace(/[:.]/g,"-"),s=e.replace(".jsonl",`.${r}.old.jsonl`);(0,_.renameSync)(e,s),console.log(`[Olympus Learning] Archived ${o} entries to ${s}`)}}catch(n){console.error(`[Olympus Learning] Failed to rotate ${e}:`,n)}}function ue(e){_o();let t=(0,oe.join)(re(),"feedback-log.jsonl");Ao(t),(0,_.appendFileSync)(t,JSON.stringify(e)+`
|
|
185
|
+
`,"utf-8")}function de(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 No(e,t){try{let n=(0,oe.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 xo=require("crypto"),qi=10,Ji=1800*1e3;function bo(e){return(0,vo.join)(e,".olympus","session-state.json")}function wo(e){return{session_id:e||(0,xo.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null}}function pe(e,t){let n=bo(e),o=de(n,null);if(!o)return wo(t);let r=new Date(o.last_updated).getTime();return Date.now()-r>Ji?wo(t):o}function fe(e,t){let n=bo(e);t.last_updated=new Date().toISOString(),No(n,t)}function Co(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,qi),e.last_updated=new Date().toISOString(),e}function Po(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Ve(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}var Lo=require("crypto"),Xi={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 Mt(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Xi))for(let{regex:s,confidence:i}of r)s.test(t)&&(!n||i>n.confidence)&&(n={category:o,confidence:i});return n}async function Do(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=pe(n,o),s=Mt(t),i=Co(r,t,s?.category);if(s&&Ve(r)){let l={id:(0,Lo.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};ue(l)}fe(n,i)}var Mo=require("crypto");async function Uo(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=pe(n,o);if(!Ve(r))return;let s=Mt(t),i=s?.category==="praise"&&s.confidence>.7,l=zi(t,r.pending_completion?.task_description||"");if(i||l){let a={id:(0,Mo.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};ue(a);let c=Po(r);fe(n,c)}}function zi(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.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 jo(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 $o(){T({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=jo(e);if(!t)return{continue:!0};let n=Wn(t),o=Vn(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"),l=o.some(a=>a.type==="analyze");return r?(mo(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ko}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:So}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:yo}}:l?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Oo}}:{continue:!0}}}),T({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=oo().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),T({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=po(),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}}}),T({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=jo(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Do({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Uo({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var se=require("fs"),Z=require("path"),Fo=require("os");function Qi(e,t){let n=(0,Z.join)((0,Fo.homedir)(),".claude"),o=[];e&&(o.push((0,Z.join)(n,"sessions",e,"todos.json")),o.push((0,Z.join)(n,"todos",`${e}.json`))),t&&(o.push((0,Z.join)(t,".olympus","todos.json")),o.push((0,Z.join)(t,".claude","todos.json")));let r=(0,Z.join)(n,"todos");if((0,se.existsSync)(r))try{let s=(0,se.readdirSync)(r);for(let i of s)i.endsWith(".json")&&o.push((0,Z.join)(r,i))}catch{}return o}function Zi(e){try{let t=(0,se.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 ea(e){return e.status!=="completed"&&e.status!=="cancelled"}async function Ae(e,t){let n=Qi(e,t),o=new Set,r=[],s=[];for(let i of n){if(!(0,se.existsSync)(i))continue;let l=Zi(i);for(let a of l){let c=`${a.content}:${a.status}`;o.has(c)||(o.add(c),r.push(a),ea(a)&&s.push(a))}}return{count:s.length,todos:s,total:r.length}}function Ho(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var Ke=require("path");var Go=500;function Bo(e){let t=de((0,Ke.join)(re(),"user-preferences.json"),null),n=de((0,Ke.join)(_e(e),"patterns.json"),null),o=de((0,Ke.join)(re(),"agent-performance.json"),{}),r=[];t&&ta(t)&&r.push(na(t)),n&&n.conventions.length>0&&r.push(oa(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(ra(t.recurring_corrections.slice(0,5)));let s=Object.values(o).filter(l=>l.weak_areas.length>0);if(s.length>0&&r.push(sa(s)),r.length===0)return"";let i=`<learned-context>
|
|
185
186
|
|
|
186
187
|
${r.join(`
|
|
187
188
|
|
|
@@ -191,18 +192,18 @@ ${r.join(`
|
|
|
191
192
|
|
|
192
193
|
---
|
|
193
194
|
|
|
194
|
-
`;return i.length>
|
|
195
|
+
`;return i.length>Go*4?i.substring(0,Go*4)+`
|
|
195
196
|
...</learned-context>
|
|
196
197
|
|
|
197
198
|
---
|
|
198
199
|
|
|
199
|
-
`:i}function
|
|
200
|
-
`)}function
|
|
201
|
-
`)}function
|
|
202
|
-
`)}function
|
|
203
|
-
`)}function
|
|
204
|
-
`)}var qe=require("path"),ie=require("fs"),
|
|
205
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function
|
|
200
|
+
`:i}function ta(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function na(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(`
|
|
201
|
+
`)}function oa(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(`
|
|
202
|
+
`)}function ra(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
|
|
203
|
+
`)}function sa(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(`
|
|
204
|
+
`)}function Yo(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(`
|
|
205
|
+
`)}var qe=require("path"),ie=require("fs"),ia=require("crypto");function aa(e){let t=(0,qe.join)(re(),"discoveries.jsonl"),n=_e(e),o=(0,qe.join)(n,"discoveries.jsonl"),r=Wo(t),s=Wo(o),i=[...r,...s],l={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0};for(let c of i)l[c.category]++;let a=[...i].sort((c,u)=>u.verification_count-c.verification_count);return{project_discoveries:s,global_discoveries:r,total_discoveries:i.length,categories:l,most_useful:a.slice(0,5)}}function Vo(e,t=10){let n=aa(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,i=o.filter(l=>l.expires_at?new Date(l.expires_at)>r:!0).map(l=>{let a=(r.getTime()-new Date(l.timestamp).getTime())/864e5,c=Math.max(.1,1-a/90),u=(l.verification_count+1)*c*l.confidence;return{discovery:l,score:u}});return i.sort((l,a)=>a.score-l.score),i.slice(0,t).map(l=>l.discovery)}function Wo(e){if(!(0,ie.existsSync)(e))return[];try{return(0,ie.readFileSync)(e,"utf-8").split(`
|
|
206
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function Ko(){T({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Bo(e.directory),n=Vo(e.directory,5),o=Yo(n),r=t+(o?`
|
|
206
207
|
|
|
207
208
|
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),T({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[],r=ne(n);r?.active&&o.push(`<session-restore>
|
|
208
209
|
|
|
@@ -229,7 +230,7 @@ Please continue working on these tasks.
|
|
|
229
230
|
---
|
|
230
231
|
|
|
231
232
|
`),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
|
|
232
|
-
`)}}:{continue:!0}}})}var he=require("fs"),J=require("path"),Wt=require("os");var L=require("fs"),ee=require("path"),
|
|
233
|
+
`)}}:{continue:!0}}})}var he=require("fs"),J=require("path"),Wt=require("os");var L=require("fs"),ee=require("path"),qo=require("os");function Ut(e){let t=(0,ee.join)(e,".olympus");return(0,ee.join)(t,"ascent-state.json")}function ca(e){let t=(0,ee.join)(e,".olympus");(0,L.existsSync)(t)||(0,L.mkdirSync)(t,{recursive:!0})}function Ne(e){let t=Ut(e);if(!(0,L.existsSync)(t))return null;try{let n=(0,L.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function la(e,t){try{ca(e);let n=Ut(e);return(0,L.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function Je(e){let t=Ut(e);if(!(0,L.existsSync)(t))return!0;try{return(0,L.unlinkSync)(t),!0}catch{return!1}}function Jo(e){let t=Ne(e);return!t||!t.active?null:(t.iteration+=1,la(e,t)?t:null)}function Xo(e,t){let n=(0,ee.join)((0,qo.homedir)(),".claude"),o=[(0,ee.join)(n,"sessions",e,"transcript.md"),(0,ee.join)(n,"sessions",e,"messages.json"),(0,ee.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,L.existsSync)(r))try{let s=(0,L.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${ua(t)}\\s*</promise>`,"is").test(s))return!0}catch{continue}return!1}function ua(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var U=require("fs"),jt=require("path"),da=3;function $t(e){return(0,jt.join)(e,".olympus","ascent-verification.json")}function ve(e){let t=$t(e);if(!(0,U.existsSync)(t))return null;try{return JSON.parse((0,U.readFileSync)(t,"utf-8"))}catch{return null}}function zo(e,t){let n=$t(e),o=(0,jt.join)(e,".olympus");if(!(0,U.existsSync)(o))try{(0,U.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,U.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function we(e){let t=$t(e);if((0,U.existsSync)(t))try{return(0,U.unlinkSync)(t),!0}catch{return!1}return!0}function Qo(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:da,requested_at:new Date().toISOString(),original_task:n};return zo(e,o),o}function Zo(e,t,n){let o=ve(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(we(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(we(e),{...o,pending:!1}):(zo(e,o),o)):null}function Ft(e){return`<ascent-verification>
|
|
233
234
|
|
|
234
235
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
235
236
|
|
|
@@ -269,7 +270,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
269
270
|
|
|
270
271
|
---
|
|
271
272
|
|
|
272
|
-
`}function
|
|
273
|
+
`}function er(e){return`<ascent-continuation-after-rejection>
|
|
273
274
|
|
|
274
275
|
[ORACLE REJECTED - Continue Working]
|
|
275
276
|
|
|
@@ -294,7 +295,7 @@ Continue working now.
|
|
|
294
295
|
|
|
295
296
|
---
|
|
296
297
|
|
|
297
|
-
`}function
|
|
298
|
+
`}function tr(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function nr(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 A=require("fs"),me=require("path"),Ht=require("os");function Gt(e){let t=e||process.cwd(),n=(0,me.join)(t,".olympus");return(0,me.join)(n,"olympus-state.json")}function Bt(){return(0,me.join)((0,Ht.homedir)(),".claude","olympus-state.json")}function pa(e){let t=e||process.cwd(),n=(0,me.join)(t,".olympus");(0,A.existsSync)(n)||(0,A.mkdirSync)(n,{recursive:!0})}function fa(){let e=(0,me.join)((0,Ht.homedir)(),".claude");(0,A.existsSync)(e)||(0,A.mkdirSync)(e,{recursive:!0})}function ge(e){let t=Gt(e);if((0,A.existsSync)(t))try{let o=(0,A.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Bt();if((0,A.existsSync)(n))try{let o=(0,A.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function or(e,t){try{pa(t);let n=Gt(t);(0,A.writeFileSync)(n,JSON.stringify(e,null,2)),fa();let o=Bt();return(0,A.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Yt(e){let t=Gt(e);if((0,A.existsSync)(t))try{(0,A.unlinkSync)(t)}catch{}let n=Bt();if((0,A.existsSync)(n))try{return(0,A.unlinkSync)(n),!0}catch{return!1}return!0}function rr(e){let t=ge(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),or(t,e)?t:null)}function sr(e){let t=ge(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),or(t,e))}function ir(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
|
|
298
299
|
|
|
299
300
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
300
301
|
|
|
@@ -316,7 +317,7 @@ Original task: ${e.original_prompt}
|
|
|
316
317
|
|
|
317
318
|
---
|
|
318
319
|
|
|
319
|
-
`}function
|
|
320
|
+
`}function ar(e){let t=(0,J.join)((0,Wt.homedir)(),".claude"),n=[(0,J.join)(t,"sessions",e,"transcript.md"),(0,J.join)(t,"sessions",e,"messages.json"),(0,J.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,he.existsSync)(o))try{let r=(0,he.readFileSync)(o,"utf-8");if(tr(r))return!0}catch{continue}return!1}function ma(e){let t=(0,J.join)((0,Wt.homedir)(),".claude"),n=[(0,J.join)(t,"sessions",e,"transcript.md"),(0,J.join)(t,"sessions",e,"messages.json"),(0,J.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,he.existsSync)(o))try{let r=(0,he.readFileSync)(o,"utf-8"),s=nr(r);if(s.rejected)return s}catch{continue}return{rejected:!1,feedback:""}}async function ga(e,t){let n=t||process.cwd(),o=Ne(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=ve(n);if(r?.pending){if(e){if(ar(e))return we(n),Je(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let c=ma(e);if(c.rejected){Zo(n,!1,c.feedback);let u=ve(n);if(u)return{shouldBlock:!0,message:er(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:Ft(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(Xo(e||"",o.completion_promise)){Qo(n,o.completion_promise,o.prompt);let a=ve(n);return a?{shouldBlock:!0,message:Ft(a),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(Je(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 Je(n),we(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let i=Jo(n);return i?{shouldBlock:!0,message:`<ascent-continuation>
|
|
320
321
|
|
|
321
322
|
[ASCENT LOOP - ITERATION ${i.iteration}/${i.max_iterations}]
|
|
322
323
|
|
|
@@ -335,7 +336,7 @@ ${i.prompt?`Original task: ${i.prompt}`:""}
|
|
|
335
336
|
|
|
336
337
|
---
|
|
337
338
|
|
|
338
|
-
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function
|
|
339
|
+
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function ha(e,t,n){let o=ne(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return go(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=ho(t);return r?{shouldBlock:!0,message:To(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Ta(e,t,n){let o=ge(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return Yt(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&&ar(e)?(sr(t),Yt(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
|
|
339
340
|
|
|
340
341
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
341
342
|
|
|
@@ -358,7 +359,7 @@ DO NOT stop until Oracle has approved.
|
|
|
358
359
|
|
|
359
360
|
---
|
|
360
361
|
|
|
361
|
-
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=
|
|
362
|
+
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=rr(t);return r?{shouldBlock:!0,message:ir(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Ea(e,t){let n=await Ae(e,t);if(n.count===0)return null;let o=Ho(n),r=o?`
|
|
362
363
|
|
|
363
364
|
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
364
365
|
|
|
@@ -370,20 +371,20 @@ ${Ro}
|
|
|
370
371
|
|
|
371
372
|
---
|
|
372
373
|
|
|
373
|
-
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function
|
|
374
|
-
`),n={},o=0;for(;o<t.length;){let r=t[o],s=r.indexOf(":");if(s===-1){o++;continue}let i=r.slice(0,s).trim(),l=r.slice(s+1).trim();if(i==="description")n.description=xe(l);else if(i==="alwaysApply")n.alwaysApply=l==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:a,consumed:c}=
|
|
374
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function cr(e,t){let n=t||process.cwd(),r=(await Ae(e,n)).count>0,s=await ga(e,n);if(s?.shouldBlock)return s;let i=await ha(e,n,r);if(i?.shouldBlock)return i;let l=await Ta(e,n,r);if(l?.shouldBlock)return l;if(r){let a=await Ea(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function lr(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var Te=require("fs"),Vt=require("path"),ur=require("os");var dr=require("crypto");function ka(){let e=(0,Vt.join)((0,ur.homedir)(),".claude","todos");if(!(0,Te.existsSync)(e))return 0;let t=0;try{let n=(0,Te.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,Te.readFileSync)((0,Vt.join)(e,o),"utf-8"),s=JSON.parse(r);Array.isArray(s)&&(t+=s.filter(i=>i.status!=="completed"&&i.status!=="cancelled").length)}catch{}}catch{}return t}async function pr(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=pe(t,n),r=ka();if(r>0&&o.pending_completion){let s={id:(0,dr.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};ue(s)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},fe(t,o)}function fr(){T({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await cr(t,n),r=lr(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),T({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await pr({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var nn=require("fs"),on=require("os"),be=require("path");var B=require("fs"),M=require("path");var Kt=require("path"),mr=require("os"),Sa=(0,Kt.join)((0,mr.homedir)(),".olympus"),Xe=(0,Kt.join)(Sa,"rules-injector"),gr=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],hr=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],Tr=[".github/copilot-instructions.md"],Er=/\.instructions\.md$/,kr=".claude/rules",Sr=[".md",".mdc"],qt=["read","write","edit","multiedit"];function ya(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function Oa(e,t){return ya(t)?Er.test(e):Sr.some(n=>e.endsWith(n))}function zt(e){let t;try{t=(0,B.statSync)(e).isDirectory()?e:(0,M.dirname)(e)}catch{t=(0,M.dirname)(e)}for(;;){for(let o of gr){let r=(0,M.join)(t,o);if((0,B.existsSync)(r))return t}let n=(0,M.dirname)(t);if(n===t)return null;t=n}}function Xt(e,t){if((0,B.existsSync)(e))try{let n=(0,B.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,M.join)(e,o.name);o.isDirectory()?Xt(r,t):o.isFile()&&Oa(o.name,e)&&t.push(r)}}catch{}}function Jt(e){try{return(0,B.realpathSync)(e)}catch{return e}}function Qt(e,t,n){let o=[],r=new Set,s=(0,M.dirname)(n),i=0;for(;;){for(let[u,d]of hr){let m=(0,M.join)(s,u,d),E=[];Xt(m,E);for(let k of E){let y=Jt(k);r.has(y)||(r.add(y),o.push({path:k,realPath:y,isGlobal:!1,distance:i}))}}if(e&&s===e)break;let c=(0,M.dirname)(s);if(c===s)break;s=c,i++}if(e)for(let c of Tr){let u=(0,M.join)(e,c);if((0,B.existsSync)(u))try{if((0,B.statSync)(u).isFile()){let m=Jt(u);r.has(m)||(r.add(m),o.push({path:u,realPath:m,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let l=(0,M.join)(t,kr),a=[];Xt(l,a);for(let c of a){let u=Jt(c);r.has(u)||(r.add(u),o.push({path:c,realPath:u,isGlobal:!0,distance:9999}))}return o.sort((c,u)=>c.isGlobal!==u.isGlobal?c.isGlobal?1:-1:c.distance-u.distance),o}var yr=require("crypto"),Or=require("path");function Ra(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function Zt(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 i=(n?(0,Or.relative)(n,t):t).replace(/\\/g,"/");for(let l of r)if(Ra(l,i))return{applies:!0,reason:`glob: ${l}`};return{applies:!1}}function Rr(e,t){return t.has(e)}function Ir(e){return(0,yr.createHash)("sha256").update(e).digest("hex").slice(0,16)}function _r(e,t){return t.has(e)}function en(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:Ia(o),body:r}}catch{return{metadata:{},body:e}}}function Ia(e){let t=e.split(`
|
|
375
|
+
`),n={},o=0;for(;o<t.length;){let r=t[o],s=r.indexOf(":");if(s===-1){o++;continue}let i=r.slice(0,s).trim(),l=r.slice(s+1).trim();if(i==="description")n.description=xe(l);else if(i==="alwaysApply")n.alwaysApply=l==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:a,consumed:c}=_a(l,t,o);n.globs=Na(n.globs,a),o+=c;continue}o++}return n}function xe(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function _a(e,t,n){if(e.startsWith("["))return{value:Aa(e),consumed:1};if(!e||e===""){let r=[],s=1;for(let i=n+1;i<t.length;i++){let l=t[i],a=l.match(/^\s+-\s*(.*)$/);if(a){let c=xe(a[1].trim());c&&r.push(c),s++}else if(l.trim()==="")s++;else break}if(r.length>0)return{value:r,consumed:s}}let o=xe(e);return o.includes(",")?{value:o.split(",").map(s=>s.trim()).filter(s=>s.length>0),consumed:1}:{value:o,consumed:1}}function Aa(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,s="";for(let l=0;l<t.length;l++){let a=t[l];if(!r&&(a==='"'||a==="'"))r=!0,s=a;else if(r&&a===s)r=!1,s="";else if(!r&&a===","){let c=o.trim();c&&n.push(xe(c)),o=""}else o+=a}let i=o.trim();return i&&n.push(xe(i)),n}function Na(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var j=require("fs"),Ar=require("path");function tn(e){return(0,Ar.join)(Xe,`${e}.json`)}function Nr(e){let t=tn(e);if(!(0,j.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,j.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 wr(e,t){(0,j.existsSync)(Xe)||(0,j.mkdirSync)(Xe,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,j.writeFileSync)(tn(e),JSON.stringify(n,null,2))}function vr(e){let t=tn(e);(0,j.existsSync)(t)&&(0,j.unlinkSync)(t)}function xr(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Nr(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,be.resolve)(e,i):null}function r(i,l){let a=o(i);if(!a)return[];let c=zt(a),u=n(l),d=(0,on.homedir)(),m=Qt(c,d,a),E=[];for(let k of m)if(!Rr(k.realPath,u.realPaths))try{let y=(0,nn.readFileSync)(k.path,"utf-8"),{metadata:O,body:w}=en(y),C;if(k.isSingleFile)C="copilot-instructions (always apply)";else{let v=Zt(O,a,c);if(!v.applies)continue;C=v.reason??"matched"}let p=Ir(w);if(_r(p,u.contentHashes))continue;let N=c?(0,be.relative)(c,k.path):k.path;E.push({relativePath:N,matchReason:C,content:w,distance:k.distance}),u.realPaths.add(k.realPath),u.contentHashes.add(p)}catch{}return E.length>0&&(E.sort((k,y)=>k.distance-y.distance),wr(l,u)),E}function s(i){if(i.length===0)return"";let l="";for(let a of i)l+=`
|
|
375
376
|
|
|
376
377
|
[Rule: ${a.relativePath}]
|
|
377
378
|
[Match: ${a.matchReason}]
|
|
378
|
-
${a.content}`;return l}return{processToolExecution:(i,l,a)=>{if(!qt.includes(i.toLowerCase()))return"";let c=r(l,a);return s(c)},getRulesForFile:i=>{let l=o(i);if(!l)return[];let a=zt(l),c=(0,on.homedir)(),u=Qt(a,c,l),d=[];for(let m of u)try{let E=(0,nn.readFileSync)(m.path,"utf-8"),{metadata:k,body:y}=en(E),O;if(m.isSingleFile)O="copilot-instructions (always apply)";else{let
|
|
379
|
+
${a.content}`;return l}return{processToolExecution:(i,l,a)=>{if(!qt.includes(i.toLowerCase()))return"";let c=r(l,a);return s(c)},getRulesForFile:i=>{let l=o(i);if(!l)return[];let a=zt(l),c=(0,on.homedir)(),u=Qt(a,c,l),d=[];for(let m of u)try{let E=(0,nn.readFileSync)(m.path,"utf-8"),{metadata:k,body:y}=en(E),O;if(m.isSingleFile)O="copilot-instructions (always apply)";else{let C=Zt(k,l,a);if(!C.applies)continue;O=C.reason??"matched"}let w=a?(0,be.relative)(a,m.path):m.path;d.push({relativePath:w,matchReason:O,content:y,distance:m.distance})}catch{}return d.sort((m,E)=>m.distance-E.distance)},clearSession:i=>{t.delete(i),vr(i)},isTrackedTool:i=>qt.includes(i.toLowerCase())}}var Qe=require("node:fs"),X=require("node:path");var $=require("node:fs"),Pr=require("node:path");var rn=require("node:path"),br=require("node:os"),wa=(0,rn.join)((0,br.homedir)(),".olympus"),ze=(0,rn.join)(wa,"directory-readme"),Cr="README.md",sn=["read","write","edit","multiedit"];function an(e){return(0,Pr.join)(ze,`${e}.json`)}function Lr(e){let t=an(e);if(!(0,$.existsSync)(t))return new Set;try{let n=(0,$.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function Dr(e,t){(0,$.existsSync)(ze)||(0,$.mkdirSync)(ze,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,$.writeFileSync)(an(e),JSON.stringify(n,null,2))}function Mr(e){let t=an(e);(0,$.existsSync)(t)&&(0,$.unlinkSync)(t)}var Ur=4,va=5e3;function xa(e,t=va){if(Math.ceil(e.length/Ur)<=t)return{result:e,truncated:!1};let o=t*Ur;return{result:e.slice(0,o),truncated:!0}}function jr(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Lr(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,X.resolve)(e,i):null}function r(i){let l=[],a=i;for(;;){let c=(0,X.join)(a,Cr);if((0,Qe.existsSync)(c)&&l.push(c),a===e)break;let u=(0,X.dirname)(a);if(u===a||!u.startsWith(e))break;a=u}return l.reverse()}function s(i,l){let a=o(i);if(!a)return"";let c=(0,X.dirname)(a),u=n(l),d=r(c),m="";for(let E of d){let k=(0,X.dirname)(E);if(!u.has(k))try{let y=(0,Qe.readFileSync)(E,"utf-8"),{result:O,truncated:w}=xa(y),C=w?`
|
|
379
380
|
|
|
380
381
|
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${E}]`:"";m+=`
|
|
381
382
|
|
|
382
383
|
[Project README: ${E}]
|
|
383
|
-
${O}${
|
|
384
|
+
${O}${C}`,u.add(k)}catch{}}return m&&Dr(l,u),m}return{processToolExecution:(i,l,a)=>sn.includes(i.toLowerCase())?s(l,a):"",getReadmesForFile:i=>{let l=o(i);if(!l)return[];let a=(0,X.dirname)(l);return r(a)},clearSession:i=>{t.delete(i),Mr(i)},isTrackedTool:i=>sn.includes(i.toLowerCase())}}var $r="non-interactive-env",Fr={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"},cn={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
|
|
384
385
|
option1
|
|
385
386
|
option2
|
|
386
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
387
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Hr=cn.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function ba(e){for(let t=0;t<Hr.length;t++)if(Hr[t].test(e))return cn.banned[t]}function Ca(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function Pa(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${Ca(o)}`).join(" ")};`}var ln={name:$r,async beforeCommand(e){let t=ba(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${Pa(Fr)} ${e}`,warning:n}:{command:e,warning:n}}};var un=require("child_process");var Gr="olympus-orchestrator",Br=".olympus/",Yr=["Write","Edit","write","edit"],Wr=`
|
|
387
388
|
|
|
388
389
|
---
|
|
389
390
|
|
|
@@ -399,7 +400,7 @@ As an orchestrator, you should:
|
|
|
399
400
|
- **COORDINATE** multiple tasks and ensure completion
|
|
400
401
|
|
|
401
402
|
You should NOT:
|
|
402
|
-
- Write code directly (except for \`.olympus/\` files like plans
|
|
403
|
+
- Write code directly (except for \`.olympus/\` files like plans)
|
|
403
404
|
- Make direct file edits outside \`.olympus/\`
|
|
404
405
|
- Implement features yourself
|
|
405
406
|
|
|
@@ -409,7 +410,7 @@ You should NOT:
|
|
|
409
410
|
3. Verify the subagent's work after completion
|
|
410
411
|
|
|
411
412
|
---
|
|
412
|
-
`,
|
|
413
|
+
`,Vr=`
|
|
413
414
|
|
|
414
415
|
---
|
|
415
416
|
|
|
@@ -431,7 +432,7 @@ As an ORCHESTRATOR, you MUST:
|
|
|
431
432
|
3. **COORDINATE** - you orchestrate, you don't implement
|
|
432
433
|
|
|
433
434
|
**ALLOWED direct file operations:**
|
|
434
|
-
- Files inside \`.olympus/\` (plans,
|
|
435
|
+
- Files inside \`.olympus/\` (plans, drafts)
|
|
435
436
|
- Reading files for verification
|
|
436
437
|
- Running diagnostics/tests
|
|
437
438
|
|
|
@@ -455,16 +456,16 @@ prompt="[specific single task with clear acceptance criteria]"
|
|
|
455
456
|
DELEGATE. DON'T IMPLEMENT.
|
|
456
457
|
|
|
457
458
|
---
|
|
458
|
-
`,
|
|
459
|
+
`,Kr=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
459
460
|
|
|
460
461
|
You have an active work plan with incomplete tasks. Continue working.
|
|
461
462
|
|
|
462
463
|
RULES:
|
|
463
464
|
- Proceed without asking for permission
|
|
464
465
|
- Mark each checkbox [x] in the plan file when done
|
|
465
|
-
-
|
|
466
|
+
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
466
467
|
- Do not stop until all tasks are complete
|
|
467
|
-
- If blocked, document the blocker and move to the next task`,
|
|
468
|
+
- If blocked, document the blocker and move to the next task`,qr=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
468
469
|
|
|
469
470
|
Subagents FREQUENTLY claim completion when:
|
|
470
471
|
- Tests are actually FAILING
|
|
@@ -479,7 +480,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
479
480
|
3. Check build/typecheck - Must succeed
|
|
480
481
|
|
|
481
482
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
482
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
483
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Jr=`
|
|
483
484
|
|
|
484
485
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
485
486
|
|
|
@@ -502,37 +503,37 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
502
503
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
503
504
|
|
|
504
505
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
505
|
-
`;var Ce=".olympus",Ze="quest.json",
|
|
506
|
+
`;var Ce=".olympus",Ze="quest.json",La=`${Ce}/${Ze}`,Xr="notepads",Da=`${Ce}/${Xr}`;var Y=require("fs"),et=require("path");function zr(e){return(0,et.join)(e,Ce,Ze)}function tt(e){let t=zr(e);if(!(0,Y.existsSync)(t))return null;try{let n=(0,Y.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function nt(e){if(!(0,Y.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,Y.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],o=t.match(/^[-*]\s*\[[xX]\]/gm)||[],r=n.length+o.length,s=o.length;return{total:r,completed:s,isComplete:r===0||s===r}}catch{return{total:0,completed:0,isComplete:!0}}}function Qr(e){return e?e.includes(Br):!0}function Zr(e){return Yr.includes(e)}function ja(e){try{let t=(0,un.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,un.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let s of n.split(`
|
|
506
507
|
`)){if(!s)continue;let i=s.substring(0,2).trim(),l=s.substring(3);i==="A"||i==="??"?o.set(l,"added"):i==="D"?o.set(l,"deleted"):o.set(l,"modified")}let r=[];for(let s of t.split(`
|
|
507
|
-
`)){let i=s.split(" ");if(i.length<3)continue;let[l,a,c]=i,u=l==="-"?0:parseInt(l,10),d=a==="-"?0:parseInt(a,10);r.push({path:c,added:u,removed:d,status:o.get(c)??"modified"})}return r}catch{return[]}}function
|
|
508
|
+
`)){let i=s.split(" ");if(i.length<3)continue;let[l,a,c]=i,u=l==="-"?0:parseInt(l,10),d=a==="-"?0:parseInt(a,10);r.push({path:c,added:u,removed:d,status:o.get(c)??"modified"})}return r}catch{return[]}}function $a(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
508
509
|
No file changes detected.
|
|
509
510
|
`;let t=e.filter(s=>s.status==="modified"),n=e.filter(s=>s.status==="added"),o=e.filter(s=>s.status==="deleted"),r=["[FILE CHANGES SUMMARY]"];if(t.length>0){r.push("Modified files:");for(let s of t)r.push(` ${s.path} (+${s.added}, -${s.removed})`);r.push("")}if(n.length>0){r.push("Created files:");for(let s of n)r.push(` ${s.path} (+${s.added})`);r.push("")}if(o.length>0){r.push("Deleted files:");for(let s of o)r.push(` ${s.path} (-${s.removed})`);r.push("")}return r.join(`
|
|
510
|
-
`)}function
|
|
511
|
+
`)}function es(e){let t=qr;return e&&(t+=`
|
|
511
512
|
|
|
512
513
|
---
|
|
513
514
|
|
|
514
515
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
515
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
516
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function Fa(e,t,n){let o=t.total-t.completed;return`
|
|
516
517
|
---
|
|
517
518
|
|
|
518
519
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
519
520
|
|
|
520
521
|
---
|
|
521
522
|
|
|
522
|
-
${
|
|
523
|
+
${es(n)}
|
|
523
524
|
|
|
524
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
525
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function Ha(e,t,n){return Kr.replace(/{PLAN_NAME}/g,e)+`
|
|
525
526
|
|
|
526
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
527
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function Ga(e){let{toolName:t,toolInput:n}=e;if(!Zr(t))return{continue:!0};let o=n?.filePath??n?.path??n?.file;return!o||Qr(o)?{continue:!0}:{continue:!0,message:Vr.replace("$FILE_PATH",o)}}function Ba(e,t){let{toolName:n,toolInput:o,directory:r}=e,s=r||process.cwd();if(Zr(n)){let i=o?.filePath??o?.path??o?.file;if(i&&!Qr(i))return{continue:!0,modifiedOutput:t+Wr}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let l=ja(s),a=$a(l),c=tt(s);if(c){let u=nt(c.active_plan);return{continue:!0,modifiedOutput:`
|
|
527
528
|
## SUBAGENT WORK COMPLETED
|
|
528
529
|
|
|
529
530
|
${a}
|
|
530
531
|
<system-reminder>
|
|
531
|
-
${
|
|
532
|
+
${Fa(c.plan_name,u)}
|
|
532
533
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
533
534
|
<system-reminder>
|
|
534
|
-
${
|
|
535
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
535
|
+
${es()}
|
|
536
|
+
</system-reminder>`}}return{continue:!0}}function Ya(e){let t=tt(e);if(!t)return{shouldContinue:!1};let n=nt(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:Ha(t.plan_name,o,n.total)}}function ot(e){return{name:Gr,preTool:(t,n)=>Ga({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>Ba({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>Ya(e),getSingleTaskDirective:()=>Jr}}function ts(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function ns(){T({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=xr(e.directory||process.cwd()),n=ts(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}}}),T({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=jr(e.directory||process.cwd()),n=ts(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}}}),T({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!ln.beforeCommand)return{continue:!0};let n=await ln.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}}}}),T({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>ot(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var Wa=["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"],Va=`
|
|
536
537
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
537
538
|
|
|
538
539
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -543,7 +544,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
543
544
|
4. CONTINUE with corrected action based on the real file content
|
|
544
545
|
|
|
545
546
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
546
|
-
`;function
|
|
547
|
+
`;function Ka(e){let t=e.toLowerCase();return Wa.some(n=>t.includes(n.toLowerCase()))}function os(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:Ka(t.output)?{...t,output:t.output+Va}:t}}var is=ce(require("fs"),1),st=ce(require("path"),1),as=require("os");var rt=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),dn=["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"],pn=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
|
|
547
548
|
|
|
548
549
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
549
550
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -581,13 +582,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
581
582
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
582
583
|
|
|
583
584
|
Detected comments/docstrings:
|
|
584
|
-
`,fn={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},mn={".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
|
|
585
|
-
`;
|
|
585
|
+
`,fn={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},mn={".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 qa(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function Ja(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of rt){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>rt.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function Xa(e){let t=e.text.toLowerCase().trim();for(let n of dn)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function za(e){return{shouldSkip:!1}}function Qa(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 Za(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 ec=[qa,Ja,Xa,Qa,Za,za];function gn(e){return e.filter(t=>{for(let n of ec)if(n(t).shouldSkip)return!1;return!0})}var tc=process.env.COMMENT_CHECKER_DEBUG==="1",nc=st.join((0,as.tmpdir)(),"comment-checker-debug.log");function ae(...e){if(tc){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
586
|
+
`;is.appendFileSync(nc,t)}}function oc(e){let t=st.extname(e).toLowerCase();return mn[t]}function hn(e,t){let n=oc(t);if(!n)return ae("unsupported language for:",t),[];let o=fn[n];if(!o)return ae("no pattern for language:",n),[];let r=[],s=e.split(`
|
|
586
587
|
`);o.lastIndex=0;let i;for(;(i=o.exec(e))!==null;){let l=i.index,a=i[0],u=e.substring(0,l).split(`
|
|
587
|
-
`).length,d="line",m=!1;a.startsWith("/*")||a.startsWith("<!--")?d="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(d="docstring",m=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:m})}return r}function
|
|
588
|
+
`).length,d="line",m=!1;a.startsWith("/*")||a.startsWith("<!--")?d="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(d="docstring",m=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:m})}return r}function rc(e,t){return hn(e,t)}function rs(e,t,n){let o=hn(e,t);if(n){let r=hn(n,t),s=new Set(r.map(i=>i.text));return o.filter(i=>!s.has(i.text))}return o}function sc(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=pn;for(let[o,r]of t){n+=`
|
|
588
589
|
File: ${o}
|
|
589
590
|
`;for(let s of r){let i=s.isDocstring?"docstring":s.commentType;n+=` Line ${s.lineNumber} (${i}): ${s.text.substring(0,100)}${s.text.length>100?"...":""}
|
|
590
|
-
`}}return n}function
|
|
591
|
+
`}}return n}function ic(e,t,n,o,r){let s=[];if(t)s=rc(t,e);else if(o)s=rs(o,e,n);else if(r&&r.length>0)for(let l of r){let a=rs(l.new_string,e,l.old_string);s.push(...a)}let i=gn(s);return ae(`found ${s.length} comments, ${i.length} flagged after filtering`),i.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:i.length,message:sc(i),comments:i}}var Pe=new Map,ac=6e4;function cc(){let e=Date.now();for(let[t,n]of Pe)e-n.timestamp>ac&&Pe.delete(t)}var ss=!1;function cs(e){return ae("createCommentCheckerHook called",{config:e}),ss||(ss=!0,setInterval(cc,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,s=t.tool_input.old_string??t.tool_input.oldString,i=t.tool_input.new_string??t.tool_input.newString,l=t.tool_input.edits;if(!o)return null;let a=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return ae("registering pendingCall:",{callId:a,filePath:o,tool:n}),Pe.set(a,{filePath:o,content:r,oldString:s,newString:i,edits:l,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[i,l]of Pe)if(l.sessionId===t.session_id&&l.tool===n){o=l,r=i;break}if(!o){let i=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!i)return null;o={filePath:i,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&&Pe.delete(r),t.tool_response){let i=t.tool_response.toLowerCase();if(i.includes("error:")||i.includes("failed to")||i.includes("could not")||i.startsWith("error"))return ae("skipping due to tool failure in response"),null}let s=ic(o.filePath,o.content,o.oldString,o.newString,o.edits);return s.hasComments&&s.message?(ae("detected comments, returning message"),e?.customPrompt||s.message):null}}}var gs=ce(require("fs"),1),hs=ce(require("path"),1),Ts=require("os");var us=[/(\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],ds=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],lc=[/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],uc=/messages\.(\d+)/;function dc(e){return lc.some(t=>t.test(e))}function Tn(e){for(let t of us){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 ls(e){let t=e.match(uc);if(t)return parseInt(t[1],10)}function Ee(e){if(dc(e))return!1;let t=e.toLowerCase();return ds.some(n=>t.includes(n.toLowerCase()))}function it(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:ls(e)};if(Ee(e)){let c=Tn(e);return{currentTokens:c?.current??0,maxTokens:c?.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,s=t.message,i=t.error,l=i?.error;if(typeof r=="string"&&n.push(r),typeof s=="string"&&n.push(s),typeof i?.message=="string"&&n.push(i.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 l?.message=="string"&&n.push(l.message),typeof o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let c=JSON.stringify(t);Ee(c)&&n.push(c)}catch{}let a=n.join(" ");if(!Ee(a))return null;if(typeof r=="string")try{let c=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of c){let m=r.match(d);if(m)try{let E=JSON.parse(m[1]),k=E.error?.message||"",y=Tn(k);if(y)return{currentTokens:y.current,maxTokens:y.max,requestId:E.request_id,errorType:E.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&Ee(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let c of n){let u=Tn(c);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:ls(a)}:Ee(a)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function En(e){return Ee(e)}var kn=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
591
592
|
|
|
592
593
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
593
594
|
|
|
@@ -634,13 +635,13 @@ Before starting a new session:
|
|
|
634
635
|
3. Document the current state of the task
|
|
635
636
|
|
|
636
637
|
You can copy this conversation summary to continue in a new session.
|
|
637
|
-
`;var Rn={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var
|
|
638
|
-
`;
|
|
638
|
+
`;var Rn={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var pc=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",fc=hs.join((0,Ts.tmpdir)(),"context-limit-recovery-debug.log");function at(...e){if(pc){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
639
|
+
`;gs.appendFileSync(fc,t)}}var ct=new Map,Es=3e5;function ps(e){let t=ct.get(e),n=Date.now();return t&&n-t.lastErrorTime>Es&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},ct.set(e,t)),t}function mc(){let e=Date.now();for(let[t,n]of ct)e-n.lastErrorTime>Es&&ct.delete(t)}var fs=!1;function ks(e){return at("createContextLimitRecoveryHook called",{config:e}),fs||(fs=!0,setInterval(mc,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=it(t.tool_response);if(!n&&!En(t.tool_response))return null;at("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=ps(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=ms(n,o,e);return r.message?(at("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=it(t.error);if(!n)return{attempted:!1,success:!1};at("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=ps(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=ms(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function ms(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:yn,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>Rn.maxAttempts)return{message:On,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=kn;return e?.currentTokens&&e?.maxTokens&&(o+=`
|
|
639
640
|
Token Details:
|
|
640
641
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
641
642
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
642
643
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
643
|
-
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:Sn,errorType:e?.errorType||"token_limit_exceeded"}}var
|
|
644
|
+
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:Sn,errorType:e?.errorType||"token_limit_exceeded"}}var Ss=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,gc=/exceeds maximum allowed tokens/i;function hc(e){let t=e.match(Ss);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Tc(e,t){return e.toLowerCase()==="read"&&(Ss.test(t)||gc.test(t))}function Ec(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
|
|
644
645
|
|
|
645
646
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
646
647
|
|
|
@@ -670,7 +671,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
670
671
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
671
672
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
672
673
|
|
|
673
|
-
Proceed with one of these strategies.`.trim()}function
|
|
674
|
+
Proceed with one of these strategies.`.trim()}function ys(){return{postToolUse:e=>{if(!e.tool_response||!Tc(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=hc(e.tool_response);return Ec(t,n||void 0)}}}var Ns=ce(require("fs"),1),ws=ce(require("path"),1),vs=require("os");var In=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,lt=4,_n=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
674
675
|
|
|
675
676
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
676
677
|
|
|
@@ -709,8 +710,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
709
710
|
|
|
710
711
|
WARNING: Further messages may fail if context is not reduced.
|
|
711
712
|
Action required: Run /compact now.
|
|
712
|
-
`;var
|
|
713
|
-
`;
|
|
713
|
+
`;var kc=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Sc=ws.join((0,vs.tmpdir)(),"preemptive-compaction-debug.log");function ke(...e){if(kc){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
714
|
+
`;Ns.appendFileSync(Sc,t)}}var ut=new Map;function yc(){let e=Date.now(),t=1800*1e3;for(let[n,o]of ut)e-o.lastWarningTime>t&&ut.delete(n)}var Os=!1;function xs(e){return Math.ceil(e.length/lt)}function Oc(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=In,s=xs(e),i=s/r,l=i>=n,a=i>=o,c="none";return a?c="compact":l&&(c="warn"),{totalTokens:s,usageRatio:i,isWarning:l,isCritical:a,action:c}}function dt(e){let t=ut.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},ut.set(e,t)),t}function Rc(e,t){let n=dt(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,s=Date.now();return s-n.lastWarningTime<o?(ke("skipping warning - cooldown active",{sessionId:e,elapsed:s-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(ke("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Ic(e){let t=dt(e);t.lastWarningTime=Date.now(),t.warningCount++}function bs(e){return ke("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(Os||(Os=!0,setInterval(yc,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=xs(t.tool_response),s=dt(t.session_id);s.estimatedTokens+=r,ke("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:s.estimatedTokens});let i=Oc("x".repeat(s.estimatedTokens*lt),e);return!i.isWarning||!Rc(t.session_id,e)?null:(Ic(t.session_id),ke("injecting context warning",{sessionId:t.session_id,usageRatio:i.usageRatio,isCritical:i.isCritical}),e?.customMessage?e.customMessage:i.isCritical?An:_n)},stop:t=>{let n=dt(t.session_id);return n.warningCount>0&&(ke("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var F=require("fs"),Ps=require("path");var Nn=require("path"),Cs=require("os"),_c=(0,Nn.join)((0,Cs.homedir)(),".olympus"),pt=(0,Nn.join)(_c,"agent-usage-reminder"),wn=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"]),vn=new Set(["task","call_omo_agent","olympus_task"]),xn=`
|
|
714
715
|
[Agent Usage Reminder]
|
|
715
716
|
|
|
716
717
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -734,7 +735,7 @@ WHY:
|
|
|
734
735
|
- Reduces context window usage in main session
|
|
735
736
|
|
|
736
737
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
737
|
-
`;function bn(e){return(0,
|
|
738
|
+
`;function bn(e){return(0,Ps.join)(pt,`${e}.json`)}function Cn(e){let t=bn(e);if(!(0,F.existsSync)(t))return null;try{let n=(0,F.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function ft(e){(0,F.existsSync)(pt)||(0,F.mkdirSync)(pt,{recursive:!0});let t=bn(e.sessionID);(0,F.writeFileSync)(t,JSON.stringify(e,null,2))}function Pn(e){let t=bn(e);(0,F.existsSync)(t)&&(0,F.unlinkSync)(t)}function Ac(e){let t=e||process.cwd();return Ne(t)?.active?{active:!0,mode:"ascent"}:ge(t)?.active?{active:!0,mode:"olympus"}:ne(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function Nc(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function wc(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
|
|
738
739
|
|
|
739
740
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
740
741
|
|
|
@@ -760,25 +761,25 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
760
761
|
|
|
761
762
|
---
|
|
762
763
|
|
|
763
|
-
`}function
|
|
764
|
-
`;(0,Vs.appendFileSync)(js,t)}}function Ks(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 qs(e){let n=Ks(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Js(e){let t=Ks(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 Cc(e){return Js(e)!==null}function Pc(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Lc(e,t){x("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=K(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=Pc(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 Dc(e,t,n){x("recoverThinkingBlockOrder",{sessionID:e});let o=qs(n);if(o!==null){let i=Ws(e,o);if(i)return x("Found target message by index",{targetIndex:o,targetMessageID:i}),Un(e,i)}let r=Mn(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)Un(e,i)&&(s=!0);return s}async function Mc(e,t){x("recoverThinkingDisabledViolation",{sessionID:e});let n=Dn(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)Bs(r)&&(o=!0);return o}async function Uc(e,t,n){x("recoverEmptyContentMessage",{sessionID:e});let o=qs(n),r=t.info?.id,s=!1,i=Ys(e);for(let c of i)Me(c,H)&&(s=!0);let l=Gs(e);for(let c of l)De(e,c,H)&&(s=!0);if(o!==null){let c=Hs(e,o);if(c&&(Me(c,H)||De(e,c,H)))return!0}if(r&&(Me(r,H)||De(e,r,H)))return!0;let a=Ln(e);for(let c of a)Me(c,H)&&(s=!0),De(e,c,H)&&(s=!0);return s}async function jc(e,t,n,o){x("handleSessionRecovery",{sessionID:e,error:t});let r=Js(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 Lc(e,i);break;case"thinking_block_order":s=await Dc(e,i,t);break;case"thinking_disabled_violation":s=await Mc(e,i);break;case"empty_content":s=await Uc(e,i,t);break}x("Recovery result",{errorType:r,success:s});let l=o?.customMessages?.[r]||gt[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?l:void 0,errorType:r}}catch(s){return x("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function Xs(e){return x("createSessionRecoveryHook",{config:e}),{onError:async t=>jc(t.session_id,t.error,t.message,e),isRecoverable:t=>Cc(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||gt[t]?.message}}}function zs(){let e=Xs();T({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 G=require("fs"),ht=require("path"),Qs=require("os");var Ue=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 $c=1800*1e3,Oe=(0,ht.join)((0,Qs.homedir)(),".claude",".olympus","background-tasks"),Tt=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Ue(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,G.existsSync)(Oe)||(0,G.mkdirSync)(Oe,{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,ht.join)(Oe,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,G.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,G.existsSync)(n)&&(0,G.unlinkSync)(n)}loadPersistedTasks(){if((0,G.existsSync)(Oe))try{let{readdirSync:t}=require("fs"),n=t(Oe);for(let o of n)if(o.endsWith(".json"))try{let r=(0,ht.join)(Oe,o),s=(0,G.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??$c;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()}`,l={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,l),this.persistTask(l),l}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(),l=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${l}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
765
|
-
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},jn;function $n(e){return jn||(jn=new Tt(e)),jn}function
|
|
766
|
-
`)}function
|
|
764
|
+
`}function Ls(){let e=new Map,t=new Map;function n(a){if(!e.has(a)){let u=Cn(a)??{sessionID:a,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(a,u)}return e.get(a)}function o(a){let c=n(a);c.agentUsed=!0,c.updatedAt=Date.now(),ft(c)}function r(a){e.delete(a),Pn(a),t.delete(a)}function s(a,c,u){let d=t.get(a)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:a};return c.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(a,d),0):(["edit","write","multiedit"].includes(c.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=c,d.lastFilePath=u,t.set(a,d)),d.consecutiveCount)}return{"tool.execute.after":async(a,c)=>{let{tool:u,sessionID:d}=a,m=u.toLowerCase();if(vn.has(m)){o(d),s(d,m,"");return}let E=a.properties||{},k=Nc(E),y=s(d,m,k||""),O=Ac();if(O.active){let C=wc(y,O.mode);if(C){c.output=C+c.output;return}}if(!wn.has(m))return;let w=n(d);w.agentUsed||(c.output+=xn,w.reminderCount++,w.updatedAt=Date.now(),ft(w))},event:async({event:a})=>{let c=a.properties;if(a.type==="session.deleted"){let u=c?.info;u?.id&&r(u.id)}if(a.type==="session.compacted"){let u=c?.sessionID??c?.info?.id;u&&r(u)}}}}function Ds(){let e=process.cwd(),t=os();T({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async a=>{if(!a.toolName||!a.toolOutput)return{continue:!0};let c=t.afterToolExecute({tool:a.toolName,sessionId:a.sessionId||"",callId:""},{title:"",output:String(a.toolOutput),metadata:void 0});return c.output!==String(a.toolOutput)?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:c.output.substring(String(a.toolOutput).length)}}:{continue:!0}}});let n=cs();T({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async a=>{if(!a.toolName)return{continue:!0};let c=n.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return c?{continue:!0,message:c}:{continue:!0}}});let o=ks();T({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async a=>{if(!a.toolName)return{continue:!0};let c=o.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return c?{continue:!0,message:c}:{continue:!0}}});let r=ys();T({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async a=>{if(!a.toolName||a.toolName.toLowerCase()!=="read")return{continue:!0};let c=r.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return c?{continue:!0,message:c}:{continue:!0}}});let s=bs();T({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async a=>{if(!a.toolName)return{continue:!0};let c=s.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return c?{continue:!0,message:c}:{continue:!0}}});let i=Ls();T({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async a=>{if(!a.toolName)return{continue:!0};let c={title:"",output:a.toolOutput?String(a.toolOutput):"",metadata:void 0};await i["tool.execute.after"]({tool:a.toolName,sessionID:a.sessionId||"",callID:""},c);let u=a.toolOutput?String(a.toolOutput):"";return c.output!==u?{continue:!0,message:c.output.substring(u.length)}:{continue:!0}}});let l=ot(e);T({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async a=>{if(!a.toolName)return{continue:!0};let c=l.postTool(a.toolName,a.toolInput||{},a.toolOutput?String(a.toolOutput):"");return c.continue?c.modifiedOutput?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:c.modifiedOutput}}:c.message?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:c.message}}:{continue:!0}:{continue:!1,stopReason:c.message}}})}var Ks=require("node:fs");var h=require("node:fs"),D=require("node:path");var Se=require("node:path"),mt=require("node:os");function vc(){return process.env.XDG_DATA_HOME??(0,Se.join)((0,mt.homedir)(),".local","share")}function xc(){return(0,Se.join)(vc(),"claude-code","storage")}var Ms=xc(),Le=(0,Se.join)(Ms,"message"),ye=(0,Se.join)(Ms,"part"),te=new Set(["thinking","redacted_thinking","reasoning"]),Us=new Set(["step-start","step-finish"]);var H="[user interrupted]",gt={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 js=process.env.SESSION_RECOVERY_DEBUG==="1",$s=(0,Se.join)((0,mt.tmpdir)(),"session-recovery-debug.log");function bc(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function Cc(e){if(!(0,h.existsSync)(Le))return"";let t=(0,D.join)(Le,e);if((0,h.existsSync)(t))return t;for(let n of(0,h.readdirSync)(Le)){let o=(0,D.join)(Le,n,e);if((0,h.existsSync)(o))return o}return""}function z(e){let t=Cc(e);if(!t||!(0,h.existsSync)(t))return[];let n=[];for(let o of(0,h.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,h.readFileSync)((0,D.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n.sort((o,r)=>{let s=o.time?.created??0,i=r.time?.created??0;return s!==i?s-i:o.id.localeCompare(r.id)})}function K(e){let t=(0,D.join)(ye,e);if(!(0,h.existsSync)(t))return[];let n=[];for(let o of(0,h.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,h.readFileSync)((0,D.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Fs(e){return te.has(e.type)||Us.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Hs(e){return K(e).some(Fs)}function De(e,t,n){let o=(0,D.join)(ye,t);(0,h.existsSync)(o)||(0,h.mkdirSync)(o,{recursive:!0});let r=bc(),s={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,h.writeFileSync)((0,D.join)(o,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Ln(e){let t=z(e),n=[];for(let o of t)Hs(o.id)||n.push(o.id);return n}function Gs(e,t){let n=z(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 s=n[r];if(!Hs(s.id))return s.id}return null}function Dn(e){let t=z(e),n=[];for(let o of t){if(o.role!=="assistant")continue;K(o.id).some(i=>te.has(i.type))&&n.push(o.id)}return n}function Bs(e){let t=z(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=K(o.id);if(r.length===0)continue;let s=r.some(l=>te.has(l.type)),i=r.some(Fs);s&&!i&&n.push(o.id)}return n}function Mn(e){let t=z(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=K(o.id);if(r.length===0)continue;let i=[...r].sort((a,c)=>a.id.localeCompare(c.id))[0];te.has(i.type)||n.push(o.id)}return n}function Pc(e,t){let n=z(e),o=n.findIndex(r=>r.id===t);if(o===-1)return"";for(let r=o-1;r>=0;r--){let s=n[r];if(s.role!=="assistant")continue;let i=K(s.id);for(let l of i)if(te.has(l.type)){let a=l.thinking,c=l.text,u=a||c;if(u&&u.trim().length>0)return u}}return""}function Un(e,t){let n=(0,D.join)(ye,t);(0,h.existsSync)(n)||(0,h.mkdirSync)(n,{recursive:!0});let o=Pc(e,t),r="prt_0000000000_thinking",s={id:r,sessionID:e,messageID:t,type:"thinking",thinking:o||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,h.writeFileSync)((0,D.join)(n,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Ys(e){let t=(0,D.join)(ye,e);if(!(0,h.existsSync)(t))return!1;let n=!1;for(let o of(0,h.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,D.join)(t,o),s=(0,h.readFileSync)(r,"utf-8"),i=JSON.parse(s);te.has(i.type)&&((0,h.unlinkSync)(r),n=!0)}catch{continue}return n}function Me(e,t=H){let n=(0,D.join)(ye,e);if(!(0,h.existsSync)(n))return!1;let o=!1;for(let r of(0,h.readdirSync)(n))if(r.endsWith(".json"))try{let s=(0,D.join)(n,r),i=(0,h.readFileSync)(s,"utf-8"),l=JSON.parse(i);if(l.type==="text"){let a=l;a.text?.trim()||(a.text=t,a.synthetic=!0,(0,h.writeFileSync)(s,JSON.stringify(a,null,2)),o=!0)}}catch{continue}return o}function Ws(e){let t=z(e),n=[];for(let o of t)K(o.id).some(i=>i.type!=="text"?!1:!i.text?.trim())&&n.push(o.id);return n}function Vs(e,t){let n=z(e);if(t<0||t>=n.length)return null;let o=n[t];if(o.role!=="assistant")return null;let r=K(o.id);if(r.length===0)return null;let i=[...r].sort((a,c)=>a.id.localeCompare(c.id))[0];return te.has(i.type)?null:o.id}function b(...e){if(js){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
765
|
+
`;(0,Ks.appendFileSync)($s,t)}}function qs(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 Js(e){let n=qs(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Xs(e){let t=qs(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 Lc(e){return Xs(e)!==null}function Dc(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Mc(e,t){b("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=K(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=Dc(n);return o.length===0?(b("No tool_use IDs found"),!1):(b("Found tool_use IDs to inject results for",o),!0)}async function Uc(e,t,n){b("recoverThinkingBlockOrder",{sessionID:e});let o=Js(n);if(o!==null){let i=Vs(e,o);if(i)return b("Found target message by index",{targetIndex:o,targetMessageID:i}),Un(e,i)}let r=Mn(e);if(r.length===0)return b("No orphan thinking messages found"),!1;b("Found orphan thinking messages",r);let s=!1;for(let i of r)Un(e,i)&&(s=!0);return s}async function jc(e,t){b("recoverThinkingDisabledViolation",{sessionID:e});let n=Dn(e);if(n.length===0)return b("No messages with thinking blocks found"),!1;b("Found messages with thinking blocks",n);let o=!1;for(let r of n)Ys(r)&&(o=!0);return o}async function $c(e,t,n){b("recoverEmptyContentMessage",{sessionID:e});let o=Js(n),r=t.info?.id,s=!1,i=Ws(e);for(let c of i)Me(c,H)&&(s=!0);let l=Bs(e);for(let c of l)De(e,c,H)&&(s=!0);if(o!==null){let c=Gs(e,o);if(c&&(Me(c,H)||De(e,c,H)))return!0}if(r&&(Me(r,H)||De(e,r,H)))return!0;let a=Ln(e);for(let c of a)Me(c,H)&&(s=!0),De(e,c,H)&&(s=!0);return s}async function Fc(e,t,n,o){b("handleSessionRecovery",{sessionID:e,error:t});let r=Xs(t);if(!r)return b("Not a recoverable error"),{attempted:!1,success:!1};b("Detected recoverable error type",r);try{let s=!1,i=n||{info:{},parts:[]};switch(r){case"tool_result_missing":s=await Mc(e,i);break;case"thinking_block_order":s=await Uc(e,i,t);break;case"thinking_disabled_violation":s=await jc(e,i);break;case"empty_content":s=await $c(e,i,t);break}b("Recovery result",{errorType:r,success:s});let l=o?.customMessages?.[r]||gt[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?l:void 0,errorType:r}}catch(s){return b("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function zs(e){return b("createSessionRecoveryHook",{config:e}),{onError:async t=>Fc(t.session_id,t.error,t.message,e),isRecoverable:t=>Lc(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||gt[t]?.message}}}function Qs(){let e=zs();T({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 G=require("fs"),ht=require("path"),Zs=require("os");var Ue=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 Hc=1800*1e3,Oe=(0,ht.join)((0,Zs.homedir)(),".claude",".olympus","background-tasks"),Tt=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Ue(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,G.existsSync)(Oe)||(0,G.mkdirSync)(Oe,{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,ht.join)(Oe,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,G.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,G.existsSync)(n)&&(0,G.unlinkSync)(n)}loadPersistedTasks(){if((0,G.existsSync)(Oe))try{let{readdirSync:t}=require("fs"),n=t(Oe);for(let o of n)if(o.endsWith(".json"))try{let r=(0,ht.join)(Oe,o),s=(0,G.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??Hc;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()}`,l={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,l),this.persistTask(l),l}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(),l=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${l}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
766
|
+
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},jn;function $n(e){return jn||(jn=new Tt(e)),jn}function Gc(e){let t=e.status.toUpperCase(),n=Bc(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 s=e.result.substring(0,200),i=e.result.length>200?"...":"";r.push(` Result: ${s}${i}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
|
|
767
|
+
`)}function Bc(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),s=Math.floor(r/60);return s>0?`${s}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function Yc(e){if(e.length===0)return"";let t=e.length===1?`
|
|
767
768
|
[BACKGROUND TASK COMPLETED]
|
|
768
769
|
`:`
|
|
769
770
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
770
|
-
`,n=e.map(o=>
|
|
771
|
+
`,n=e.map(o=>Gc(o)).join(`
|
|
771
772
|
|
|
772
773
|
`);return`${t}
|
|
773
774
|
${n}
|
|
774
|
-
`}function
|
|
775
|
-
`;break;case 114:p+="\r";break;case 116:p+=" ";break;case 117:let f=m(4,!0);f>=0?p+=String.fromCharCode(f):d=4;break;default:d=5}
|
|
776
|
-
`),l++,c=o,i=14;switch(p){case 123:return o++,i=1;case 125:return o++,i=2;case 91:return o++,i=3;case 93:return o++,i=4;case 58:return o++,i=6;case 44:return o++,i=5;case 34:return o++,r=y(),i=10;case 47:let
|
|
777
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
778
|
-
`+" ".repeat(t))}," ":{"\n":new Array(
|
|
779
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
780
|
-
`+" ".repeat(t))}};var kt;(function(e){e.DEFAULT={allowTrailingComma:!1}})(kt||(kt={}));function
|
|
775
|
+
`}function Wc(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let s=(n?.formatNotification??Yc)(o);return{hasNotifications:!0,tasks:o,message:s}}function ei(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=$n(),r=Wc(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function ti(){T({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 ei(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var ni=!1;function oi(){ni||($o(),Ko(),fr(),ns(),Ds(),Qs(),ti(),ni=!0)}var yt=require("fs"),pi=require("os"),$e=require("path");function Et(e,t=!1){let n=e.length,o=0,r="",s=0,i=16,l=0,a=0,c=0,u=0,d=0;function m(p,N){let v=0,S=0;for(;v<p||!N;){let f=e.charCodeAt(o);if(f>=48&&f<=57)S=S*16+f-48;else if(f>=65&&f<=70)S=S*16+f-65+10;else if(f>=97&&f<=102)S=S*16+f-97+10;else break;o++,v++}return v<p&&(S=-1),S}function E(p){o=p,r="",s=0,i=16,d=0}function k(){let p=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&Re(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&Re(e.charCodeAt(o)))for(o++;o<e.length&&Re(e.charCodeAt(o));)o++;else return d=3,e.substring(p,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&&Re(e.charCodeAt(o))){for(o++;o<e.length&&Re(e.charCodeAt(o));)o++;N=o}else d=3;return e.substring(p,N)}function y(){let p="",N=o;for(;;){if(o>=n){p+=e.substring(N,o),d=2;break}let v=e.charCodeAt(o);if(v===34){p+=e.substring(N,o),o++;break}if(v===92){if(p+=e.substring(N,o),o++,o>=n){d=2;break}switch(e.charCodeAt(o++)){case 34:p+='"';break;case 92:p+="\\";break;case 47:p+="/";break;case 98:p+="\b";break;case 102:p+="\f";break;case 110:p+=`
|
|
776
|
+
`;break;case 114:p+="\r";break;case 116:p+=" ";break;case 117:let f=m(4,!0);f>=0?p+=String.fromCharCode(f):d=4;break;default:d=5}N=o;continue}if(v>=0&&v<=31)if(je(v)){p+=e.substring(N,o),d=2;break}else d=6;o++}return p}function O(){if(r="",d=0,s=o,a=l,u=c,o>=n)return s=n,i=17;let p=e.charCodeAt(o);if(Fn(p)){do o++,r+=String.fromCharCode(p),p=e.charCodeAt(o);while(Fn(p));return i=15}if(je(p))return o++,r+=String.fromCharCode(p),p===13&&e.charCodeAt(o)===10&&(o++,r+=`
|
|
777
|
+
`),l++,c=o,i=14;switch(p){case 123:return o++,i=1;case 125:return o++,i=2;case 91:return o++,i=3;case 93:return o++,i=4;case 58:return o++,i=6;case 44:return o++,i=5;case 34:return o++,r=y(),i=10;case 47:let N=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!je(e.charCodeAt(o));)o++;return r=e.substring(N,o),i=12}if(e.charCodeAt(o+1)===42){o+=2;let v=n-1,S=!1;for(;o<v;){let f=e.charCodeAt(o);if(f===42&&e.charCodeAt(o+1)===47){o+=2,S=!0;break}o++,je(f)&&(f===13&&e.charCodeAt(o)===10&&o++,l++,c=o)}return S||(o++,d=1),r=e.substring(N,o),i=13}return r+=String.fromCharCode(p),o++,i=16;case 45:if(r+=String.fromCharCode(p),o++,o===n||!Re(e.charCodeAt(o)))return i=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=k(),i=11;default:for(;o<n&&w(p);)o++,p=e.charCodeAt(o);if(s!==o){switch(r=e.substring(s,o),r){case"true":return i=8;case"false":return i=9;case"null":return i=7}return i=16}return r+=String.fromCharCode(p),o++,i=16}}function w(p){if(Fn(p)||je(p))return!1;switch(p){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function C(){let p;do p=O();while(p>=12&&p<=15);return p}return{setPosition:E,getPosition:()=>o,scan:t?C:O,getToken:()=>i,getTokenValue:()=>r,getTokenOffset:()=>s,getTokenLength:()=>o-s,getTokenStartLine:()=>a,getTokenStartCharacter:()=>s-u,getTokenError:()=>d}}function Fn(e){return e===32||e===9}function je(e){return e===10||e===13}function Re(e){return e>=48&&e<=57}var ri;(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"})(ri||(ri={}));var Kc=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),Ie=200,qc={" ":{"\n":new Array(Ie).fill(0).map((e,t)=>`
|
|
778
|
+
`+" ".repeat(t)),"\r":new Array(Ie).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Ie).fill(0).map((e,t)=>`\r
|
|
779
|
+
`+" ".repeat(t))}," ":{"\n":new Array(Ie).fill(0).map((e,t)=>`
|
|
780
|
+
`+" ".repeat(t)),"\r":new Array(Ie).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Ie).fill(0).map((e,t)=>`\r
|
|
781
|
+
`+" ".repeat(t))}};var kt;(function(e){e.DEFAULT={allowTrailingComma:!1}})(kt||(kt={}));function si(e,t=[],n=kt.DEFAULT){let o=null,r=[],s=[];function i(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return ii(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,c,u)=>{t.push({error:a,offset:c,length:u})}},n),r[0]}function ii(e,t,n=kt.DEFAULT){let o=Et(e,!1),r=[],s=0;function i(g){return g?()=>s===0&&g(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function l(g){return g?R=>s===0&&g(R,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(g){return g?R=>s===0&&g(R,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function c(g){return g?()=>{s>0?s++:g(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(s=1)}:()=>!0}function u(g){return g?()=>{s>0&&s--,s===0&&g(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=c(t.onObjectBegin),m=a(t.onObjectProperty),E=u(t.onObjectEnd),k=c(t.onArrayBegin),y=u(t.onArrayEnd),O=a(t.onLiteralValue),w=l(t.onSeparator),C=i(t.onComment),p=l(t.onError),N=n&&n.disallowComments,v=n&&n.allowTrailingComma;function S(){for(;;){let g=o.scan();switch(o.getTokenError()){case 4:f(14);break;case 5:f(15);break;case 3:f(13);break;case 1:N||f(11);break;case 2:f(12);break;case 6:f(16);break}switch(g){case 12:case 13:N?f(10):C();break;case 16:f(1);break;case 15:case 14:break;default:return g}}}function f(g,R=[],Gn=[]){if(p(g),R.length+Gn.length>0){let Fe=o.getToken();for(;Fe!==17;){if(R.indexOf(Fe)!==-1){S();break}else if(Gn.indexOf(Fe)!==-1)break;Fe=S()}}}function Hn(g){let R=o.getTokenValue();return g?O(R):(m(R),r.push(R)),S(),!0}function hi(){switch(o.getToken()){case 11:let g=o.getTokenValue(),R=Number(g);isNaN(R)&&(f(2),R=0),O(R);break;case 7:O(null);break;case 8:O(!0);break;case 9:O(!1);break;default:return!1}return S(),!0}function Ti(){return o.getToken()!==10?(f(3,[],[2,5]),!1):(Hn(!1),o.getToken()===6?(w(":"),S(),Rt()||f(4,[],[2,5])):f(5,[],[2,5]),r.pop(),!0)}function Ei(){d(),S();let g=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(g||f(4,[],[]),w(","),S(),o.getToken()===2&&v)break}else g&&f(6,[],[]);Ti()||f(4,[],[2,5]),g=!0}return E(),o.getToken()!==2?f(7,[2],[]):S(),!0}function ki(){k(),S();let g=!0,R=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(R||f(4,[],[]),w(","),S(),o.getToken()===4&&v)break}else R&&f(6,[],[]);g?(r.push(0),g=!1):r[r.length-1]++,Rt()||f(4,[],[4,5]),R=!0}return y(),g||r.pop(),o.getToken()!==4?f(8,[4],[]):S(),!0}function Rt(){switch(o.getToken()){case 3:return ki();case 1:return Ei();case 10:return Hn(!0);default:return hi()}}return S(),o.getToken()===17?n.allowEmptyContent?!0:(f(4,[],[]),!1):Rt()?(o.getToken()!==17&&f(9,[],[]),!0):(f(4,[],[]),!1)}var ai;(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"})(ai||(ai={}));var ci;(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"})(ci||(ci={}));var ui=si;var li;(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"})(li||(li={}));var nl={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"]}};function ol(){let e=process.env.XDG_CONFIG_HOME??(0,$e.join)((0,pi.homedir)(),".config");return{user:(0,$e.join)(e,"claude-olympus","config.jsonc"),project:(0,$e.join)(process.cwd(),".claude","olympus.jsonc")}}function di(e){if(!(0,yt.existsSync)(e))return null;try{let t=(0,yt.readFileSync)(e,"utf-8"),n=[],o=ui(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 St(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]=St(s,r):r!==void 0&&(n[o]=r)}return n}function rl(){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})}return process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),e}function fi(){let e=ol(),t={...nl},n=di(e.user);n&&(t=St(t,n));let o=di(e.project);o&&(t=St(t,o));let r=rl();return t=St(t,r),t}function sl(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function il(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 al(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function cl(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function mi(e,t){let n=fi(),o=Yn(e),r=sl(n),s=!0,i=[],l,a=t.toolInput,c=t.messages;for(let u of o)if(il(n,u.name)&&cl(u.matcher,t.toolName))try{let d=await al(()=>u.handler({...t,toolInput:a,messages:c}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(s=!1,l=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&&(c=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:s,message:i.length>0?i.join(`
|
|
781
782
|
|
|
782
783
|
---
|
|
783
784
|
|
|
784
|
-
`):void 0,stopReason:l,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:c!==t.messages?c:void 0}}
|
|
785
|
+
`):void 0,stopReason:l,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:c!==t.messages?c:void 0}}oi();async function ll(){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 gi(){let t=process.argv.slice(2).find(i=>i.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],o=await ll(),r;try{r=JSON.parse(o)}catch{r={}}let s=await mi(n,r);console.log(JSON.stringify(s)),process.exit(0)}var Ot=process.argv[1]||"",ul=Ot.endsWith("entry.ts")||Ot.endsWith("entry.js")||Ot.endsWith("olympus-hooks.mjs")||Ot.includes("olympus-hooks");ul&&gi().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|