olympus-ai 3.3.0 → 3.4.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-plugin/marketplace.json +1 -1
- package/README.md +2 -0
- package/dist/__tests__/learning/aggregation.test.d.ts +2 -0
- package/dist/__tests__/learning/aggregation.test.d.ts.map +1 -0
- package/dist/__tests__/learning/aggregation.test.js +282 -0
- package/dist/__tests__/learning/aggregation.test.js.map +1 -0
- package/dist/__tests__/learning/anomaly.test.d.ts +2 -0
- package/dist/__tests__/learning/anomaly.test.d.ts.map +1 -0
- package/dist/__tests__/learning/anomaly.test.js +107 -0
- package/dist/__tests__/learning/anomaly.test.js.map +1 -0
- package/dist/__tests__/learning/baselines.test.d.ts +2 -0
- package/dist/__tests__/learning/baselines.test.d.ts.map +1 -0
- package/dist/__tests__/learning/baselines.test.js +155 -0
- package/dist/__tests__/learning/baselines.test.js.map +1 -0
- package/dist/__tests__/learning/efficiency.test.d.ts +2 -0
- package/dist/__tests__/learning/efficiency.test.d.ts.map +1 -0
- package/dist/__tests__/learning/efficiency.test.js +94 -0
- package/dist/__tests__/learning/efficiency.test.js.map +1 -0
- package/dist/__tests__/learning/feedback-loop-injection.test.d.ts +6 -0
- package/dist/__tests__/learning/feedback-loop-injection.test.d.ts.map +1 -0
- package/dist/__tests__/learning/feedback-loop-injection.test.js +288 -0
- package/dist/__tests__/learning/feedback-loop-injection.test.js.map +1 -0
- package/dist/__tests__/learning/learning-capture-integration.test.d.ts +6 -0
- package/dist/__tests__/learning/learning-capture-integration.test.d.ts.map +1 -0
- package/dist/__tests__/learning/learning-capture-integration.test.js +151 -0
- package/dist/__tests__/learning/learning-capture-integration.test.js.map +1 -0
- package/dist/__tests__/learning/token-metrics.test.d.ts +2 -0
- package/dist/__tests__/learning/token-metrics.test.d.ts.map +1 -0
- package/dist/__tests__/learning/token-metrics.test.js +308 -0
- package/dist/__tests__/learning/token-metrics.test.js.map +1 -0
- package/dist/__tests__/token-tracking-integration.test.d.ts +8 -0
- package/dist/__tests__/token-tracking-integration.test.d.ts.map +1 -0
- package/dist/__tests__/token-tracking-integration.test.js +669 -0
- package/dist/__tests__/token-tracking-integration.test.js.map +1 -0
- package/dist/cli/commands/metrics.d.ts +10 -2
- package/dist/cli/commands/metrics.d.ts.map +1 -1
- package/dist/cli/commands/metrics.js +25 -239
- package/dist/cli/commands/metrics.js.map +1 -1
- package/dist/cli/index.js +196 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +14 -0
- package/dist/config/loader.js.map +1 -1
- package/dist/hooks/registrations/budget-warning.d.ts +8 -0
- package/dist/hooks/registrations/budget-warning.d.ts.map +1 -0
- package/dist/hooks/registrations/budget-warning.js +63 -0
- package/dist/hooks/registrations/budget-warning.js.map +1 -0
- package/dist/hooks/registrations/index.d.ts +3 -2
- package/dist/hooks/registrations/index.d.ts.map +1 -1
- package/dist/hooks/registrations/index.js +5 -3
- package/dist/hooks/registrations/index.js.map +1 -1
- package/dist/hooks/registrations/learning-capture.d.ts +19 -0
- package/dist/hooks/registrations/learning-capture.d.ts.map +1 -0
- package/dist/hooks/registrations/learning-capture.js +220 -0
- package/dist/hooks/registrations/learning-capture.js.map +1 -0
- package/dist/hooks/registrations/session-start.d.ts.map +1 -1
- package/dist/hooks/registrations/session-start.js +13 -0
- package/dist/hooks/registrations/session-start.js.map +1 -1
- package/dist/hooks/registrations/token-metrics.d.ts +10 -2
- package/dist/hooks/registrations/token-metrics.d.ts.map +1 -1
- package/dist/hooks/registrations/token-metrics.js +18 -4
- package/dist/hooks/registrations/token-metrics.js.map +1 -1
- package/dist/installer/index.d.ts +1 -1
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +56 -0
- package/dist/installer/index.js.map +1 -1
- package/dist/learning/aggregation.d.ts +39 -0
- package/dist/learning/aggregation.d.ts.map +1 -0
- package/dist/learning/aggregation.js +101 -0
- package/dist/learning/aggregation.js.map +1 -0
- package/dist/learning/anomaly.d.ts +30 -0
- package/dist/learning/anomaly.d.ts.map +1 -0
- package/dist/learning/anomaly.js +102 -0
- package/dist/learning/anomaly.js.map +1 -0
- package/dist/learning/baselines.d.ts +44 -0
- package/dist/learning/baselines.d.ts.map +1 -0
- package/dist/learning/baselines.js +126 -0
- package/dist/learning/baselines.js.map +1 -0
- package/dist/learning/efficiency.d.ts +23 -0
- package/dist/learning/efficiency.d.ts.map +1 -0
- package/dist/learning/efficiency.js +67 -0
- package/dist/learning/efficiency.js.map +1 -0
- package/dist/learning/hooks/learned-context.d.ts.map +1 -1
- package/dist/learning/hooks/learned-context.js +46 -0
- package/dist/learning/hooks/learned-context.js.map +1 -1
- package/dist/learning/pricing.d.ts +30 -0
- package/dist/learning/pricing.d.ts.map +1 -0
- package/dist/learning/pricing.js +98 -0
- package/dist/learning/pricing.js.map +1 -0
- package/dist/learning/session-state.d.ts +12 -2
- package/dist/learning/session-state.d.ts.map +1 -1
- package/dist/learning/session-state.js +72 -3
- package/dist/learning/session-state.js.map +1 -1
- package/dist/learning/storage.d.ts +21 -1
- package/dist/learning/storage.d.ts.map +1 -1
- package/dist/learning/storage.js +84 -0
- package/dist/learning/storage.js.map +1 -1
- package/dist/learning/token-estimator.d.ts +41 -0
- package/dist/learning/token-estimator.d.ts.map +1 -0
- package/dist/learning/token-estimator.js +111 -0
- package/dist/learning/token-estimator.js.map +1 -0
- package/dist/learning/types.d.ts +32 -0
- package/dist/learning/types.d.ts.map +1 -1
- package/dist/learning/utils.d.ts +42 -0
- package/dist/learning/utils.d.ts.map +1 -0
- package/dist/learning/utils.js +76 -0
- package/dist/learning/utils.js.map +1 -0
- package/dist/shared/types.d.ts +29 -0
- package/dist/shared/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/scripts/dist/hooks/olympus-hooks.cjs +86 -84
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
`)){let c=i.indexOf(":");if(c===-1)continue;let a=i.slice(0,c).trim(),l=i.slice(c+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[a]=l}return{data:s,body:r}}function
|
|
3
|
+
"use strict";var Wi=Object.create;var Je=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var qi=Object.getPrototypeOf,Ji=Object.prototype.hasOwnProperty;var Xi=(e,t)=>{for(var n in t)Je(e,n,{get:t[n],enumerable:!0})},to=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ki(t))!Ji.call(e,r)&&r!==n&&Je(e,r,{get:()=>t[r],enumerable:!(o=Vi(t,r))||o.enumerable});return e};var ae=(e,t,n)=>(n=e!=null?Wi(qi(e)):{},to(t||!e||!e.__esModule?Je(n,"default",{value:e,enumerable:!0}):n,e)),zi=e=>to(Je({},"__esModule",{value:!0}),e);var Bl={};Xi(Bl,{main:()=>Hi});module.exports=zi(Bl);var xt=new Map;function g(e){let t=xt.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),xt.set(e.event,t)}function no(e){return xt.get(e)||[]}var Qi={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},Zi=["ultrawork","ultrathink","olympus","search","analyze"];function oo(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function ro(e,t){let n=[];for(let o of Zi){let r=Qi[o],s=e.match(r);s&&s.index!==void 0&&n.push({type:o,keyword:s[0],position:s.index})}return n}var so="auto-slash-command",Xe="<auto-slash-command>",ze="</auto-slash-command>",io=/^\/([a-zA-Z][\w-]*)\s*(.*)/,ao=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var ea=/```[\s\S]*?```/g;function co(e){return e.replace(ea,"")}function lo(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(io);if(!n)return null;let[o,r,s]=n;return{command:r.toLowerCase(),args:s.trim(),raw:o}}function uo(e){return ao.has(e.toLowerCase())}function Pt(e){let n=co(e).trim();if(!n.startsWith("/"))return null;let o=lo(n);return!o||uo(o.command)?null:o}function Lt(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var K=require("fs"),X=require("path"),mo=require("os"),po=(0,X.join)((0,mo.homedir)(),".claude");function go(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 c=i.indexOf(":");if(c===-1)continue;let a=i.slice(0,c).trim(),l=i.slice(c+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[a]=l}return{data:s,body:r}}function fo(e,t){if(!(0,K.existsSync)(e))return[];let n;try{n=(0,K.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let s=(0,X.join)(e,r.name),i=(0,X.basename)(r.name,".md");try{let c=(0,K.readFileSync)(s,"utf-8"),{data:a,body:l}=go(c),u={name:i,description:a.description||"",argumentHint:a["argument-hint"],model:a.model,agent:a.agent};o.push({name:i,path:s,metadata:u,content:l,scope:t})}catch{continue}}return o}function Dt(){let e=(0,X.join)(po,"commands"),t=(0,X.join)(process.cwd(),".claude","commands"),n=(0,X.join)(po,"skills"),o=fo(e,"user"),r=fo(t,"project"),s=[];if((0,K.existsSync)(n))try{let i=(0,K.readdirSync)(n,{withFileTypes:!0});for(let c of i){if(!c.isDirectory())continue;let a=(0,X.join)(n,c.name,"SKILL.md");if((0,K.existsSync)(a))try{let l=(0,K.readFileSync)(a,"utf-8"),{data:u,body:d}=go(l),f={name:u.name||c.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||c.name,path:a,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...s]}function Qe(e){return Dt().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function ta(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function na(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
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=ta(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
|
|
16
|
+
`)}function Mt(e){let t=Qe(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:na(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function Ut(){return Dt().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var Ze=new Set;function ho(){return{name:so,processMessage:(e,t)=>{let n=Lt(t);if(n.includes(Xe)||n.includes(ze))return{detected:!1};let o=Pt(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(Ze.has(r))return{detected:!1};Ze.add(r);let s=Mt(o);if(s.success&&s.replacementText){let c=`${Xe}
|
|
17
17
|
${s.replacementText}
|
|
18
|
-
${
|
|
18
|
+
${ze}`;return{detected:!0,parsedCommand:o,injectedMessage:c}}let i=`${Xe}
|
|
19
19
|
[AUTO-SLASH-COMMAND ERROR]
|
|
20
20
|
${s.error}
|
|
21
21
|
|
|
22
22
|
Original input: ${o.raw}
|
|
23
|
-
${
|
|
23
|
+
${ze}`;return{detected:!0,parsedCommand:o,injectedMessage:i}},listCommands:()=>Ut(),findCommand:e=>Qe(e),clearSession:e=>{let t=[];for(let n of Ze)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)Ze.delete(n)}}}var oa=[/\bultrathink\b/i,/\bthink\b/i],ra=["\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"],sa=ra.map(e=>new RegExp(e,"i")),ia=[...oa,...sa],aa=/```[\s\S]*?```/g,ca=/`[^`]+`/g;function la(e){return e.replace(aa,"").replace(ca,"")}function To(e){let t=la(e);return ia.some(n=>n.test(t))}function ko(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function jt(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function Ft(e){return e.replace(/\.(\d+)/g,"-$1")}var Eo={"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"},yo=new Set(Object.values(Eo)),So={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"}},ua={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 Oo(e){let t=Ft(e),{prefix:n,base:o}=jt(t);if(yo.has(o)||o.endsWith("-high"))return null;let r=Eo[o];return r?n+r:null}function $t(e){let t=Ft(e),{base:n}=jt(t);return yo.has(n)||n.endsWith("-high")}function da(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 pa(e){return e in So}function _o(e,t){let n=Ft(t),{base:o}=jt(n);if($t(n))return null;let r=da(e,t);if(!pa(r))return null;let s=So[r],i=ua[r];if(!i)return null;let c=o.toLowerCase();return i.some(l=>c.includes(l.toLowerCase()))?s:null}var ee=new Map;function fa(e){ee.delete(e)}function Ro(){return{processChatParams:(e,t)=>{let n=ko(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!To(n))return ee.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,$t(r.modelId)))return ee.set(e,o),o;let s=Oo(r.modelId),i=_o(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),ee.set(e,o),o},onSessionDeleted:e=>{ee.delete(e)},isRequested:e=>ee.get(e)?.requested??!1,getState:e=>ee.get(e),clear:fa}}var w=require("fs"),he=require("path"),Ht=require("os");function Gt(e){let t=e||process.cwd(),n=(0,he.join)(t,".olympus");return(0,he.join)(n,"ultrawork-state.json")}function Bt(){return(0,he.join)((0,Ht.homedir)(),".claude","ultrawork-state.json")}function ma(e){let t=e||process.cwd(),n=(0,he.join)(t,".olympus");(0,w.existsSync)(n)||(0,w.mkdirSync)(n,{recursive:!0})}function ga(){let e=(0,he.join)((0,Ht.homedir)(),".claude");(0,w.existsSync)(e)||(0,w.mkdirSync)(e,{recursive:!0})}function ce(e){let t=Gt(e);if((0,w.existsSync)(t))try{let o=(0,w.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Bt();if((0,w.existsSync)(n))try{let o=(0,w.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Io(e,t){try{ma(t);let n=Gt(t);(0,w.writeFileSync)(n,JSON.stringify(e,null,2)),ga();let o=Bt();return(0,w.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Ao(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 Io(o,n)}function bo(e){let t=Gt(e);if((0,w.existsSync)(t))try{(0,w.unlinkSync)(t)}catch{}let n=Bt();if((0,w.existsSync)(n))try{return(0,w.unlinkSync)(n),!0}catch{return!1}return!0}function wo(e){let t=ce(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Io(t,e)?t:null)}function vo(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 No=require("os"),
|
|
44
|
+
`}var No=require("os"),C=require("path");function q(){return process.platform==="win32"}function ha(){return(0,C.join)((0,No.homedir)(),".claude")}function L(){return(0,C.join)(ha(),"hooks")}var Co=`<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
|
|
|
@@ -132,7 +132,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
|
|
|
132
132
|
|
|
133
133
|
---
|
|
134
134
|
|
|
135
|
-
`,
|
|
135
|
+
`,xo=`<think-mode>
|
|
136
136
|
|
|
137
137
|
**ULTRATHINK MODE ENABLED** - Extended reasoning activated.
|
|
138
138
|
|
|
@@ -148,7 +148,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
|
|
|
148
148
|
|
|
149
149
|
---
|
|
150
150
|
|
|
151
|
-
`;var
|
|
151
|
+
`;var Po=`<search-mode>
|
|
152
152
|
MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
|
|
153
153
|
- explore agents (codebase patterns, file structures)
|
|
154
154
|
- librarian agents (remote repos, official docs, GitHub examples)
|
|
@@ -158,7 +158,7 @@ NEVER stop at first result - be exhaustive.
|
|
|
158
158
|
|
|
159
159
|
---
|
|
160
160
|
|
|
161
|
-
`,
|
|
161
|
+
`,Lo=`<analyze-mode>
|
|
162
162
|
ANALYSIS MODE. Gather context before diving deep:
|
|
163
163
|
|
|
164
164
|
CONTEXT GATHERING (parallel):
|
|
@@ -174,15 +174,16 @@ SYNTHESIZE findings before proceeding.
|
|
|
174
174
|
|
|
175
175
|
---
|
|
176
176
|
|
|
177
|
-
`,
|
|
177
|
+
`,Do=`[SYSTEM REMINDER - TODO CONTINUATION]
|
|
178
178
|
|
|
179
179
|
Incomplete tasks remain in your todo list. Continue working on the next pending task.
|
|
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
|
-
`).filter(r=>r.trim()).length;if(o>=t){let r=new Date().toISOString().replace(/[:.]/g,"-"),s=e.replace(".jsonl",`.${r}.old.jsonl`);(0,
|
|
185
|
-
`,"utf-8")}function
|
|
183
|
+
- Do not stop until all tasks are done`;var hu={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:q()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:q()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:q()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},Tu={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:q()?`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:q()?`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:q()?`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:q()?`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:q()?`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:q()?`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:q()?`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,C.join)(L(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};var Bo=require("path");var Mo=require("os"),te=require("path"),A=require("fs"),Ta=require("crypto");function Yt(e){if(!e.token_usage)return null;let{token_usage:t}=e;return typeof t.input_tokens!="number"||typeof t.output_tokens!="number"||typeof t.total_tokens!="number"||typeof t.estimated!="boolean"?null:t}function Te(e){return Yt(e)?.total_tokens||0}var ka=1e4;function ne(){return(0,te.join)((0,Mo.homedir)(),".claude","olympus","learning")}function Ce(e){return(0,te.join)(e,".olympus","learning")}function Uo(e){let t=ne();if((0,A.existsSync)(t)||(0,A.mkdirSync)(t,{recursive:!0}),e){let n=Ce(e);(0,A.existsSync)(n)||(0,A.mkdirSync)(n,{recursive:!0})}}function jo(e,t=ka){if((0,A.existsSync)(e))try{let o=(0,A.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,A.renameSync)(e,s),console.log(`[Olympus Learning] Archived ${o} entries to ${s}`)}}catch(n){console.error(`[Olympus Learning] Failed to rotate ${e}:`,n)}}function oe(e){Uo();let t=(0,te.join)(ne(),"feedback-log.jsonl");jo(t),(0,A.appendFileSync)(t,JSON.stringify(e)+`
|
|
185
|
+
`,"utf-8")}function Ea(){let e=(0,te.join)(ne(),"feedback-log.jsonl");return(0,A.existsSync)(e)?(0,A.readFileSync)(e,"utf-8").split(`
|
|
186
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n)):[]}function Fo(){return Ea()}function $o(e,t){let n=t.filter(u=>u.agent_used===e);if(n.length===0)return null;let o=n.length,r=n.filter(u=>u.event_type==="success").length,s=n.filter(u=>u.event_type==="revision").length,i=n.filter(u=>u.event_type==="cancellation").length,c=o>0?r/o:0,a,l=n.filter(u=>Yt(u)!==null);if(l.length>0){let u=l.filter(h=>h.event_type==="success"),d=l.filter(h=>h.event_type==="revision"||h.event_type==="cancellation"),f=l.reduce((h,_)=>h+Te(_),0),E=u.reduce((h,_)=>h+Te(_),0),S=d.reduce((h,_)=>h+Te(_),0),O=u.length>0?E/u.length:0,R=d.length>0?S/d.length:0;if(a={avg_tokens_per_success:O,avg_tokens_per_failure:R,total_tokens:f,invocation_count:l.length,efficiency_score:O,trend:"insufficient_data"},l.length>=10){let h=Math.floor(l.length/2),_=l.slice(0,h),p=l.slice(h),I=_.reduce((ge,Ne)=>ge+Te(Ne),0)/_.length,y=p.reduce((ge,Ne)=>ge+Te(Ne),0)/p.length-I,m=I*.1;Math.abs(y)<m?a.trend="stable":y<0?a.trend="improving":a.trend="declining"}}return{agent_name:e,total_invocations:o,success_count:r,revision_count:s,cancellation_count:i,success_rate:c,failure_patterns:[],strong_areas:[],weak_areas:[],last_updated:new Date().toISOString(),token_efficiency:a}}function ke(e,t){if(!(0,A.existsSync)(e))return t;try{return JSON.parse((0,A.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function Ho(e,t){try{let n=(0,te.dirname)(e);n&&!(0,A.existsSync)(n)&&(0,A.mkdirSync)(n,{recursive:!0}),(0,A.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}var Yo=require("crypto");function le(e,t,n){return!n||n.sample_count<5?1e4:e&&n.by_project[e]!==void 0?n.by_project[e]:t&&n.by_task_type[t]!==void 0?n.by_task_type[t]:n.overall_avg}var ya=10,Sa=1800*1e3;function Wo(e){return(0,Bo.join)(e,".olympus","session-state.json")}function Go(e,t){let n=le(t);return{session_id:e||(0,Yo.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null,token_budget:{session_baseline:n,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}}}function D(e,t){let n=Wo(e),o=ke(n,null);if(!o)return Go(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>Sa)return Go(t,e);if(!o.token_budget){let i=le(e);o.token_budget={session_baseline:i,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o}function P(e,t){let n=Wo(e);t.last_updated=new Date().toISOString(),Ho(n,t)}function Vo(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,ya),e.last_updated=new Date().toISOString(),e}function Ko(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function et(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}function qo(e,t){let n=le(t);return e.token_budget={session_baseline:n,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function Jo(e,t){return e.token_budget||(e.token_budget={session_baseline:le(),current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e.token_budget.current_usage+=t,e.last_updated=new Date().toISOString(),e}function Xo(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function zo(e){if(!e.token_budget||e.token_budget.warning_issued)return!1;let t=e.token_budget.session_baseline*e.token_budget.warning_threshold;return e.token_budget.current_usage>=t}var Qo=require("crypto"),Oa={correction:[{regex:/no[,.]?\s*(that's|thats)?\s*(not|wrong)/i,confidence:.9},{regex:/that's\s*(incorrect|not right|not what)/i,confidence:.9},{regex:/you\s*(misunderstood|got it wrong)/i,confidence:.85},{regex:/actually,?\s*(I|it|the)/i,confidence:.6}],rejection:[{regex:/\b(stop|cancel|abort|halt)\b/i,confidence:.95},{regex:/don't\s*(do|want|need)\s*(that|this)/i,confidence:.85},{regex:/never\s*mind/i,confidence:.9},{regex:/forget\s*(it|that|about)/i,confidence:.8}],clarification:[{regex:/I\s*(meant|wanted|asked for)/i,confidence:.85},{regex:/what I\s*(mean|want|need)/i,confidence:.8},{regex:/to clarify/i,confidence:.9},{regex:/let me\s*(rephrase|explain|be clearer)/i,confidence:.85}],explicit_preference:[{regex:/always\s+(use|do|include|add|prefer)/i,confidence:.95},{regex:/never\s+(use|do|include|add)/i,confidence:.95},{regex:/I\s*(prefer|like|want)\s*(you to)?/i,confidence:.7},{regex:/from now on/i,confidence:.9},{regex:/in the future,?\s*(please|always)/i,confidence:.85}],praise:[{regex:/\bperfect\b/i,confidence:.9},{regex:/exactly(\s+what I (wanted|needed))?/i,confidence:.85},{regex:/great(\s+job)?/i,confidence:.7},{regex:/\bthanks?\b/i,confidence:.5},{regex:/looks?\s+good/i,confidence:.75}],enhancement:[{regex:/also\s+(add|include|do)/i,confidence:.7},{regex:/can you (also|additionally)/i,confidence:.7},{regex:/one more thing/i,confidence:.75}]};function Wt(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Oa))for(let{regex:s,confidence:i}of r)s.test(t)&&(!n||i>n.confidence)&&(n={category:o,confidence:i});return n}async function Zo(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=D(n,o),s=Wt(t),i=Vo(r,t,s?.category);if(s&&et(r)){let c={id:(0,Qo.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:s.category==="explicit_preference"?"explicit_preference":"revision",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:s.category,confidence:s.confidence};oe(c)}P(n,i)}var er=require("crypto");async function tr(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=D(n,o);if(!et(r))return;let s=Wt(t),i=s?.category==="praise"&&s.confidence>.7,c=_a(t,r.pending_completion?.task_description||"");if(i||c){let a={id:(0,er.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:"success",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:i?"praise":"enhancement",confidence:i?s.confidence:.6};oe(a);let l=Ko(r);P(n,l)}}function _a(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(l=>l.length>3)),o=n(e),r=n(t),s=new Set([...o].filter(a=>r.has(a))),i=new Set([...o,...r]);return(i.size>0?s.size/i.size:0)<.2}function nr(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function or(){g({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=nr(e);if(!t)return{continue:!0};let n=oo(t),o=ro(n);if(o.length===0)return{continue:!0};let r=o.some(a=>a.type==="ultrawork"),s=o.some(a=>a.type==="ultrathink"),i=o.some(a=>a.type==="search"),c=o.some(a=>a.type==="analyze");return r?(Ao(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Co}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:xo}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Po}}:c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Lo}}:{continue:!0}}}),g({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=ho().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),g({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Ro(),n=e.sessionId||"default",o={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},r=t.processChatParams(n,o);return r.requested&&r.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),g({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=nr(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Zo({prompt:t,directory:e.directory,sessionId:e.sessionId}),await tr({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var ue=require("fs"),re=require("path"),rr=require("os");function Ra(e,t){let n=(0,re.join)((0,rr.homedir)(),".claude"),o=[];e&&(o.push((0,re.join)(n,"sessions",e,"todos.json")),o.push((0,re.join)(n,"todos",`${e}.json`))),t&&(o.push((0,re.join)(t,".olympus","todos.json")),o.push((0,re.join)(t,".claude","todos.json")));let r=(0,re.join)(n,"todos");if((0,ue.existsSync)(r))try{let s=(0,ue.readdirSync)(r);for(let i of s)i.endsWith(".json")&&o.push((0,re.join)(r,i))}catch{}return o}function Ia(e){try{let t=(0,ue.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(o=>o&&typeof o.content=="string"&&typeof o.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(o=>{let r=o;return r&&typeof r.content=="string"&&typeof r.status=="string"}):[]}catch{return[]}}function Aa(e){return e.status!=="completed"&&e.status!=="cancelled"}async function xe(e,t){let n=Ra(e,t),o=new Set,r=[],s=[];for(let i of n){if(!(0,ue.existsSync)(i))continue;let c=Ia(i);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),Aa(a)&&s.push(a))}}return{count:s.length,todos:s,total:r.length}}function sr(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var tt=require("path");function ir(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}var ar=500;function cr(e){let t=ke((0,tt.join)(ne(),"user-preferences.json"),null),n=ke((0,tt.join)(Ce(e),"patterns.json"),null),o=ke((0,tt.join)(ne(),"agent-performance.json"),{}),r=[];t&&ba(t)&&r.push(wa(t)),n&&n.conventions.length>0&&r.push(va(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(Na(t.recurring_corrections.slice(0,5)));let s=Object.values(o).filter(a=>a.weak_areas.length>0);s.length>0&&r.push(Ca(s));let i=xa(o);if(i&&r.push(i),r.length===0)return"";let c=`<learned-context>
|
|
186
187
|
|
|
187
188
|
${r.join(`
|
|
188
189
|
|
|
@@ -192,20 +193,21 @@ ${r.join(`
|
|
|
192
193
|
|
|
193
194
|
---
|
|
194
195
|
|
|
195
|
-
`;return
|
|
196
|
+
`;return c.length>ar*4?c.substring(0,ar*4)+`
|
|
196
197
|
...</learned-context>
|
|
197
198
|
|
|
198
199
|
---
|
|
199
200
|
|
|
200
|
-
`:
|
|
201
|
-
`)}function
|
|
202
|
-
`)}function
|
|
203
|
-
`)}function
|
|
204
|
-
`)}function
|
|
205
|
-
`)}
|
|
206
|
-
`)
|
|
201
|
+
`:c}function ba(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function wa(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(`
|
|
202
|
+
`)}function va(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(`
|
|
203
|
+
`)}function Na(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
|
|
204
|
+
`)}function Ca(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(`
|
|
205
|
+
`)}function xa(e){let t=Object.values(e).filter(c=>c.token_efficiency&&ir(c)).sort((c,a)=>{let l=c.token_efficiency?.efficiency_score??0;return(a.token_efficiency?.efficiency_score??0)-l});if(t.length===0)return"";let n=[];n.push("<olympus-efficiency>"),n.push("AGENT EFFICIENCY (success%/avg tokens):");for(let c of t.slice(0,3)){let a=Math.round(c.success_rate*100),l=c.token_efficiency.avg_tokens_per_success,u=l>=1e3?`${(l/1e3).toFixed(1)}k`:`${Math.round(l)}`,f=c.success_rate>=.9&&c.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${c.agent_name}: ${a}%/${u}${f}`)}let o=le(),r=o>=1e3?`${(o/1e3).toFixed(0)}k`:o.toString(),s=Math.round(o*1.5),i=s>=1e3?`${(s/1e3).toFixed(0)}k`:s.toString();return n.push(""),n.push(`SESSION BUDGET: ~${r} baseline | warn at ${i}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
|
|
206
|
+
`)}function lr(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(`
|
|
207
|
+
`)}var nt=require("path"),de=require("fs"),Pa=require("crypto");function La(e){let t=(0,nt.join)(ne(),"discoveries.jsonl"),n=Ce(e),o=(0,nt.join)(n,"discoveries.jsonl"),r=ur(t),s=ur(o),i=[...r,...s],c={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0};for(let l of i)c[l.category]++;let a=[...i].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:s,global_discoveries:r,total_discoveries:i.length,categories:c,most_useful:a.slice(0,5)}}function dr(e,t=10){let n=La(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,i=o.filter(c=>c.expires_at?new Date(c.expires_at)>r:!0).map(c=>{let a=(r.getTime()-new Date(c.timestamp).getTime())/864e5,l=Math.max(.1,1-a/90),u=(c.verification_count+1)*l*c.confidence;return{discovery:c,score:u}});return i.sort((c,a)=>a.score-c.score),i.slice(0,t).map(c=>c.discovery)}function ur(e){if(!(0,de.existsSync)(e))return[];try{return(0,de.readFileSync)(e,"utf-8").split(`
|
|
208
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function pr(){g({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=cr(e.directory),n=dr(e.directory,5),o=lr(n),r=t+(o?`
|
|
207
209
|
|
|
208
|
-
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),
|
|
210
|
+
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),g({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[];try{let i=D(n,t);i.token_budget||(qo(i,n),P(n,i))}catch(i){console.error("[Olympus Learning] Failed to initialize token budget:",i)}let r=ce(n);r?.active&&o.push(`<session-restore>
|
|
209
211
|
|
|
210
212
|
[ULTRAWORK MODE RESTORED]
|
|
211
213
|
|
|
@@ -218,7 +220,7 @@ Continue working in ultrawork mode until all tasks are complete.
|
|
|
218
220
|
|
|
219
221
|
---
|
|
220
222
|
|
|
221
|
-
`);let s=await
|
|
223
|
+
`);let s=await xe(t,n);return s.count>0&&o.push(`<session-restore>
|
|
222
224
|
|
|
223
225
|
[PENDING TASKS DETECTED]
|
|
224
226
|
|
|
@@ -230,7 +232,7 @@ Please continue working on these tasks.
|
|
|
230
232
|
---
|
|
231
233
|
|
|
232
234
|
`),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
|
|
233
|
-
`)}}:{continue:!0}}})}var
|
|
235
|
+
`)}}:{continue:!0}}})}var Se=require("fs"),z=require("path"),en=require("os");var M=require("fs"),se=require("path"),fr=require("os");function Vt(e){let t=(0,se.join)(e,".olympus");return(0,se.join)(t,"ascent-state.json")}function Da(e){let t=(0,se.join)(e,".olympus");(0,M.existsSync)(t)||(0,M.mkdirSync)(t,{recursive:!0})}function Pe(e){let t=Vt(e);if(!(0,M.existsSync)(t))return null;try{let n=(0,M.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Ma(e,t){try{Da(e);let n=Vt(e);return(0,M.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function ot(e){let t=Vt(e);if(!(0,M.existsSync)(t))return!0;try{return(0,M.unlinkSync)(t),!0}catch{return!1}}function mr(e){let t=Pe(e);return!t||!t.active?null:(t.iteration+=1,Ma(e,t)?t:null)}function gr(e,t){let n=(0,se.join)((0,fr.homedir)(),".claude"),o=[(0,se.join)(n,"sessions",e,"transcript.md"),(0,se.join)(n,"sessions",e,"messages.json"),(0,se.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,M.existsSync)(r))try{let s=(0,M.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 F=require("fs"),Kt=require("path"),ja=3;function qt(e){return(0,Kt.join)(e,".olympus","ascent-verification.json")}function De(e){let t=qt(e);if(!(0,F.existsSync)(t))return null;try{return JSON.parse((0,F.readFileSync)(t,"utf-8"))}catch{return null}}function hr(e,t){let n=qt(e),o=(0,Kt.join)(e,".olympus");if(!(0,F.existsSync)(o))try{(0,F.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,F.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function Le(e){let t=qt(e);if((0,F.existsSync)(t))try{return(0,F.unlinkSync)(t),!0}catch{return!1}return!0}function Tr(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:ja,requested_at:new Date().toISOString(),original_task:n};return hr(e,o),o}function kr(e,t,n){let o=De(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(Le(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(Le(e),{...o,pending:!1}):(hr(e,o),o)):null}function Jt(e){return`<ascent-verification>
|
|
234
236
|
|
|
235
237
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
236
238
|
|
|
@@ -270,7 +272,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
270
272
|
|
|
271
273
|
---
|
|
272
274
|
|
|
273
|
-
`}function
|
|
275
|
+
`}function Er(e){return`<ascent-continuation-after-rejection>
|
|
274
276
|
|
|
275
277
|
[ORACLE REJECTED - Continue Working]
|
|
276
278
|
|
|
@@ -295,7 +297,7 @@ Continue working now.
|
|
|
295
297
|
|
|
296
298
|
---
|
|
297
299
|
|
|
298
|
-
`}function
|
|
300
|
+
`}function yr(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Sr(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 v=require("fs"),Ee=require("path"),Xt=require("os");function zt(e){let t=e||process.cwd(),n=(0,Ee.join)(t,".olympus");return(0,Ee.join)(n,"olympus-state.json")}function Qt(){return(0,Ee.join)((0,Xt.homedir)(),".claude","olympus-state.json")}function Fa(e){let t=e||process.cwd(),n=(0,Ee.join)(t,".olympus");(0,v.existsSync)(n)||(0,v.mkdirSync)(n,{recursive:!0})}function $a(){let e=(0,Ee.join)((0,Xt.homedir)(),".claude");(0,v.existsSync)(e)||(0,v.mkdirSync)(e,{recursive:!0})}function ye(e){let t=zt(e);if((0,v.existsSync)(t))try{let o=(0,v.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Qt();if((0,v.existsSync)(n))try{let o=(0,v.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Or(e,t){try{Fa(t);let n=zt(t);(0,v.writeFileSync)(n,JSON.stringify(e,null,2)),$a();let o=Qt();return(0,v.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Zt(e){let t=zt(e);if((0,v.existsSync)(t))try{(0,v.unlinkSync)(t)}catch{}let n=Qt();if((0,v.existsSync)(n))try{return(0,v.unlinkSync)(n),!0}catch{return!1}return!0}function _r(e){let t=ye(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Or(t,e)?t:null)}function Rr(e){let t=ye(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?`
|
|
299
301
|
|
|
300
302
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
301
303
|
|
|
@@ -317,7 +319,7 @@ Original task: ${e.original_prompt}
|
|
|
317
319
|
|
|
318
320
|
---
|
|
319
321
|
|
|
320
|
-
`}function
|
|
322
|
+
`}function Ar(e){let t=(0,z.join)((0,en.homedir)(),".claude"),n=[(0,z.join)(t,"sessions",e,"transcript.md"),(0,z.join)(t,"sessions",e,"messages.json"),(0,z.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,Se.existsSync)(o))try{let r=(0,Se.readFileSync)(o,"utf-8");if(yr(r))return!0}catch{continue}return!1}function Ha(e){let t=(0,z.join)((0,en.homedir)(),".claude"),n=[(0,z.join)(t,"sessions",e,"transcript.md"),(0,z.join)(t,"sessions",e,"messages.json"),(0,z.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,Se.existsSync)(o))try{let r=(0,Se.readFileSync)(o,"utf-8"),s=Sr(r);if(s.rejected)return s}catch{continue}return{rejected:!1,feedback:""}}async function Ga(e,t){let n=t||process.cwd(),o=Pe(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=De(n);if(r?.pending){if(e){if(Ar(e))return Le(n),ot(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=Ha(e);if(l.rejected){kr(n,!1,l.feedback);let u=De(n);if(u)return{shouldBlock:!0,message:Er(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:Jt(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(gr(e||"",o.completion_promise)){Tr(n,o.completion_promise,o.prompt);let a=De(n);return a?{shouldBlock:!0,message:Jt(a),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(ot(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 ot(n),Le(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=mr(n);return i?{shouldBlock:!0,message:`<ascent-continuation>
|
|
321
323
|
|
|
322
324
|
[ASCENT LOOP - ITERATION ${i.iteration}/${i.max_iterations}]
|
|
323
325
|
|
|
@@ -336,7 +338,7 @@ ${i.prompt?`Original task: ${i.prompt}`:""}
|
|
|
336
338
|
|
|
337
339
|
---
|
|
338
340
|
|
|
339
|
-
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function
|
|
341
|
+
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function Ba(e,t,n){let o=ce(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return bo(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=wo(t);return r?{shouldBlock:!0,message:vo(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Ya(e,t,n){let o=ye(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return Zt(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)?(Rr(t),Zt(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
|
|
340
342
|
|
|
341
343
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
342
344
|
|
|
@@ -359,11 +361,11 @@ DO NOT stop until Oracle has approved.
|
|
|
359
361
|
|
|
360
362
|
---
|
|
361
363
|
|
|
362
|
-
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=
|
|
364
|
+
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=_r(t);return r?{shouldBlock:!0,message:Ir(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Wa(e,t){let n=await xe(e,t);if(n.count===0)return null;let o=sr(n),r=o?`
|
|
363
365
|
|
|
364
366
|
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
365
367
|
|
|
366
|
-
${
|
|
368
|
+
${Do}
|
|
367
369
|
|
|
368
370
|
[Status: ${n.count} of ${n.total} tasks remaining]${r}
|
|
369
371
|
|
|
@@ -371,20 +373,20 @@ ${Po}
|
|
|
371
373
|
|
|
372
374
|
---
|
|
373
375
|
|
|
374
|
-
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function
|
|
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(),c=r.slice(s+1).trim();if(i==="description")n.description=
|
|
376
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function br(e,t){let n=t||process.cwd(),r=(await xe(e,n)).count>0,s=await Ga(e,n);if(s?.shouldBlock)return s;let i=await Ba(e,n,r);if(i?.shouldBlock)return i;let c=await Ya(e,n,r);if(c?.shouldBlock)return c;if(r){let a=await Wa(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function wr(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var Oe=require("fs"),tn=require("path"),vr=require("os");var Nr=require("crypto");function Va(){let e=(0,tn.join)((0,vr.homedir)(),".claude","todos");if(!(0,Oe.existsSync)(e))return 0;let t=0;try{let n=(0,Oe.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,Oe.readFileSync)((0,tn.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 Cr(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=D(t,n),r=Va();if(r>0&&o.pending_completion){let s={id:(0,Nr.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};oe(s)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},P(t,o)}function xr(){g({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await br(t,n),r=wr(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),g({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await Cr({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var pn=require("fs"),fn=require("os"),Ue=require("path");var W=require("fs"),j=require("path");var nn=require("path"),Pr=require("os"),Ka=(0,nn.join)((0,Pr.homedir)(),".olympus"),rt=(0,nn.join)(Ka,"rules-injector"),Lr=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],Dr=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],Mr=[".github/copilot-instructions.md"],Ur=/\.instructions\.md$/,jr=".claude/rules",Fr=[".md",".mdc"],on=["read","write","edit","multiedit"];function qa(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function Ja(e,t){return qa(t)?Ur.test(e):Fr.some(n=>e.endsWith(n))}function an(e){let t;try{t=(0,W.statSync)(e).isDirectory()?e:(0,j.dirname)(e)}catch{t=(0,j.dirname)(e)}for(;;){for(let o of Lr){let r=(0,j.join)(t,o);if((0,W.existsSync)(r))return t}let n=(0,j.dirname)(t);if(n===t)return null;t=n}}function sn(e,t){if((0,W.existsSync)(e))try{let n=(0,W.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,j.join)(e,o.name);o.isDirectory()?sn(r,t):o.isFile()&&Ja(o.name,e)&&t.push(r)}}catch{}}function rn(e){try{return(0,W.realpathSync)(e)}catch{return e}}function cn(e,t,n){let o=[],r=new Set,s=(0,j.dirname)(n),i=0;for(;;){for(let[u,d]of Dr){let f=(0,j.join)(s,u,d),E=[];sn(f,E);for(let S of E){let O=rn(S);r.has(O)||(r.add(O),o.push({path:S,realPath:O,isGlobal:!1,distance:i}))}}if(e&&s===e)break;let l=(0,j.dirname)(s);if(l===s)break;s=l,i++}if(e)for(let l of Mr){let u=(0,j.join)(e,l);if((0,W.existsSync)(u))try{if((0,W.statSync)(u).isFile()){let f=rn(u);r.has(f)||(r.add(f),o.push({path:u,realPath:f,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let c=(0,j.join)(t,jr),a=[];sn(c,a);for(let l of a){let u=rn(l);r.has(u)||(r.add(u),o.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return o.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),o}var $r=require("crypto"),Hr=require("path");function Xa(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function ln(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,Hr.relative)(n,t):t).replace(/\\/g,"/");for(let c of r)if(Xa(c,i))return{applies:!0,reason:`glob: ${c}`};return{applies:!1}}function Gr(e,t){return t.has(e)}function Br(e){return(0,$r.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Yr(e,t){return t.has(e)}function un(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:za(o),body:r}}catch{return{metadata:{},body:e}}}function za(e){let t=e.split(`
|
|
377
|
+
`),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(),c=r.slice(s+1).trim();if(i==="description")n.description=Me(c);else if(i==="alwaysApply")n.alwaysApply=c==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:a,consumed:l}=Qa(c,t,o);n.globs=ec(n.globs,a),o+=l;continue}o++}return n}function Me(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function Qa(e,t,n){if(e.startsWith("["))return{value:Za(e),consumed:1};if(!e||e===""){let r=[],s=1;for(let i=n+1;i<t.length;i++){let c=t[i],a=c.match(/^\s+-\s*(.*)$/);if(a){let l=Me(a[1].trim());l&&r.push(l),s++}else if(c.trim()==="")s++;else break}if(r.length>0)return{value:r,consumed:s}}let o=Me(e);return o.includes(",")?{value:o.split(",").map(s=>s.trim()).filter(s=>s.length>0),consumed:1}:{value:o,consumed:1}}function Za(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,s="";for(let c=0;c<t.length;c++){let a=t[c];if(!r&&(a==='"'||a==="'"))r=!0,s=a;else if(r&&a===s)r=!1,s="";else if(!r&&a===","){let l=o.trim();l&&n.push(Me(l)),o=""}else o+=a}let i=o.trim();return i&&n.push(Me(i)),n}function ec(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var $=require("fs"),Wr=require("path");function dn(e){return(0,Wr.join)(rt,`${e}.json`)}function Vr(e){let t=dn(e);if(!(0,$.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,$.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 Kr(e,t){(0,$.existsSync)(rt)||(0,$.mkdirSync)(rt,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,$.writeFileSync)(dn(e),JSON.stringify(n,null,2))}function qr(e){let t=dn(e);(0,$.existsSync)(t)&&(0,$.unlinkSync)(t)}function Jr(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Vr(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,Ue.resolve)(e,i):null}function r(i,c){let a=o(i);if(!a)return[];let l=an(a),u=n(c),d=(0,fn.homedir)(),f=cn(l,d,a),E=[];for(let S of f)if(!Gr(S.realPath,u.realPaths))try{let O=(0,pn.readFileSync)(S.path,"utf-8"),{metadata:R,body:h}=un(O),_;if(S.isSingleFile)_="copilot-instructions (always apply)";else{let N=ln(R,a,l);if(!N.applies)continue;_=N.reason??"matched"}let p=Br(h);if(Yr(p,u.contentHashes))continue;let I=l?(0,Ue.relative)(l,S.path):S.path;E.push({relativePath:I,matchReason:_,content:h,distance:S.distance}),u.realPaths.add(S.realPath),u.contentHashes.add(p)}catch{}return E.length>0&&(E.sort((S,O)=>S.distance-O.distance),Kr(c,u)),E}function s(i){if(i.length===0)return"";let c="";for(let a of i)c+=`
|
|
376
378
|
|
|
377
379
|
[Rule: ${a.relativePath}]
|
|
378
380
|
[Match: ${a.matchReason}]
|
|
379
|
-
${a.content}`;return c}return{processToolExecution:(i,c,a)=>{if(!
|
|
381
|
+
${a.content}`;return c}return{processToolExecution:(i,c,a)=>{if(!on.includes(i.toLowerCase()))return"";let l=r(c,a);return s(l)},getRulesForFile:i=>{let c=o(i);if(!c)return[];let a=an(c),l=(0,fn.homedir)(),u=cn(a,l,c),d=[];for(let f of u)try{let E=(0,pn.readFileSync)(f.path,"utf-8"),{metadata:S,body:O}=un(E),R;if(f.isSingleFile)R="copilot-instructions (always apply)";else{let _=ln(S,c,a);if(!_.applies)continue;R=_.reason??"matched"}let h=a?(0,Ue.relative)(a,f.path):f.path;d.push({relativePath:h,matchReason:R,content:O,distance:f.distance})}catch{}return d.sort((f,E)=>f.distance-E.distance)},clearSession:i=>{t.delete(i),qr(i)},isTrackedTool:i=>on.includes(i.toLowerCase())}}var it=require("node:fs"),Q=require("node:path");var H=require("node:fs"),Qr=require("node:path");var mn=require("node:path"),Xr=require("node:os"),tc=(0,mn.join)((0,Xr.homedir)(),".olympus"),st=(0,mn.join)(tc,"directory-readme"),zr="README.md",gn=["read","write","edit","multiedit"];function hn(e){return(0,Qr.join)(st,`${e}.json`)}function Zr(e){let t=hn(e);if(!(0,H.existsSync)(t))return new Set;try{let n=(0,H.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function es(e,t){(0,H.existsSync)(st)||(0,H.mkdirSync)(st,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,H.writeFileSync)(hn(e),JSON.stringify(n,null,2))}function ts(e){let t=hn(e);(0,H.existsSync)(t)&&(0,H.unlinkSync)(t)}var ns=4,nc=5e3;function oc(e,t=nc){if(Math.ceil(e.length/ns)<=t)return{result:e,truncated:!1};let o=t*ns;return{result:e.slice(0,o),truncated:!0}}function os(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Zr(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,Q.resolve)(e,i):null}function r(i){let c=[],a=i;for(;;){let l=(0,Q.join)(a,zr);if((0,it.existsSync)(l)&&c.push(l),a===e)break;let u=(0,Q.dirname)(a);if(u===a||!u.startsWith(e))break;a=u}return c.reverse()}function s(i,c){let a=o(i);if(!a)return"";let l=(0,Q.dirname)(a),u=n(c),d=r(l),f="";for(let E of d){let S=(0,Q.dirname)(E);if(!u.has(S))try{let O=(0,it.readFileSync)(E,"utf-8"),{result:R,truncated:h}=oc(O),_=h?`
|
|
380
382
|
|
|
381
|
-
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${
|
|
383
|
+
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${E}]`:"";f+=`
|
|
382
384
|
|
|
383
|
-
[Project README: ${
|
|
384
|
-
${
|
|
385
|
+
[Project README: ${E}]
|
|
386
|
+
${R}${_}`,u.add(S)}catch{}}return f&&es(c,u),f}return{processToolExecution:(i,c,a)=>gn.includes(i.toLowerCase())?s(c,a):"",getReadmesForFile:i=>{let c=o(i);if(!c)return[];let a=(0,Q.dirname)(c);return r(a)},clearSession:i=>{t.delete(i),ts(i)},isTrackedTool:i=>gn.includes(i.toLowerCase())}}var rs="non-interactive-env",ss={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"},Tn={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
|
|
385
387
|
option1
|
|
386
388
|
option2
|
|
387
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
389
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var is=Tn.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function rc(e){for(let t=0;t<is.length;t++)if(is[t].test(e))return Tn.banned[t]}function sc(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function ic(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${sc(o)}`).join(" ")};`}var kn={name:rs,async beforeCommand(e){let t=rc(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${ic(ss)} ${e}`,warning:n}:{command:e,warning:n}}};var yn=require("child_process");var as="olympus-orchestrator",cs=".olympus/",ls=["Write","Edit","write","edit"],us=`
|
|
388
390
|
|
|
389
391
|
---
|
|
390
392
|
|
|
@@ -410,7 +412,7 @@ You should NOT:
|
|
|
410
412
|
3. Verify the subagent's work after completion
|
|
411
413
|
|
|
412
414
|
---
|
|
413
|
-
`;var
|
|
415
|
+
`;var ds=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
414
416
|
|
|
415
417
|
You have an active work plan with incomplete tasks. Continue working.
|
|
416
418
|
|
|
@@ -419,7 +421,7 @@ RULES:
|
|
|
419
421
|
- Mark each checkbox [x] in the plan file when done
|
|
420
422
|
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
421
423
|
- Do not stop until all tasks are complete
|
|
422
|
-
- If blocked, document the blocker and move to the next task`,
|
|
424
|
+
- If blocked, document the blocker and move to the next task`,ps=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
423
425
|
|
|
424
426
|
Subagents FREQUENTLY claim completion when:
|
|
425
427
|
- Tests are actually FAILING
|
|
@@ -434,7 +436,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
434
436
|
3. Check build/typecheck - Must succeed
|
|
435
437
|
|
|
436
438
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
437
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
439
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,fs=`
|
|
438
440
|
|
|
439
441
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
440
442
|
|
|
@@ -457,7 +459,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
457
459
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
458
460
|
|
|
459
461
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
460
|
-
`,
|
|
462
|
+
`,ms=`
|
|
461
463
|
|
|
462
464
|
================================================================================
|
|
463
465
|
HARD BLOCK: DELEGATION REQUIRED
|
|
@@ -496,41 +498,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
|
|
|
496
498
|
Delegate to a subagent to proceed.
|
|
497
499
|
|
|
498
500
|
================================================================================
|
|
499
|
-
`;var
|
|
500
|
-
`;(0,
|
|
501
|
+
`;var je=".olympus",at="quest.json",ac=`${je}/${at}`,gs="notepads",cc=`${je}/${gs}`;var V=require("fs"),ct=require("path");function hs(e){return(0,ct.join)(e,je,at)}function lt(e){let t=hs(e);if(!(0,V.existsSync)(t))return null;try{let n=(0,V.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function ut(e){if(!(0,V.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,V.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}}}var Fe=class{recentTasks=[];maxTracked=3;recordTaskCompletion(t){this.recentTasks.unshift(t),this.recentTasks.length>this.maxTracked&&this.recentTasks.pop()}isVerificationEdit(t,n){return this.recentTasks.some(r=>r.filesModified.includes(t))&&n<10}getRecentTaskFiles(){let t=this.recentTasks.flatMap(n=>n.filesModified);return Array.from(new Set(t))}getRecentTasks(){return[...this.recentTasks]}clear(){this.recentTasks=[]}get trackedCount(){return this.recentTasks.length}},Op=new Fe;var pe=require("fs"),En=require("path");function $e(e,t){let n=t||process.cwd(),o=(0,En.join)(n,".olympus","logs"),r=(0,En.join)(o,"hook-violations.jsonl");try{(0,pe.existsSync)(o)||(0,pe.mkdirSync)(o,{recursive:!0});let s=JSON.stringify(e)+`
|
|
502
|
+
`;(0,pe.appendFileSync)(r,s,"utf-8")}catch(s){console.error("[Hook Logging] Failed to log violation:",s)}}var Ts=new Fe;function ks(e){return e?e.replace(/\\/g,"/").includes(cs):!0}function dc(e){if(!e)return!1;let t=e.replace(/\\/g,"/");return t.includes("__tests__/")||t.endsWith(".test.ts")||t.endsWith(".test.js")||t.endsWith(".spec.ts")||t.endsWith(".spec.js")}function pc(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",o=t.new_string??"";if(!n&&!o)return 0;let r=n.split(`
|
|
501
503
|
`).length,s=o.split(`
|
|
502
504
|
`).length;return Math.abs(s-r)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
|
|
503
|
-
`).length:0}return 0}function
|
|
505
|
+
`).length:0}return 0}function Es(e){return ls.includes(e)}function fc(e){try{let t=(0,yn.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,yn.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let s of n.split(`
|
|
504
506
|
`)){if(!s)continue;let i=s.substring(0,2).trim(),c=s.substring(3);i==="A"||i==="??"?o.set(c,"added"):i==="D"?o.set(c,"deleted"):o.set(c,"modified")}let r=[];for(let s of t.split(`
|
|
505
|
-
`)){let i=s.split(" ");if(i.length<3)continue;let[c,a,l]=i,u=c==="-"?0:parseInt(c,10),
|
|
507
|
+
`)){let i=s.split(" ");if(i.length<3)continue;let[c,a,l]=i,u=c==="-"?0:parseInt(c,10),d=a==="-"?0:parseInt(a,10);r.push({path:l,added:u,removed:d,status:o.get(l)??"modified"})}return r}catch{return[]}}function mc(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
506
508
|
No file changes detected.
|
|
507
509
|
`;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(`
|
|
508
|
-
`)}function
|
|
510
|
+
`)}function ys(e){let t=ps;return e&&(t+=`
|
|
509
511
|
|
|
510
512
|
---
|
|
511
513
|
|
|
512
514
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
513
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
515
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function gc(e,t,n){let o=t.total-t.completed;return`
|
|
514
516
|
---
|
|
515
517
|
|
|
516
518
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
517
519
|
|
|
518
520
|
---
|
|
519
521
|
|
|
520
|
-
${
|
|
522
|
+
${ys(n)}
|
|
521
523
|
|
|
522
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
524
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function hc(e,t,n){return ds.replace(/{PLAN_NAME}/g,e)+`
|
|
523
525
|
|
|
524
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
526
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function Tc(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!Es(t))return{continue:!0};let s=n?.filePath??n?.path??n?.file;if(!s)return{continue:!0};let i=s.replace(/\\/g,"/");if(ks(i))return $e({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(dc(i))return $e({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let c=pc(t,n);return Ts.isVerificationEdit(i,c)?($e({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:c,wasBlocked:!1,reason:`Allowed: Verification edit (${c} lines on recent task file)`},r),{continue:!0}):($e({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:c,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:ms})}function kc(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:s}=e,i=r||process.cwd();if(Es(n)){let c=o?.filePath??o?.path??o?.file;if(c&&!ks(c))return{continue:!0,modifiedOutput:t+us}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let a=fc(i),l=a.map(f=>f.path);Ts.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:s||`task-${Date.now()}`});let u=mc(a),d=lt(i);if(d){let f=ut(d.active_plan);return{continue:!0,modifiedOutput:`
|
|
525
527
|
## SUBAGENT WORK COMPLETED
|
|
526
528
|
|
|
527
529
|
${u}
|
|
528
530
|
<system-reminder>
|
|
529
|
-
${
|
|
531
|
+
${gc(d.plan_name,f,s)}
|
|
530
532
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
531
533
|
<system-reminder>
|
|
532
|
-
${
|
|
533
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
534
|
+
${ys(s)}
|
|
535
|
+
</system-reminder>`}}return{continue:!0}}function Ec(e){let t=lt(e);if(!t)return{shouldContinue:!1};let n=ut(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:hc(t.plan_name,o,n.total)}}function dt(e){return{name:as,preTool:(t,n)=>Tc({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>kc({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>Ec(e),getSingleTaskDirective:()=>fs}}function Ss(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function Os(){g({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=Jr(e.directory||process.cwd()),n=Ss(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}}}),g({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=os(e.directory||process.cwd()),n=Ss(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}}}),g({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!kn.beforeCommand)return{continue:!0};let n=await kn.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}}}}),g({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>dt(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var yc=["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"],Sc=`
|
|
534
536
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
535
537
|
|
|
536
538
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -541,7 +543,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
541
543
|
4. CONTINUE with corrected action based on the real file content
|
|
542
544
|
|
|
543
545
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
544
|
-
`;function
|
|
546
|
+
`;function Oc(e){let t=e.toLowerCase();return yc.some(n=>t.includes(n.toLowerCase()))}function _s(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:Oc(t.output)?{...t,output:t.output+Sc}:t}}var As=ae(require("fs"),1),ft=ae(require("path"),1),bs=require("os");var pt=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Sn=["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"],On=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
|
|
545
547
|
|
|
546
548
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
547
549
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -579,13 +581,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
579
581
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
580
582
|
|
|
581
583
|
Detected comments/docstrings:
|
|
582
|
-
`,
|
|
583
|
-
`;
|
|
584
|
+
`,_n={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},Rn={".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 _c(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function Rc(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of pt){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>pt.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function Ic(e){let t=e.text.toLowerCase().trim();for(let n of Sn)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function Ac(e){return{shouldSkip:!1}}function bc(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 wc(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 vc=[_c,Rc,Ic,bc,wc,Ac];function In(e){return e.filter(t=>{for(let n of vc)if(n(t).shouldSkip)return!1;return!0})}var Nc=process.env.COMMENT_CHECKER_DEBUG==="1",Cc=ft.join((0,bs.tmpdir)(),"comment-checker-debug.log");function fe(...e){if(Nc){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
585
|
+
`;As.appendFileSync(Cc,t)}}function xc(e){let t=ft.extname(e).toLowerCase();return Rn[t]}function An(e,t){let n=xc(t);if(!n)return fe("unsupported language for:",t),[];let o=_n[n];if(!o)return fe("no pattern for language:",n),[];let r=[],s=e.split(`
|
|
584
586
|
`);o.lastIndex=0;let i;for(;(i=o.exec(e))!==null;){let c=i.index,a=i[0],u=e.substring(0,c).split(`
|
|
585
|
-
`).length,
|
|
587
|
+
`).length,d="line",f=!1;a.startsWith("/*")||a.startsWith("<!--")?d="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(d="docstring",f=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:f})}return r}function Pc(e,t){return An(e,t)}function Rs(e,t,n){let o=An(e,t);if(n){let r=An(n,t),s=new Set(r.map(i=>i.text));return o.filter(i=>!s.has(i.text))}return o}function Lc(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=On;for(let[o,r]of t){n+=`
|
|
586
588
|
File: ${o}
|
|
587
589
|
`;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?"...":""}
|
|
588
|
-
`}}return n}function
|
|
590
|
+
`}}return n}function Dc(e,t,n,o,r){let s=[];if(t)s=Pc(t,e);else if(o)s=Rs(o,e,n);else if(r&&r.length>0)for(let c of r){let a=Rs(c.new_string,e,c.old_string);s.push(...a)}let i=In(s);return fe(`found ${s.length} comments, ${i.length} flagged after filtering`),i.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:i.length,message:Lc(i),comments:i}}var He=new Map,Mc=6e4;function Uc(){let e=Date.now();for(let[t,n]of He)e-n.timestamp>Mc&&He.delete(t)}var Is=!1;function ws(e){return fe("createCommentCheckerHook called",{config:e}),Is||(Is=!0,setInterval(Uc,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,c=t.tool_input.edits;if(!o)return null;let a=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return fe("registering pendingCall:",{callId:a,filePath:o,tool:n}),He.set(a,{filePath:o,content:r,oldString:s,newString:i,edits:c,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o,r;for(let[i,c]of He)if(c.sessionId===t.session_id&&c.tool===n){o=c,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&&He.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 fe("skipping due to tool failure in response"),null}let s=Dc(o.filePath,o.content,o.oldString,o.newString,o.edits);return s.hasComments&&s.message?(fe("detected comments, returning message"),e?.customPrompt||s.message):null}}}var Ds=ae(require("fs"),1),Ms=ae(require("path"),1),Us=require("os");var Ns=[/(\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],Cs=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],jc=[/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],Fc=/messages\.(\d+)/;function $c(e){return jc.some(t=>t.test(e))}function bn(e){for(let t of Ns){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 vs(e){let t=e.match(Fc);if(t)return parseInt(t[1],10)}function _e(e){if($c(e))return!1;let t=e.toLowerCase();return Cs.some(n=>t.includes(n.toLowerCase()))}function mt(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:vs(e)};if(_e(e)){let l=bn(e);return{currentTokens:l?.current??0,maxTokens:l?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],o=t.data,r=o?.responseBody,s=t.message,i=t.error,c=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 c?.message=="string"&&n.push(c.message),typeof o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let l=JSON.stringify(t);_e(l)&&n.push(l)}catch{}let a=n.join(" ");if(!_e(a))return null;if(typeof r=="string")try{let l=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of l){let f=r.match(d);if(f)try{let E=JSON.parse(f[1]),S=E.error?.message||"",O=bn(S);if(O)return{currentTokens:O.current,maxTokens:O.max,requestId:E.request_id,errorType:E.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&_e(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=bn(l);if(u)return{currentTokens:u.current,maxTokens:u.max,errorType:"token_limit_exceeded"}}return a.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:vs(a)}:_e(a)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function wn(e){return _e(e)}var vn=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
589
591
|
|
|
590
592
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
591
593
|
|
|
@@ -610,7 +612,7 @@ Current Status:
|
|
|
610
612
|
- Context limit exceeded
|
|
611
613
|
- Further API calls will fail until context is reduced
|
|
612
614
|
- Action required before continuing
|
|
613
|
-
`,
|
|
615
|
+
`,Nn="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",Cn=`API ERROR: Non-empty content validation failed.
|
|
614
616
|
|
|
615
617
|
This error typically occurs when:
|
|
616
618
|
- A message has empty text content
|
|
@@ -621,7 +623,7 @@ Suggested actions:
|
|
|
621
623
|
2. If the error persists, start a new session
|
|
622
624
|
|
|
623
625
|
The system will attempt automatic recovery.
|
|
624
|
-
`;var
|
|
626
|
+
`;var xn=`CONTEXT RECOVERY FAILED
|
|
625
627
|
|
|
626
628
|
All automatic recovery attempts have been exhausted.
|
|
627
629
|
Please start a new session to continue.
|
|
@@ -632,13 +634,13 @@ Before starting a new session:
|
|
|
632
634
|
3. Document the current state of the task
|
|
633
635
|
|
|
634
636
|
You can copy this conversation summary to continue in a new session.
|
|
635
|
-
`;var
|
|
636
|
-
`;
|
|
637
|
+
`;var Pn={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var Hc=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",Gc=Ms.join((0,Us.tmpdir)(),"context-limit-recovery-debug.log");function gt(...e){if(Hc){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
638
|
+
`;Ds.appendFileSync(Gc,t)}}var ht=new Map,js=3e5;function xs(e){let t=ht.get(e),n=Date.now();return t&&n-t.lastErrorTime>js&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},ht.set(e,t)),t}function Bc(){let e=Date.now();for(let[t,n]of ht)e-n.lastErrorTime>js&&ht.delete(t)}var Ps=!1;function Fs(e){return gt("createContextLimitRecoveryHook called",{config:e}),Ps||(Ps=!0,setInterval(Bc,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=mt(t.tool_response);if(!n&&!wn(t.tool_response))return null;gt("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=xs(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=Ls(n,o,e);return r.message?(gt("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=mt(t.error);if(!n)return{attempted:!1,success:!1};gt("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=xs(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=Ls(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function Ls(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:Cn,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>Pn.maxAttempts)return{message:xn,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=vn;return e?.currentTokens&&e?.maxTokens&&(o+=`
|
|
637
639
|
Token Details:
|
|
638
640
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
639
641
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
640
642
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
641
|
-
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:
|
|
643
|
+
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:Nn,errorType:e?.errorType||"token_limit_exceeded"}}var $s=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,Yc=/exceeds maximum allowed tokens/i;function Wc(e){let t=e.match($s);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Vc(e,t){return e.toLowerCase()==="read"&&($s.test(t)||Yc.test(t))}function Kc(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
|
|
642
644
|
|
|
643
645
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
644
646
|
|
|
@@ -668,7 +670,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
668
670
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
669
671
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
670
672
|
|
|
671
|
-
Proceed with one of these strategies.`.trim()}function
|
|
673
|
+
Proceed with one of these strategies.`.trim()}function Hs(){return{postToolUse:e=>{if(!e.tool_response||!Vc(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=Wc(e.tool_response);return Kc(t,n||void 0)}}}var Ks=ae(require("fs"),1),qs=ae(require("path"),1),Js=require("os");var Ln=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,Tt=4,Dn=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
672
674
|
|
|
673
675
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
674
676
|
|
|
@@ -688,7 +690,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
|
|
|
688
690
|
|
|
689
691
|
Current Status: Context usage is high but recoverable.
|
|
690
692
|
Action recommended: Use /compact when convenient.
|
|
691
|
-
`,
|
|
693
|
+
`,Mn=`CRITICAL: CONTEXT WINDOW ALMOST FULL
|
|
692
694
|
|
|
693
695
|
Your context usage is critically high. Immediate action required:
|
|
694
696
|
|
|
@@ -707,8 +709,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
707
709
|
|
|
708
710
|
WARNING: Further messages may fail if context is not reduced.
|
|
709
711
|
Action required: Run /compact now.
|
|
710
|
-
`;var
|
|
711
|
-
`;
|
|
712
|
+
`;var qc=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Jc=qs.join((0,Js.tmpdir)(),"preemptive-compaction-debug.log");function Re(...e){if(qc){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
713
|
+
`;Ks.appendFileSync(Jc,t)}}var kt=new Map;function Xc(){let e=Date.now(),t=1800*1e3;for(let[n,o]of kt)e-o.lastWarningTime>t&&kt.delete(n)}var Gs=!1;function Xs(e){return Math.ceil(e.length/Tt)}function zc(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=Ln,s=Xs(e),i=s/r,c=i>=n,a=i>=o,l="none";return a?l="compact":c&&(l="warn"),{totalTokens:s,usageRatio:i,isWarning:c,isCritical:a,action:l}}function Et(e){let t=kt.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},kt.set(e,t)),t}function Qc(e,t){let n=Et(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,s=Date.now();return s-n.lastWarningTime<o?(Re("skipping warning - cooldown active",{sessionId:e,elapsed:s-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(Re("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Zc(e){let t=Et(e);t.lastWarningTime=Date.now(),t.warningCount++}function zs(e){return Re("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(Gs||(Gs=!0,setInterval(Xc,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=Et(t.session_id);s.estimatedTokens+=r,Re("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:s.estimatedTokens});let i=zc("x".repeat(s.estimatedTokens*Tt),e);return!i.isWarning||!Qc(t.session_id,e)?null:(Zc(t.session_id),Re("injecting context warning",{sessionId:t.session_id,usageRatio:i.usageRatio,isCritical:i.isCritical}),e?.customMessage?e.customMessage:i.isCritical?Mn:Dn)},stop:t=>{let n=Et(t.session_id);return n.warningCount>0&&(Re("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var G=require("fs"),Zs=require("path");var Un=require("path"),Qs=require("os"),el=(0,Un.join)((0,Qs.homedir)(),".olympus"),yt=(0,Un.join)(el,"agent-usage-reminder"),jn=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"]),Fn=new Set(["task","call_omo_agent","olympus_task"]),$n=`
|
|
712
714
|
[Agent Usage Reminder]
|
|
713
715
|
|
|
714
716
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -732,7 +734,7 @@ WHY:
|
|
|
732
734
|
- Reduces context window usage in main session
|
|
733
735
|
|
|
734
736
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
735
|
-
`;function
|
|
737
|
+
`;function Hn(e){return(0,Zs.join)(yt,`${e}.json`)}function Gn(e){let t=Hn(e);if(!(0,G.existsSync)(t))return null;try{let n=(0,G.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function St(e){(0,G.existsSync)(yt)||(0,G.mkdirSync)(yt,{recursive:!0});let t=Hn(e.sessionID);(0,G.writeFileSync)(t,JSON.stringify(e,null,2))}function Bn(e){let t=Hn(e);(0,G.existsSync)(t)&&(0,G.unlinkSync)(t)}function tl(e){let t=e||process.cwd();return Pe(t)?.active?{active:!0,mode:"ascent"}:ye(t)?.active?{active:!0,mode:"olympus"}:ce(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function nl(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function ol(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
|
|
736
738
|
|
|
737
739
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
738
740
|
|
|
@@ -758,27 +760,27 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
758
760
|
|
|
759
761
|
---
|
|
760
762
|
|
|
761
|
-
`}function
|
|
762
|
-
`;(0,ri.appendFileSync)(Xs,t)}}function si(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 ii(e){let n=si(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function ai(e){let t=si(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 Qc(e){return ai(e)!==null}function Zc(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function el(e,t){x("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=J(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let o=Zc(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 tl(e,t,n){x("recoverThinkingBlockOrder",{sessionID:e});let o=ii(n);if(o!==null){let i=oi(e,o);if(i)return x("Found target message by index",{targetIndex:o,targetMessageID:i}),Yn(e,i)}let r=Bn(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)Yn(e,i)&&(s=!0);return s}async function nl(e,t){x("recoverThinkingDisabledViolation",{sessionID:e});let n=Gn(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)ti(r)&&(o=!0);return o}async function ol(e,t,n){x("recoverEmptyContentMessage",{sessionID:e});let o=ii(n),r=t.info?.id,s=!1,i=ni(e);for(let l of i)He(l,G)&&(s=!0);let c=ei(e);for(let l of c)Fe(e,l,G)&&(s=!0);if(o!==null){let l=Zs(e,o);if(l&&(He(l,G)||Fe(e,l,G)))return!0}if(r&&(He(r,G)||Fe(e,r,G)))return!0;let a=Hn(e);for(let l of a)He(l,G)&&(s=!0),Fe(e,l,G)&&(s=!0);return s}async function rl(e,t,n,o){x("handleSessionRecovery",{sessionID:e,error:t});let r=ai(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 el(e,i);break;case"thinking_block_order":s=await tl(e,i,t);break;case"thinking_disabled_violation":s=await nl(e,i);break;case"empty_content":s=await ol(e,i,t);break}x("Recovery result",{errorType:r,success:s});let c=o?.customMessages?.[r]||St[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?c:void 0,errorType:r}}catch(s){return x("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function ci(e){return x("createSessionRecoveryHook",{config:e}),{onError:async t=>rl(t.session_id,t.error,t.message,e),isRecoverable:t=>Qc(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||St[t]?.message}}}function li(){let e=ci();h({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 B=require("fs"),Ot=require("path"),ui=require("os");var Ge=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 sl=1800*1e3,Ie=(0,Ot.join)((0,ui.homedir)(),".claude",".olympus","background-tasks"),Rt=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Ge(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,B.existsSync)(Ie)||(0,B.mkdirSync)(Ie,{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,Ot.join)(Ie,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,B.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,B.existsSync)(n)&&(0,B.unlinkSync)(n)}loadPersistedTasks(){if((0,B.existsSync)(Ie))try{let{readdirSync:t}=require("fs"),n=t(Ie);for(let o of n)if(o.endsWith(".json"))try{let r=(0,Ot.join)(Ie,o),s=(0,B.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??sl;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let s=r.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(o):s.length!==r.length&&this.notifications.set(o,s)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(a=>a.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,c={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,c),this.persistTask(c),c}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let s=this.tasks.get(t);s&&(s.status=n,o&&(s.result=o),r&&(s.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(s=>s.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),s=Math.floor(r/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${r%60}s`:s>0?`${s}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let s=this.formatDuration(r.startedAt,r.completedAt),i=r.status.toUpperCase(),c=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${c}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
763
|
-
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},
|
|
764
|
-
`)}function
|
|
763
|
+
`}function ei(){let e=new Map,t=new Map;function n(a){if(!e.has(a)){let u=Gn(a)??{sessionID:a,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(a,u)}return e.get(a)}function o(a){let l=n(a);l.agentUsed=!0,l.updatedAt=Date.now(),St(l)}function r(a){e.delete(a),Bn(a),t.delete(a)}function s(a,l,u){let d=t.get(a)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:a};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(a,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(a,d)),d.consecutiveCount)}return{"tool.execute.after":async(a,l)=>{let{tool:u,sessionID:d}=a,f=u.toLowerCase();if(Fn.has(f)){o(d),s(d,f,"");return}let E=a.properties||{},S=nl(E),O=s(d,f,S||""),R=tl();if(R.active){let _=ol(O,R.mode);if(_){l.output=_+l.output;return}}if(!jn.has(f))return;let h=n(d);h.agentUsed||(l.output+=$n,h.reminderCount++,h.updatedAt=Date.now(),St(h))},event:async({event:a})=>{let l=a.properties;if(a.type==="session.deleted"){let u=l?.info;u?.id&&r(u.id)}if(a.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&r(u)}}}}function ti(){let e=process.cwd(),t=_s();g({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async a=>{if(!a.toolName||!a.toolOutput)return{continue:!0};let l=t.afterToolExecute({tool:a.toolName,sessionId:a.sessionId||"",callId:""},{title:"",output:String(a.toolOutput),metadata:void 0});return l.output!==String(a.toolOutput)?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.output.substring(String(a.toolOutput).length)}}:{continue:!0}}});let n=ws();g({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async a=>{if(!a.toolName)return{continue:!0};let l=n.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let o=Fs();g({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async a=>{if(!a.toolName)return{continue:!0};let l=o.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let r=Hs();g({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async a=>{if(!a.toolName||a.toolName.toLowerCase()!=="read")return{continue:!0};let l=r.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let s=zs();g({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async a=>{if(!a.toolName)return{continue:!0};let l=s.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let i=ei();g({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async a=>{if(!a.toolName)return{continue:!0};let l={title:"",output:a.toolOutput?String(a.toolOutput):"",metadata:void 0};await i["tool.execute.after"]({tool:a.toolName,sessionID:a.sessionId||"",callID:""},l);let u=a.toolOutput?String(a.toolOutput):"";return l.output!==u?{continue:!0,message:l.output.substring(u.length)}:{continue:!0}}});let c=dt(e);g({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async a=>{if(!a.toolName)return{continue:!0};let l=c.postTool(a.toolName,a.toolInput||{},a.toolOutput?String(a.toolOutput):"");return l.continue?l.modifiedOutput?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.modifiedOutput}}:l.message?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.message}}:{continue:!0}:{continue:!1,stopReason:l.message}}})}var fi=require("node:fs");var k=require("node:fs"),U=require("node:path");var Ie=require("node:path"),Ot=require("node:os");function rl(){return process.env.XDG_DATA_HOME??(0,Ie.join)((0,Ot.homedir)(),".local","share")}function sl(){return(0,Ie.join)(rl(),"claude-code","storage")}var ni=sl(),Ge=(0,Ie.join)(ni,"message"),Ae=(0,Ie.join)(ni,"part"),ie=new Set(["thinking","redacted_thinking","reasoning"]),oi=new Set(["step-start","step-finish"]);var B="[user interrupted]",_t={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 ri=process.env.SESSION_RECOVERY_DEBUG==="1",si=(0,Ie.join)((0,Ot.tmpdir)(),"session-recovery-debug.log");function il(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function al(e){if(!(0,k.existsSync)(Ge))return"";let t=(0,U.join)(Ge,e);if((0,k.existsSync)(t))return t;for(let n of(0,k.readdirSync)(Ge)){let o=(0,U.join)(Ge,n,e);if((0,k.existsSync)(o))return o}return""}function Z(e){let t=al(e);if(!t||!(0,k.existsSync)(t))return[];let n=[];for(let o of(0,k.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,k.readFileSync)((0,U.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 J(e){let t=(0,U.join)(Ae,e);if(!(0,k.existsSync)(t))return[];let n=[];for(let o of(0,k.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,k.readFileSync)((0,U.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function ii(e){return ie.has(e.type)||oi.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function ai(e){return J(e).some(ii)}function Be(e,t,n){let o=(0,U.join)(Ae,t);(0,k.existsSync)(o)||(0,k.mkdirSync)(o,{recursive:!0});let r=il(),s={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,k.writeFileSync)((0,U.join)(o,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Yn(e){let t=Z(e),n=[];for(let o of t)ai(o.id)||n.push(o.id);return n}function ci(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(!ai(s.id))return s.id}return null}function Wn(e){let t=Z(e),n=[];for(let o of t){if(o.role!=="assistant")continue;J(o.id).some(i=>ie.has(i.type))&&n.push(o.id)}return n}function li(e){let t=Z(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=J(o.id);if(r.length===0)continue;let s=r.some(c=>ie.has(c.type)),i=r.some(ii);s&&!i&&n.push(o.id)}return n}function Vn(e){let t=Z(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=J(o.id);if(r.length===0)continue;let i=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];ie.has(i.type)||n.push(o.id)}return n}function cl(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=J(s.id);for(let c of i)if(ie.has(c.type)){let a=c.thinking,l=c.text,u=a||l;if(u&&u.trim().length>0)return u}}return""}function Kn(e,t){let n=(0,U.join)(Ae,t);(0,k.existsSync)(n)||(0,k.mkdirSync)(n,{recursive:!0});let o=cl(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,k.writeFileSync)((0,U.join)(n,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function ui(e){let t=(0,U.join)(Ae,e);if(!(0,k.existsSync)(t))return!1;let n=!1;for(let o of(0,k.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,U.join)(t,o),s=(0,k.readFileSync)(r,"utf-8"),i=JSON.parse(s);ie.has(i.type)&&((0,k.unlinkSync)(r),n=!0)}catch{continue}return n}function Ye(e,t=B){let n=(0,U.join)(Ae,e);if(!(0,k.existsSync)(n))return!1;let o=!1;for(let r of(0,k.readdirSync)(n))if(r.endsWith(".json"))try{let s=(0,U.join)(n,r),i=(0,k.readFileSync)(s,"utf-8"),c=JSON.parse(i);if(c.type==="text"){let a=c;a.text?.trim()||(a.text=t,a.synthetic=!0,(0,k.writeFileSync)(s,JSON.stringify(a,null,2)),o=!0)}}catch{continue}return o}function di(e){let t=Z(e),n=[];for(let o of t)J(o.id).some(i=>i.type!=="text"?!1:!i.text?.trim())&&n.push(o.id);return n}function pi(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=J(o.id);if(r.length===0)return null;let i=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];return ie.has(i.type)?null:o.id}function x(...e){if(ri){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
764
|
+
`;(0,fi.appendFileSync)(si,t)}}function mi(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function gi(e){let n=mi(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function hi(e){let t=mi(e);return t.includes("tool_use")&&t.includes("tool_result")?"tool_result_missing":t.includes("thinking")&&(t.includes("first block")||t.includes("must start with")||t.includes("preceeding")||t.includes("final block")||t.includes("cannot be thinking")||t.includes("expected")&&t.includes("found"))?"thinking_block_order":t.includes("thinking is disabled")&&t.includes("cannot contain")?"thinking_disabled_violation":t.includes("empty")&&(t.includes("content")||t.includes("message"))?"empty_content":null}function ll(e){return hi(e)!==null}function ul(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function dl(e,t){x("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=J(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let o=ul(n);return o.length===0?(x("No tool_use IDs found"),!1):(x("Found tool_use IDs to inject results for",o),!0)}async function pl(e,t,n){x("recoverThinkingBlockOrder",{sessionID:e});let o=gi(n);if(o!==null){let i=pi(e,o);if(i)return x("Found target message by index",{targetIndex:o,targetMessageID:i}),Kn(e,i)}let r=Vn(e);if(r.length===0)return x("No orphan thinking messages found"),!1;x("Found orphan thinking messages",r);let s=!1;for(let i of r)Kn(e,i)&&(s=!0);return s}async function fl(e,t){x("recoverThinkingDisabledViolation",{sessionID:e});let n=Wn(e);if(n.length===0)return x("No messages with thinking blocks found"),!1;x("Found messages with thinking blocks",n);let o=!1;for(let r of n)ui(r)&&(o=!0);return o}async function ml(e,t,n){x("recoverEmptyContentMessage",{sessionID:e});let o=gi(n),r=t.info?.id,s=!1,i=di(e);for(let l of i)Ye(l,B)&&(s=!0);let c=li(e);for(let l of c)Be(e,l,B)&&(s=!0);if(o!==null){let l=ci(e,o);if(l&&(Ye(l,B)||Be(e,l,B)))return!0}if(r&&(Ye(r,B)||Be(e,r,B)))return!0;let a=Yn(e);for(let l of a)Ye(l,B)&&(s=!0),Be(e,l,B)&&(s=!0);return s}async function gl(e,t,n,o){x("handleSessionRecovery",{sessionID:e,error:t});let r=hi(t);if(!r)return x("Not a recoverable error"),{attempted:!1,success:!1};x("Detected recoverable error type",r);try{let s=!1,i=n||{info:{},parts:[]};switch(r){case"tool_result_missing":s=await dl(e,i);break;case"thinking_block_order":s=await pl(e,i,t);break;case"thinking_disabled_violation":s=await fl(e,i);break;case"empty_content":s=await ml(e,i,t);break}x("Recovery result",{errorType:r,success:s});let c=o?.customMessages?.[r]||_t[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?c:void 0,errorType:r}}catch(s){return x("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function Ti(e){return x("createSessionRecoveryHook",{config:e}),{onError:async t=>gl(t.session_id,t.error,t.message,e),isRecoverable:t=>ll(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||_t[t]?.message}}}function ki(){let e=Ti();g({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var Y=require("fs"),Rt=require("path"),Ei=require("os");var We=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let s=this.queues.get(t)??[];s.push(r),this.queues.set(t,s)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var hl=1800*1e3,be=(0,Rt.join)((0,Ei.homedir)(),".claude",".olympus","background-tasks"),It=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new We(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,Y.existsSync)(be)||(0,Y.mkdirSync)(be,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,Rt.join)(be,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,Y.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,Y.existsSync)(n)&&(0,Y.unlinkSync)(n)}loadPersistedTasks(){if((0,Y.existsSync)(be))try{let{readdirSync:t}=require("fs"),n=t(be);for(let o of n)if(o.endsWith(".json"))try{let r=(0,Rt.join)(be,o),s=(0,Y.readFileSync)(r,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??hl;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let s=r.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(o):s.length!==r.length&&this.notifications.set(o,s)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(a=>a.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,c={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,c),this.persistTask(c),c}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let s=this.tasks.get(t);s&&(s.status=n,o&&(s.result=o),r&&(s.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(s=>s.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),s=Math.floor(r/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${r%60}s`:s>0?`${s}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let s=this.formatDuration(r.startedAt,r.completedAt),i=r.status.toUpperCase(),c=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${c}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
765
|
+
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},qn;function Jn(e){return qn||(qn=new It(e)),qn}function Tl(e){let t=e.status.toUpperCase(),n=kl(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(`
|
|
766
|
+
`)}function kl(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 El(e){if(e.length===0)return"";let t=e.length===1?`
|
|
765
767
|
[BACKGROUND TASK COMPLETED]
|
|
766
768
|
`:`
|
|
767
769
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
768
|
-
`,n=e.map(o=>
|
|
770
|
+
`,n=e.map(o=>Tl(o)).join(`
|
|
769
771
|
|
|
770
772
|
`);return`${t}
|
|
771
773
|
${n}
|
|
772
|
-
`}function
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
`;break;case 114:
|
|
776
|
-
`),c++,l=o,i=14;switch(
|
|
777
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
778
|
-
`+" ".repeat(t))}," ":{"\n":new Array(
|
|
779
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
780
|
-
`+" ".repeat(t))}};var It;(function(e){e.DEFAULT={allowTrailingComma:!1}})(It||(It={}));function Si(e,t=[],n=It.DEFAULT){let o=null,r=[],s=[];function i(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return Oi(e,{onObjectBegin:()=>{let a={};i(a),s.push(r),r=a,o=null},onObjectProperty:a=>{o=a},onObjectEnd:()=>{r=s.pop()},onArrayBegin:()=>{let a=[];i(a),s.push(r),r=a,o=null},onArrayEnd:()=>{r=s.pop()},onLiteralValue:i,onError:(a,l,u)=>{t.push({error:a,offset:l,length:u})}},n),r[0]}function Oi(e,t,n=It.DEFAULT){let o=_t(e,!1),r=[],s=0;function i(g){return g?()=>s===0&&g(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(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 l(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 p=l(t.onObjectBegin),f=a(t.onObjectProperty),k=u(t.onObjectEnd),E=l(t.onArrayBegin),S=u(t.onArrayEnd),O=a(t.onLiteralValue),N=c(t.onSeparator),P=i(t.onComment),d=c(t.onError),w=n&&n.disallowComments,v=n&&n.allowTrailingComma;function y(){for(;;){let g=o.scan();switch(o.getTokenError()){case 4:m(14);break;case 5:m(15);break;case 3:m(13);break;case 1:w||m(11);break;case 2:m(12);break;case 6:m(16);break}switch(g){case 12:case 13:w?m(10):P();break;case 16:m(1);break;case 15:case 14:break;default:return g}}}function m(g,R=[],Qn=[]){if(d(g),R.length+Qn.length>0){let Ve=o.getToken();for(;Ve!==17;){if(R.indexOf(Ve)!==-1){y();break}else if(Qn.indexOf(Ve)!==-1)break;Ve=y()}}}function zn(g){let R=o.getTokenValue();return g?O(R):(f(R),r.push(R)),y(),!0}function Ci(){switch(o.getToken()){case 11:let g=o.getTokenValue(),R=Number(g);isNaN(R)&&(m(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 y(),!0}function Pi(){return o.getToken()!==10?(m(3,[],[2,5]),!1):(zn(!1),o.getToken()===6?(N(":"),y(),vt()||m(4,[],[2,5])):m(5,[],[2,5]),r.pop(),!0)}function Di(){p(),y();let g=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(g||m(4,[],[]),N(","),y(),o.getToken()===2&&v)break}else g&&m(6,[],[]);Pi()||m(4,[],[2,5]),g=!0}return k(),o.getToken()!==2?m(7,[2],[]):y(),!0}function Li(){E(),y();let g=!0,R=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(R||m(4,[],[]),N(","),y(),o.getToken()===4&&v)break}else R&&m(6,[],[]);g?(r.push(0),g=!1):r[r.length-1]++,vt()||m(4,[],[4,5]),R=!0}return S(),g||r.pop(),o.getToken()!==4?m(8,[4],[]):y(),!0}function vt(){switch(o.getToken()){case 3:return Li();case 1:return Di();case 10:return zn(!0);default:return Ci()}}return y(),o.getToken()===17?n.allowEmptyContent?!0:(m(4,[],[]),!1):vt()?(o.getToken()!==17&&m(9,[],[]),!0):(m(4,[],[]),!1)}var Ri;(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"})(Ri||(Ri={}));var _i;(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"})(_i||(_i={}));var Ai=Si;var Ii;(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"})(Ii||(Ii={}));var wl={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100}};function Nl(){let e=process.env.XDG_CONFIG_HOME??(0,We.join)((0,Ni.homedir)(),".config");return{user:(0,We.join)(e,"claude-olympus","config.jsonc"),project:(0,We.join)(process.cwd(),".claude","olympus.jsonc")}}function wi(e){if(!(0,wt.existsSync)(e))return null;try{let t=(0,wt.readFileSync)(e,"utf-8"),n=[],o=Ai(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 At(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]=At(s,r):r!==void 0&&(n[o]=r)}return n}function vl(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}if(process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),process.env.OLYMPUS_MAX_ASCENT_ITERATIONS){let t=parseInt(process.env.OLYMPUS_MAX_ASCENT_ITERATIONS,10);!isNaN(t)&&t>=10&&t<=1e3?e.ascent={...e.ascent,maxIterations:t}:isNaN(t)||console.warn(`Warning: OLYMPUS_MAX_ASCENT_ITERATIONS must be between 10 and 1000. Got: ${t}`)}return e}function vi(){let e=Nl(),t={...wl},n=wi(e.user);n&&(t=At(t,n));let o=wi(e.project);o&&(t=At(t,o));let r=vl();return t=At(t,r),t}function bl(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function xl(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 Cl(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function Pl(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function bi(e,t){let n=vi(),o=eo(e),r=bl(n),s=!0,i=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(xl(n,u.name)&&Pl(u.matcher,t.toolName))try{let p=await Cl(()=>u.handler({...t,toolInput:a,messages:l}),r);if(p===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}p.continue||(s=!1,c=p.stopReason),p.message&&i.push(p.message),p.hookSpecificOutput?.additionalContext&&i.push(p.hookSpecificOutput.additionalContext),p.modifiedInput!==void 0&&(a=p.modifiedInput),p.modifiedMessages!==void 0&&(l=p.modifiedMessages)}catch(p){console.error(`[hook-router] ${u.name} error:`,p)}return{continue:s,message:i.length>0?i.join(`
|
|
774
|
+
`}function yl(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let s=(n?.formatNotification??El)(o);return{hasNotifications:!0,tasks:o,message:s}}function yi(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Jn(),r=yl(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function Si(){g({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 yi(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var zn=null,Xn=!1;async function Sl(){if(!Xn)try{let{encode:e}=await import("gpt-tokenizer");zn=e,Xn=!0}catch{Xn=!0}}function Ol(e){return Math.ceil(e.length/4)}async function me(e){if(!e||e.length===0)return 0;await Sl();try{if(zn)return zn(e).length}catch{}return Ol(e)}async function Oi(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return me(n.content);if("output"in n&&typeof n.output=="string")return me(n.output);if("text"in n&&typeof n.text=="string")return me(n.text);if("result"in n&&typeof n.result=="string")return me(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return me(t)}var Qn=[{model_pattern:"claude-opus",input_per_million:15,output_per_million:75,effective_date:"2025-01-01"},{model_pattern:"claude-sonnet",input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},{model_pattern:"claude-haiku",input_per_million:.25,output_per_million:1.25,effective_date:"2025-01-01"}];function _i(e,t,n,o=Qn){let r=o.find(c=>new RegExp(c.model_pattern,"i").test(n));if(!r){let c=o.find(u=>u.model_pattern==="claude-sonnet")||{input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},a=e/1e6*c.input_per_million,l=t/1e6*c.output_per_million;return{inputCost:a,outputCost:l,totalCost:a+l,pricingVersion:c.effective_date}}let s=e/1e6*r.input_per_million,i=t/1e6*r.output_per_million;return{inputCost:s,outputCost:i,totalCost:s+i,pricingVersion:r.effective_date}}var Ii=require("crypto");function _l(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 Ri(e,t=1e4){return e.token_budget||(e.token_budget={session_baseline:t,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e}function Ai(){g({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=_l(e);if(!t)return{continue:!0};let n=await me(t),o=D(e.directory,e.sessionId);Ri(o),o.token_budget&&(o.token_budget.current_usage+=n,P(e.directory,o))}catch(t){console.error("[Olympus Learning Capture] Error in prompt handler:",t)}return{continue:!0}}}),g({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{try{if(!e.directory||!e.toolName)return{continue:!0};let t=e.toolOutput?await Oi(e.toolOutput):0,n=D(e.directory,e.sessionId);Ri(n),n.token_budget&&(n.token_budget.current_usage+=t,P(e.directory,n))}catch(t){console.error("[Olympus Learning Capture] Error in tool use handler:",t)}return{continue:!0}}}),g({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=D(e.directory,e.sessionId);if(!t.token_budget)return{continue:!0};let n=t.token_budget.current_usage;if(n===0)return{continue:!0};let o="unknown",r={input_tokens:0,output_tokens:0,total_tokens:n,estimated:!0,model:o},s={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let c=_i(0,n,o);s.input_cost=c.inputCost,s.output_cost=c.outputCost,s.total_cost=c.totalCost,s.pricing_version=c.pricingVersion}catch{}let i={id:(0,Ii.randomUUID)(),timestamp:new Date().toISOString(),session_id:t.session_id,project_path:e.directory,event_type:"success",user_message:"Session completed",feedback_category:"praise",confidence:.5,token_usage:r,cost_estimate:s,agent_used:t.pending_completion?.agent_used,original_task:t.pending_completion?.task_description};if(oe(i),t.pending_completion?.agent_used){let c=Fo();$o(t.pending_completion.agent_used,c)}t.token_budget.current_usage=0,t.token_budget.warning_issued=!1,t.token_budget.started_at=new Date().toISOString(),P(e.directory,t)}catch(t){console.error("[Olympus Learning Capture] Error in stop handler:",t)}return{continue:!0}}})}function bi(){g({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=D(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let o=e.toolOutput;o.token_usage&&typeof o.token_usage=="object"&&(n=o.token_usage.total_tokens??0)}if(n>0&&Jo(t,n),zo(t)){let o=t.token_budget,r=(o.current_usage/1e3).toFixed(1),s=(o.session_baseline/1e3).toFixed(0),i=(o.current_usage/o.session_baseline).toFixed(2);return Xo(t),P(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${i}x baseline of ${s}k).
|
|
775
|
+
This is informational - continue if task requires it.
|
|
776
|
+
Consider: delegate to subagent, break into smaller tasks.`}}return P(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}var wi=!1;function vi(){wi||(or(),pr(),xr(),Os(),ti(),ki(),Si(),Ai(),bi(),wi=!0)}var vt=require("fs"),ji=require("os"),Ke=require("path");function At(e,t=!1){let n=e.length,o=0,r="",s=0,i=16,c=0,a=0,l=0,u=0,d=0;function f(p,I){let N=0,y=0;for(;N<p||!I;){let m=e.charCodeAt(o);if(m>=48&&m<=57)y=y*16+m-48;else if(m>=65&&m<=70)y=y*16+m-65+10;else if(m>=97&&m<=102)y=y*16+m-97+10;else break;o++,N++}return N<p&&(y=-1),y}function E(p){o=p,r="",s=0,i=16,d=0}function S(){let p=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&we(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&we(e.charCodeAt(o)))for(o++;o<e.length&&we(e.charCodeAt(o));)o++;else return d=3,e.substring(p,o);let I=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&&we(e.charCodeAt(o))){for(o++;o<e.length&&we(e.charCodeAt(o));)o++;I=o}else d=3;return e.substring(p,I)}function O(){let p="",I=o;for(;;){if(o>=n){p+=e.substring(I,o),d=2;break}let N=e.charCodeAt(o);if(N===34){p+=e.substring(I,o),o++;break}if(N===92){if(p+=e.substring(I,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+=`
|
|
777
|
+
`;break;case 114:p+="\r";break;case 116:p+=" ";break;case 117:let m=f(4,!0);m>=0?p+=String.fromCharCode(m):d=4;break;default:d=5}I=o;continue}if(N>=0&&N<=31)if(Ve(N)){p+=e.substring(I,o),d=2;break}else d=6;o++}return p}function R(){if(r="",d=0,s=o,a=c,u=l,o>=n)return s=n,i=17;let p=e.charCodeAt(o);if(Zn(p)){do o++,r+=String.fromCharCode(p),p=e.charCodeAt(o);while(Zn(p));return i=15}if(Ve(p))return o++,r+=String.fromCharCode(p),p===13&&e.charCodeAt(o)===10&&(o++,r+=`
|
|
778
|
+
`),c++,l=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=O(),i=10;case 47:let I=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Ve(e.charCodeAt(o));)o++;return r=e.substring(I,o),i=12}if(e.charCodeAt(o+1)===42){o+=2;let N=n-1,y=!1;for(;o<N;){let m=e.charCodeAt(o);if(m===42&&e.charCodeAt(o+1)===47){o+=2,y=!0;break}o++,Ve(m)&&(m===13&&e.charCodeAt(o)===10&&o++,c++,l=o)}return y||(o++,d=1),r=e.substring(I,o),i=13}return r+=String.fromCharCode(p),o++,i=16;case 45:if(r+=String.fromCharCode(p),o++,o===n||!we(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+=S(),i=11;default:for(;o<n&&h(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 h(p){if(Zn(p)||Ve(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 _(){let p;do p=R();while(p>=12&&p<=15);return p}return{setPosition:E,getPosition:()=>o,scan:t?_:R,getToken:()=>i,getTokenValue:()=>r,getTokenOffset:()=>s,getTokenLength:()=>o-s,getTokenStartLine:()=>a,getTokenStartCharacter:()=>s-u,getTokenError:()=>d}}function Zn(e){return e===32||e===9}function Ve(e){return e===10||e===13}function we(e){return e>=48&&e<=57}var Ni;(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"})(Ni||(Ni={}));var Il=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),ve=200,Al={" ":{"\n":new Array(ve).fill(0).map((e,t)=>`
|
|
779
|
+
`+" ".repeat(t)),"\r":new Array(ve).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(ve).fill(0).map((e,t)=>`\r
|
|
780
|
+
`+" ".repeat(t))}," ":{"\n":new Array(ve).fill(0).map((e,t)=>`
|
|
781
|
+
`+" ".repeat(t)),"\r":new Array(ve).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(ve).fill(0).map((e,t)=>`\r
|
|
782
|
+
`+" ".repeat(t))}};var bt;(function(e){e.DEFAULT={allowTrailingComma:!1}})(bt||(bt={}));function Ci(e,t=[],n=bt.DEFAULT){let o=null,r=[],s=[];function i(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return xi(e,{onObjectBegin:()=>{let a={};i(a),s.push(r),r=a,o=null},onObjectProperty:a=>{o=a},onObjectEnd:()=>{r=s.pop()},onArrayBegin:()=>{let a=[];i(a),s.push(r),r=a,o=null},onArrayEnd:()=>{r=s.pop()},onLiteralValue:i,onError:(a,l,u)=>{t.push({error:a,offset:l,length:u})}},n),r[0]}function xi(e,t,n=bt.DEFAULT){let o=At(e,!1),r=[],s=0;function i(T){return T?()=>s===0&&T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(T){return T?b=>s===0&&T(b,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(T){return T?b=>s===0&&T(b,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(T){return T?()=>{s>0?s++:T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(s=1)}:()=>!0}function u(T){return T?()=>{s>0&&s--,s===0&&T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=a(t.onObjectProperty),E=u(t.onObjectEnd),S=l(t.onArrayBegin),O=u(t.onArrayEnd),R=a(t.onLiteralValue),h=c(t.onSeparator),_=i(t.onComment),p=c(t.onError),I=n&&n.disallowComments,N=n&&n.allowTrailingComma;function y(){for(;;){let T=o.scan();switch(o.getTokenError()){case 4:m(14);break;case 5:m(15);break;case 3:m(13);break;case 1:I||m(11);break;case 2:m(12);break;case 6:m(16);break}switch(T){case 12:case 13:I?m(10):_();break;case 16:m(1);break;case 15:case 14:break;default:return T}}}function m(T,b=[],eo=[]){if(p(T),b.length+eo.length>0){let qe=o.getToken();for(;qe!==17;){if(b.indexOf(qe)!==-1){y();break}else if(eo.indexOf(qe)!==-1)break;qe=y()}}}function ge(T){let b=o.getTokenValue();return T?R(b):(f(b),r.push(b)),y(),!0}function Ne(){switch(o.getToken()){case 11:let T=o.getTokenValue(),b=Number(T);isNaN(b)&&(m(2),b=0),R(b);break;case 7:R(null);break;case 8:R(!0);break;case 9:R(!1);break;default:return!1}return y(),!0}function Gi(){return o.getToken()!==10?(m(3,[],[2,5]),!1):(ge(!1),o.getToken()===6?(h(":"),y(),Ct()||m(4,[],[2,5])):m(5,[],[2,5]),r.pop(),!0)}function Bi(){d(),y();let T=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(T||m(4,[],[]),h(","),y(),o.getToken()===2&&N)break}else T&&m(6,[],[]);Gi()||m(4,[],[2,5]),T=!0}return E(),o.getToken()!==2?m(7,[2],[]):y(),!0}function Yi(){S(),y();let T=!0,b=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(b||m(4,[],[]),h(","),y(),o.getToken()===4&&N)break}else b&&m(6,[],[]);T?(r.push(0),T=!1):r[r.length-1]++,Ct()||m(4,[],[4,5]),b=!0}return O(),T||r.pop(),o.getToken()!==4?m(8,[4],[]):y(),!0}function Ct(){switch(o.getToken()){case 3:return Yi();case 1:return Bi();case 10:return ge(!0);default:return Ne()}}return y(),o.getToken()===17?n.allowEmptyContent?!0:(m(4,[],[]),!1):Ct()?(o.getToken()!==17&&m(9,[],[]),!0):(m(4,[],[]),!1)}var Pi;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(Pi||(Pi={}));var Li;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(Li||(Li={}));var Mi=Ci;var Di;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(Di||(Di={}));var Ll={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100},learning:{tokenMetrics:{enabled:!0,warningThreshold:1.5,minimumSamples:5,injectionTokenBudget:150,sessionBaseline:1e4}},pricing:{models:Qn,customPricing:[]}};function Dl(){let e=process.env.XDG_CONFIG_HOME??(0,Ke.join)((0,ji.homedir)(),".config");return{user:(0,Ke.join)(e,"claude-olympus","config.jsonc"),project:(0,Ke.join)(process.cwd(),".claude","olympus.jsonc")}}function Ui(e){if(!(0,vt.existsSync)(e))return null;try{let t=(0,vt.readFileSync)(e,"utf-8"),n=[],o=Mi(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),o}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function wt(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],s=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[o]=wt(s,r):r!==void 0&&(n[o]=r)}return n}function Ml(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}if(process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),process.env.OLYMPUS_MAX_ASCENT_ITERATIONS){let t=parseInt(process.env.OLYMPUS_MAX_ASCENT_ITERATIONS,10);!isNaN(t)&&t>=10&&t<=1e3?e.ascent={...e.ascent,maxIterations:t}:isNaN(t)||console.warn(`Warning: OLYMPUS_MAX_ASCENT_ITERATIONS must be between 10 and 1000. Got: ${t}`)}return e}function Fi(){let e=Dl(),t={...Ll},n=Ui(e.user);n&&(t=wt(t,n));let o=Ui(e.project);o&&(t=wt(t,o));let r=Ml();return t=wt(t,r),t}function Ul(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function jl(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let o=n[t];if(typeof o=="object"&&o!==null){let r=o.enabled;if(typeof r=="boolean")return r}}return!0}async function Fl(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function $l(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function $i(e,t){let n=Fi(),o=no(e),r=Ul(n),s=!0,i=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(jl(n,u.name)&&$l(u.matcher,t.toolName))try{let d=await Fl(()=>u.handler({...t,toolInput:a,messages:l}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(s=!1,c=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(a=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:s,message:i.length>0?i.join(`
|
|
781
783
|
|
|
782
784
|
---
|
|
783
785
|
|
|
784
|
-
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}
|
|
786
|
+
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}vi();async function Hl(){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 Hi(){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 Hl(),r;try{r=JSON.parse(o)}catch{r={}}let s=await $i(n,r);console.log(JSON.stringify(s)),process.exit(0)}var Nt=process.argv[1]||"",Gl=Nt.endsWith("entry.ts")||Nt.endsWith("entry.js")||Nt.endsWith("olympus-hooks.mjs")||Nt.includes("olympus-hooks");Gl&&Hi().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|