olympus-ai 3.2.3 → 3.3.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/plugin.json +1 -1
- package/dist/__tests__/ascent-checkpoint.test.d.ts +2 -0
- package/dist/__tests__/ascent-checkpoint.test.d.ts.map +1 -0
- package/dist/__tests__/ascent-checkpoint.test.js +261 -0
- package/dist/__tests__/ascent-checkpoint.test.js.map +1 -0
- package/dist/__tests__/config-ascent.test.d.ts +2 -0
- package/dist/__tests__/config-ascent.test.d.ts.map +1 -0
- package/dist/__tests__/config-ascent.test.js +134 -0
- package/dist/__tests__/config-ascent.test.js.map +1 -0
- package/dist/__tests__/hook-blocking.test.d.ts +8 -0
- package/dist/__tests__/hook-blocking.test.d.ts.map +1 -0
- package/dist/__tests__/hook-blocking.test.js +277 -0
- package/dist/__tests__/hook-blocking.test.js.map +1 -0
- package/dist/__tests__/installer.test.js +1 -1
- package/dist/__tests__/metrics-cli.test.d.ts +5 -0
- package/dist/__tests__/metrics-cli.test.d.ts.map +1 -0
- package/dist/__tests__/metrics-cli.test.js +24 -0
- package/dist/__tests__/metrics-cli.test.js.map +1 -0
- package/dist/__tests__/skill-auto-detection.test.d.ts +2 -0
- package/dist/__tests__/skill-auto-detection.test.d.ts.map +1 -0
- package/dist/__tests__/skill-auto-detection.test.js +255 -0
- package/dist/__tests__/skill-auto-detection.test.js.map +1 -0
- package/dist/__tests__/token-estimator.test.d.ts +5 -0
- package/dist/__tests__/token-estimator.test.d.ts.map +1 -0
- package/dist/__tests__/token-estimator.test.js +192 -0
- package/dist/__tests__/token-estimator.test.js.map +1 -0
- package/dist/agents/definitions.d.ts.map +1 -1
- package/dist/agents/definitions.js +83 -1
- package/dist/agents/definitions.js.map +1 -1
- package/dist/agents/document-writer.d.ts.map +1 -1
- package/dist/agents/document-writer.js +38 -0
- package/dist/agents/document-writer.js.map +1 -1
- package/dist/agents/frontend-engineer.d.ts.map +1 -1
- package/dist/agents/frontend-engineer.js +16 -0
- package/dist/agents/frontend-engineer.js.map +1 -1
- package/dist/agents/olympian.d.ts.map +1 -1
- package/dist/agents/olympian.js +15 -0
- package/dist/agents/olympian.js.map +1 -1
- package/dist/cli/commands/metrics.d.ts +31 -0
- package/dist/cli/commands/metrics.d.ts.map +1 -0
- package/dist/cli/commands/metrics.js +266 -0
- package/dist/cli/commands/metrics.js.map +1 -0
- package/dist/cli/index.js +39 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +16 -0
- package/dist/config/loader.js.map +1 -1
- package/dist/features/ascent-checkpoint/index.d.ts +48 -0
- package/dist/features/ascent-checkpoint/index.d.ts.map +1 -0
- package/dist/features/ascent-checkpoint/index.js +144 -0
- package/dist/features/ascent-checkpoint/index.js.map +1 -0
- package/dist/features/hook-logging/index.d.ts +37 -0
- package/dist/features/hook-logging/index.d.ts.map +1 -0
- package/dist/features/hook-logging/index.js +120 -0
- package/dist/features/hook-logging/index.js.map +1 -0
- package/dist/features/hook-logging/index.test.d.ts +5 -0
- package/dist/features/hook-logging/index.test.d.ts.map +1 -0
- package/dist/features/hook-logging/index.test.js +268 -0
- package/dist/features/hook-logging/index.test.js.map +1 -0
- package/dist/features/index.d.ts +3 -0
- package/dist/features/index.d.ts.map +1 -1
- package/dist/features/index.js +8 -0
- package/dist/features/index.js.map +1 -1
- package/dist/features/magic-keywords.d.ts +51 -0
- package/dist/features/magic-keywords.d.ts.map +1 -1
- package/dist/features/magic-keywords.js +172 -0
- package/dist/features/magic-keywords.js.map +1 -1
- package/dist/features/session-state/index.d.ts +50 -0
- package/dist/features/session-state/index.d.ts.map +1 -0
- package/dist/features/session-state/index.js +64 -0
- package/dist/features/session-state/index.js.map +1 -0
- package/dist/features/session-state/index.test.d.ts +5 -0
- package/dist/features/session-state/index.test.d.ts.map +1 -0
- package/dist/features/session-state/index.test.js +221 -0
- package/dist/features/session-state/index.test.js.map +1 -0
- package/dist/features/token-metrics/index.d.ts +6 -0
- package/dist/features/token-metrics/index.d.ts.map +1 -0
- package/dist/features/token-metrics/index.js +5 -0
- package/dist/features/token-metrics/index.js.map +1 -0
- package/dist/features/token-metrics/storage.d.ts +16 -0
- package/dist/features/token-metrics/storage.d.ts.map +1 -0
- package/dist/features/token-metrics/storage.js +144 -0
- package/dist/features/token-metrics/storage.js.map +1 -0
- package/dist/features/token-metrics/token-estimator.d.ts +66 -0
- package/dist/features/token-metrics/token-estimator.d.ts.map +1 -0
- package/dist/features/token-metrics/token-estimator.js +230 -0
- package/dist/features/token-metrics/token-estimator.js.map +1 -0
- package/dist/features/token-metrics/types.d.ts +63 -0
- package/dist/features/token-metrics/types.d.ts.map +1 -0
- package/dist/features/token-metrics/types.js +5 -0
- package/dist/features/token-metrics/types.js.map +1 -0
- package/dist/hooks/olympus-orchestrator/constants.d.ts +2 -0
- package/dist/hooks/olympus-orchestrator/constants.d.ts.map +1 -1
- package/dist/hooks/olympus-orchestrator/constants.js +41 -0
- package/dist/hooks/olympus-orchestrator/constants.js.map +1 -1
- package/dist/hooks/olympus-orchestrator/index.d.ts +10 -1
- package/dist/hooks/olympus-orchestrator/index.d.ts.map +1 -1
- package/dist/hooks/olympus-orchestrator/index.js +108 -14
- package/dist/hooks/olympus-orchestrator/index.js.map +1 -1
- package/dist/hooks/registrations/index.d.ts +2 -1
- package/dist/hooks/registrations/index.d.ts.map +1 -1
- package/dist/hooks/registrations/index.js +3 -1
- package/dist/hooks/registrations/index.js.map +1 -1
- package/dist/hooks/registrations/token-metrics.d.ts +11 -0
- package/dist/hooks/registrations/token-metrics.d.ts.map +1 -0
- package/dist/hooks/registrations/token-metrics.js +119 -0
- package/dist/hooks/registrations/token-metrics.js.map +1 -0
- package/dist/installer/index.d.ts +1 -1
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +334 -9
- package/dist/installer/index.js.map +1 -1
- package/dist/shared/types.d.ts +16 -0
- package/dist/shared/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/scripts/.olympus/token-metrics.jsonl +1 -0
- package/scripts/dist/hooks/olympus-hooks.cjs +127 -128
- package/scripts/esbuild.hooks.mjs +1 -1
- package/.claude/CLAUDE.md +0 -66
- package/scripts/generate-logo-hybrid-v2.mjs +0 -213
- package/scripts/generate-logo-hybrid.mjs +0 -209
- package/scripts/generate-logo-infinity.mjs +0 -239
- package/scripts/generate-logo-mythology.mjs +0 -190
- package/scripts/generate-logo-orchestration.mjs +0 -228
- package/scripts/generate-logo-recraft.mjs +0 -147
- package/scripts/generate-logo-simple.mjs +0 -154
- package/scripts/generate-logo.mjs +0 -117
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
`)){let
|
|
3
|
+
"use strict";var Mi=Object.create;var Ke=Object.defineProperty;var Ui=Object.getOwnPropertyDescriptor;var ji=Object.getOwnPropertyNames;var $i=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty;var Hi=(e,t)=>{for(var n in t)Ke(e,n,{get:t[n],enumerable:!0})},Zn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ji(t))!Fi.call(e,r)&&r!==n&&Ke(e,r,{get:()=>t[r],enumerable:!(o=Ui(t,r))||o.enumerable});return e};var oe=(e,t,n)=>(n=e!=null?Mi($i(e)):{},Zn(t||!e||!e.__esModule?Ke(n,"default",{value:e,enumerable:!0}):n,e)),Gi=e=>Zn(Ke({},"__esModule",{value:!0}),e);var Ml={};Hi(Ml,{main:()=>xi});module.exports=Gi(Ml);var bt=new Map;function h(e){let t=bt.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),bt.set(e.event,t)}function eo(e){return bt.get(e)||[]}var Bi={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},Yi=["ultrawork","ultrathink","olympus","search","analyze"];function to(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function no(e,t){let n=[];for(let o of Yi){let r=Bi[o],s=e.match(r);s&&s.index!==void 0&&n.push({type:o,keyword:s[0],position:s.index})}return n}var oo="auto-slash-command",Je="<auto-slash-command>",qe="</auto-slash-command>",ro=/^\/([a-zA-Z][\w-]*)\s*(.*)/,so=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Wi=/```[\s\S]*?```/g;function io(e){return e.replace(Wi,"")}function ao(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(ro);if(!n)return null;let[o,r,s]=n;return{command:r.toLowerCase(),args:s.trim(),raw:o}}function co(e){return so.has(e.toLowerCase())}function xt(e){let n=io(e).trim();if(!n.startsWith("/"))return null;let o=ao(n);return!o||co(o.command)?null:o}function Ct(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var V=require("fs"),q=require("path"),po=require("os"),lo=(0,q.join)((0,po.homedir)(),".claude");function fo(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 uo(e,t){if(!(0,V.existsSync)(e))return[];let n;try{n=(0,V.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let s=(0,q.join)(e,r.name),i=(0,q.basename)(r.name,".md");try{let c=(0,V.readFileSync)(s,"utf-8"),{data:a,body:l}=fo(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 Pt(){let e=(0,q.join)(lo,"commands"),t=(0,q.join)(process.cwd(),".claude","commands"),n=(0,q.join)(lo,"skills"),o=uo(e,"user"),r=uo(t,"project"),s=[];if((0,V.existsSync)(n))try{let i=(0,V.readdirSync)(n,{withFileTypes:!0});for(let c of i){if(!c.isDirectory())continue;let a=(0,q.join)(n,c.name,"SKILL.md");if((0,V.existsSync)(a))try{let l=(0,V.readFileSync)(a,"utf-8"),{data:u,body:p}=fo(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:p,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...s]}function Xe(e){return Pt().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function Vi(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function Ki(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=Vi(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 Dt(e){let t=Xe(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:Ki(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function Lt(){return Pt().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var ze=new Set;function mo(){return{name:oo,processMessage:(e,t)=>{let n=Ct(t);if(n.includes(Je)||n.includes(qe))return{detected:!1};let o=xt(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=Dt(o);if(s.success&&s.replacementText){let c=`${Je}
|
|
17
17
|
${s.replacementText}
|
|
18
|
-
${
|
|
18
|
+
${qe}`;return{detected:!0,parsedCommand:o,injectedMessage:c}}let i=`${Je}
|
|
19
19
|
[AUTO-SLASH-COMMAND ERROR]
|
|
20
20
|
${s.error}
|
|
21
21
|
|
|
22
22
|
Original input: ${o.raw}
|
|
23
|
-
${
|
|
23
|
+
${qe}`;return{detected:!0,parsedCommand:o,injectedMessage:i}},listCommands:()=>Lt(),findCommand:e=>Xe(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 Ji=[/\bultrathink\b/i,/\bthink\b/i],qi=["\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"],Xi=qi.map(e=>new RegExp(e,"i")),zi=[...Ji,...Xi],Qi=/```[\s\S]*?```/g,Zi=/`[^`]+`/g;function ea(e){return e.replace(Qi,"").replace(Zi,"")}function go(e){let t=ea(e);return zi.some(n=>n.test(t))}function ho(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function Mt(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function Ut(e){return e.replace(/\.(\d+)/g,"-$1")}var To={"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"},ko=new Set(Object.values(To)),Eo={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"}},ta={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 yo(e){let t=Ut(e),{prefix:n,base:o}=Mt(t);if(ko.has(o)||o.endsWith("-high"))return null;let r=To[o];return r?n+r:null}function jt(e){let t=Ut(e),{base:n}=Mt(t);return ko.has(n)||n.endsWith("-high")}function na(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 oa(e){return e in Eo}function So(e,t){let n=Ut(t),{base:o}=Mt(n);if(jt(n))return null;let r=na(e,t);if(!oa(r))return null;let s=Eo[r],i=ta[r];if(!i)return null;let c=o.toLowerCase();return i.some(l=>c.includes(l.toLowerCase()))?s:null}var Z=new Map;function ra(e){Z.delete(e)}function Oo(){return{processChatParams:(e,t)=>{let n=ho(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!go(n))return Z.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,jt(r.modelId)))return Z.set(e,o),o;let s=yo(r.modelId),i=So(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),Z.set(e,o),o},onSessionDeleted:e=>{Z.delete(e)},isRequested:e=>Z.get(e)?.requested??!1,getState:e=>Z.get(e),clear:ra}}var _=require("fs"),de=require("path"),$t=require("os");function Ft(e){let t=e||process.cwd(),n=(0,de.join)(t,".olympus");return(0,de.join)(n,"ultrawork-state.json")}function Ht(){return(0,de.join)((0,$t.homedir)(),".claude","ultrawork-state.json")}function sa(e){let t=e||process.cwd(),n=(0,de.join)(t,".olympus");(0,_.existsSync)(n)||(0,_.mkdirSync)(n,{recursive:!0})}function ia(){let e=(0,de.join)((0,$t.homedir)(),".claude");(0,_.existsSync)(e)||(0,_.mkdirSync)(e,{recursive:!0})}function re(e){let t=Ft(e);if((0,_.existsSync)(t))try{let o=(0,_.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Ht();if((0,_.existsSync)(n))try{let o=(0,_.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Ro(e,t){try{sa(t);let n=Ft(t);(0,_.writeFileSync)(n,JSON.stringify(e,null,2)),ia();let o=Ht();return(0,_.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function _o(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 Ro(o,n)}function Io(e){let t=Ft(e);if((0,_.existsSync)(t))try{(0,_.unlinkSync)(t)}catch{}let n=Ht();if((0,_.existsSync)(n))try{return(0,_.unlinkSync)(n),!0}catch{return!1}return!0}function Ao(e){let t=re(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Ro(t,e)?t:null)}function wo(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
|
|
44
|
+
`}var No=require("os"),b=require("path");function K(){return process.platform==="win32"}function aa(){return(0,b.join)((0,No.homedir)(),".claude")}function D(){return(0,b.join)(aa(),"hooks")}var vo=`<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
|
+
`,bo=`<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 xo=`<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
|
+
`,Co=`<analyze-mode>
|
|
162
162
|
ANALYSIS MODE. Gather context before diving deep:
|
|
163
163
|
|
|
164
164
|
CONTEXT GATHERING (parallel):
|
|
@@ -174,15 +174,15 @@ SYNTHESIZE findings before proceeding.
|
|
|
174
174
|
|
|
175
175
|
---
|
|
176
176
|
|
|
177
|
-
`,
|
|
177
|
+
`,Po=`[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 lu={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:K()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:K()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:K()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},uu={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:K()?`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:K()?`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:K()?`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:K()?`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:K()?`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:K()?`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:K()?`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,b.join)(D(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};var $o=require("path");var Do=require("os"),se=require("path"),I=require("fs"),ca=require("crypto"),la=1e4;function ie(){return(0,se.join)((0,Do.homedir)(),".claude","olympus","learning")}function Ne(e){return(0,se.join)(e,".olympus","learning")}function Lo(e){let t=ie();if((0,I.existsSync)(t)||(0,I.mkdirSync)(t,{recursive:!0}),e){let n=Ne(e);(0,I.existsSync)(n)||(0,I.mkdirSync)(n,{recursive:!0})}}function Mo(e,t=la){if((0,I.existsSync)(e))try{let o=(0,I.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,I.renameSync)(e,s),console.log(`[Olympus Learning] Archived ${o} entries to ${s}`)}}catch(n){console.error(`[Olympus Learning] Failed to rotate ${e}:`,n)}}function fe(e){Lo();let t=(0,se.join)(ie(),"feedback-log.jsonl");Mo(t),(0,I.appendFileSync)(t,JSON.stringify(e)+`
|
|
185
|
+
`,"utf-8")}function me(e,t){if(!(0,I.existsSync)(e))return t;try{return JSON.parse((0,I.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function Uo(e,t){try{let n=(0,se.dirname)(e);n&&!(0,I.existsSync)(n)&&(0,I.mkdirSync)(n,{recursive:!0}),(0,I.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}var Fo=require("crypto"),ua=10,pa=1800*1e3;function Ho(e){return(0,$o.join)(e,".olympus","session-state.json")}function jo(e){return{session_id:e||(0,Fo.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null}}function ge(e,t){let n=Ho(e),o=me(n,null);if(!o)return jo(t);let r=new Date(o.last_updated).getTime();return Date.now()-r>pa?jo(t):o}function he(e,t){let n=Ho(e);t.last_updated=new Date().toISOString(),Uo(n,t)}function Go(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,ua),e.last_updated=new Date().toISOString(),e}function Bo(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Qe(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}var Yo=require("crypto"),da={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 Gt(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(da))for(let{regex:s,confidence:i}of r)s.test(t)&&(!n||i>n.confidence)&&(n={category:o,confidence:i});return n}async function Wo(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=ge(n,o),s=Gt(t),i=Go(r,t,s?.category);if(s&&Qe(r)){let c={id:(0,Yo.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};fe(c)}he(n,i)}var Vo=require("crypto");async function Ko(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=ge(n,o);if(!Qe(r))return;let s=Gt(t),i=s?.category==="praise"&&s.confidence>.7,c=fa(t,r.pending_completion?.task_description||"");if(i||c){let a={id:(0,Vo.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};fe(a);let l=Bo(r);he(n,l)}}function fa(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 Jo(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function qo(){h({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=Jo(e);if(!t)return{continue:!0};let n=to(t),o=no(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?(_o(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:vo}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:bo}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:xo}}:c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Co}}:{continue:!0}}}),h({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=mo().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),h({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Oo(),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}}}),h({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=Jo(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Wo({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Ko({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var ae=require("fs"),ee=require("path"),Xo=require("os");function ma(e,t){let n=(0,ee.join)((0,Xo.homedir)(),".claude"),o=[];e&&(o.push((0,ee.join)(n,"sessions",e,"todos.json")),o.push((0,ee.join)(n,"todos",`${e}.json`))),t&&(o.push((0,ee.join)(t,".olympus","todos.json")),o.push((0,ee.join)(t,".claude","todos.json")));let r=(0,ee.join)(n,"todos");if((0,ae.existsSync)(r))try{let s=(0,ae.readdirSync)(r);for(let i of s)i.endsWith(".json")&&o.push((0,ee.join)(r,i))}catch{}return o}function ga(e){try{let t=(0,ae.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 ha(e){return e.status!=="completed"&&e.status!=="cancelled"}async function ve(e,t){let n=ma(e,t),o=new Set,r=[],s=[];for(let i of n){if(!(0,ae.existsSync)(i))continue;let c=ga(i);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),ha(a)&&s.push(a))}}return{count:s.length,todos:s,total:r.length}}function zo(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var Ze=require("path");var Qo=500;function Zo(e){let t=me((0,Ze.join)(ie(),"user-preferences.json"),null),n=me((0,Ze.join)(Ne(e),"patterns.json"),null),o=me((0,Ze.join)(ie(),"agent-performance.json"),{}),r=[];t&&Ta(t)&&r.push(ka(t)),n&&n.conventions.length>0&&r.push(Ea(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(ya(t.recurring_corrections.slice(0,5)));let s=Object.values(o).filter(c=>c.weak_areas.length>0);if(s.length>0&&r.push(Sa(s)),r.length===0)return"";let i=`<learned-context>
|
|
186
186
|
|
|
187
187
|
${r.join(`
|
|
188
188
|
|
|
@@ -192,20 +192,20 @@ ${r.join(`
|
|
|
192
192
|
|
|
193
193
|
---
|
|
194
194
|
|
|
195
|
-
`;return i.length>
|
|
195
|
+
`;return i.length>Qo*4?i.substring(0,Qo*4)+`
|
|
196
196
|
...</learned-context>
|
|
197
197
|
|
|
198
198
|
---
|
|
199
199
|
|
|
200
|
-
`:i}function
|
|
201
|
-
`)}function
|
|
202
|
-
`)}function
|
|
203
|
-
`)}function
|
|
204
|
-
`)}function
|
|
205
|
-
`)}var
|
|
206
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function
|
|
200
|
+
`:i}function Ta(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function ka(e){let t=["## User Preferences"];e.verbosity!=="unknown"&&t.push(`- Verbosity: ${e.verbosity}`),e.autonomy!=="unknown"&&t.push(`- Autonomy: ${e.autonomy}`);for(let n of e.explicit_rules.slice(0,5))t.push(`- ${n}`);return t.join(`
|
|
201
|
+
`)}function Ea(e){let t=["## Project Conventions"];for(let n of e.conventions.slice(0,5))t.push(`- ${n}`);return e.tech_stack.length>0&&t.push(`- Tech: ${e.tech_stack.join(", ")}`),t.join(`
|
|
202
|
+
`)}function ya(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
|
|
203
|
+
`)}function Sa(e){let t=["## Agent Notes"];for(let n of e.slice(0,3))t.push(`- ${n.agent_name}: struggles with ${n.weak_areas.join(", ")}`);return t.join(`
|
|
204
|
+
`)}function er(e){if(e.length===0)return"";let t=["## Agent Discoveries"];t.push(""),t.push("These insights were discovered during previous work:"),t.push("");for(let n of e.slice(0,5))t.push(`- **${n.category}**: ${n.summary}`),t.push(` ${n.details.substring(0,200)}`);return t.join(`
|
|
205
|
+
`)}var et=require("path"),ce=require("fs"),Oa=require("crypto");function Ra(e){let t=(0,et.join)(ie(),"discoveries.jsonl"),n=Ne(e),o=(0,et.join)(n,"discoveries.jsonl"),r=tr(t),s=tr(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 nr(e,t=10){let n=Ra(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 tr(e){if(!(0,ce.existsSync)(e))return[];try{return(0,ce.readFileSync)(e,"utf-8").split(`
|
|
206
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function or(){h({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Zo(e.directory),n=nr(e.directory,5),o=er(n),r=t+(o?`
|
|
207
207
|
|
|
208
|
-
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),
|
|
208
|
+
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),h({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[],r=re(n);r?.active&&o.push(`<session-restore>
|
|
209
209
|
|
|
210
210
|
[ULTRAWORK MODE RESTORED]
|
|
211
211
|
|
|
@@ -218,7 +218,7 @@ Continue working in ultrawork mode until all tasks are complete.
|
|
|
218
218
|
|
|
219
219
|
---
|
|
220
220
|
|
|
221
|
-
`);let s=await
|
|
221
|
+
`);let s=await ve(t,n);return s.count>0&&o.push(`<session-restore>
|
|
222
222
|
|
|
223
223
|
[PENDING TASKS DETECTED]
|
|
224
224
|
|
|
@@ -230,7 +230,7 @@ Please continue working on these tasks.
|
|
|
230
230
|
---
|
|
231
231
|
|
|
232
232
|
`),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
|
|
233
|
-
`)}}:{continue:!0}}})}var
|
|
233
|
+
`)}}:{continue:!0}}})}var Ee=require("fs"),X=require("path"),zt=require("os");var L=require("fs"),te=require("path"),rr=require("os");function Bt(e){let t=(0,te.join)(e,".olympus");return(0,te.join)(t,"ascent-state.json")}function _a(e){let t=(0,te.join)(e,".olympus");(0,L.existsSync)(t)||(0,L.mkdirSync)(t,{recursive:!0})}function be(e){let t=Bt(e);if(!(0,L.existsSync)(t))return null;try{let n=(0,L.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Ia(e,t){try{_a(e);let n=Bt(e);return(0,L.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function tt(e){let t=Bt(e);if(!(0,L.existsSync)(t))return!0;try{return(0,L.unlinkSync)(t),!0}catch{return!1}}function sr(e){let t=be(e);return!t||!t.active?null:(t.iteration+=1,Ia(e,t)?t:null)}function ir(e,t){let n=(0,te.join)((0,rr.homedir)(),".claude"),o=[(0,te.join)(n,"sessions",e,"transcript.md"),(0,te.join)(n,"sessions",e,"messages.json"),(0,te.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,L.existsSync)(r))try{let s=(0,L.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${Aa(t)}\\s*</promise>`,"is").test(s))return!0}catch{continue}return!1}function Aa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var j=require("fs"),Yt=require("path"),wa=3;function Wt(e){return(0,Yt.join)(e,".olympus","ascent-verification.json")}function Ce(e){let t=Wt(e);if(!(0,j.existsSync)(t))return null;try{return JSON.parse((0,j.readFileSync)(t,"utf-8"))}catch{return null}}function ar(e,t){let n=Wt(e),o=(0,Yt.join)(e,".olympus");if(!(0,j.existsSync)(o))try{(0,j.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,j.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function xe(e){let t=Wt(e);if((0,j.existsSync)(t))try{return(0,j.unlinkSync)(t),!0}catch{return!1}return!0}function cr(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:wa,requested_at:new Date().toISOString(),original_task:n};return ar(e,o),o}function lr(e,t,n){let o=Ce(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(xe(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(xe(e),{...o,pending:!1}):(ar(e,o),o)):null}function Vt(e){return`<ascent-verification>
|
|
234
234
|
|
|
235
235
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
236
236
|
|
|
@@ -270,7 +270,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
270
270
|
|
|
271
271
|
---
|
|
272
272
|
|
|
273
|
-
`}function
|
|
273
|
+
`}function ur(e){return`<ascent-continuation-after-rejection>
|
|
274
274
|
|
|
275
275
|
[ORACLE REJECTED - Continue Working]
|
|
276
276
|
|
|
@@ -295,7 +295,7 @@ Continue working now.
|
|
|
295
295
|
|
|
296
296
|
---
|
|
297
297
|
|
|
298
|
-
`}function
|
|
298
|
+
`}function pr(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function dr(e){let t=[/oracle.*?(rejected|found issues|not complete|incomplete)/i,/issues? (found|identified|detected)/i,/not yet complete/i,/missing.*?(implementation|feature|test)/i,/bug.*?(found|detected|identified)/i,/error.*?(found|detected|identified)/i];for(let n of t)if(n.test(e)){let o=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:o?o[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var A=require("fs"),Te=require("path"),Kt=require("os");function Jt(e){let t=e||process.cwd(),n=(0,Te.join)(t,".olympus");return(0,Te.join)(n,"olympus-state.json")}function qt(){return(0,Te.join)((0,Kt.homedir)(),".claude","olympus-state.json")}function Na(e){let t=e||process.cwd(),n=(0,Te.join)(t,".olympus");(0,A.existsSync)(n)||(0,A.mkdirSync)(n,{recursive:!0})}function va(){let e=(0,Te.join)((0,Kt.homedir)(),".claude");(0,A.existsSync)(e)||(0,A.mkdirSync)(e,{recursive:!0})}function ke(e){let t=Jt(e);if((0,A.existsSync)(t))try{let o=(0,A.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=qt();if((0,A.existsSync)(n))try{let o=(0,A.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function fr(e,t){try{Na(t);let n=Jt(t);(0,A.writeFileSync)(n,JSON.stringify(e,null,2)),va();let o=qt();return(0,A.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Xt(e){let t=Jt(e);if((0,A.existsSync)(t))try{(0,A.unlinkSync)(t)}catch{}let n=qt();if((0,A.existsSync)(n))try{return(0,A.unlinkSync)(n),!0}catch{return!1}return!0}function mr(e){let t=ke(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),fr(t,e)?t:null)}function gr(e){let t=ke(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),fr(t,e))}function hr(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
|
|
299
299
|
|
|
300
300
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
301
301
|
|
|
@@ -317,7 +317,7 @@ Original task: ${e.original_prompt}
|
|
|
317
317
|
|
|
318
318
|
---
|
|
319
319
|
|
|
320
|
-
`}function
|
|
320
|
+
`}function Tr(e){let t=(0,X.join)((0,zt.homedir)(),".claude"),n=[(0,X.join)(t,"sessions",e,"transcript.md"),(0,X.join)(t,"sessions",e,"messages.json"),(0,X.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,Ee.existsSync)(o))try{let r=(0,Ee.readFileSync)(o,"utf-8");if(pr(r))return!0}catch{continue}return!1}function ba(e){let t=(0,X.join)((0,zt.homedir)(),".claude"),n=[(0,X.join)(t,"sessions",e,"transcript.md"),(0,X.join)(t,"sessions",e,"messages.json"),(0,X.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,Ee.existsSync)(o))try{let r=(0,Ee.readFileSync)(o,"utf-8"),s=dr(r);if(s.rejected)return s}catch{continue}return{rejected:!1,feedback:""}}async function xa(e,t){let n=t||process.cwd(),o=be(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=Ce(n);if(r?.pending){if(e){if(Tr(e))return xe(n),tt(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=ba(e);if(l.rejected){lr(n,!1,l.feedback);let u=Ce(n);if(u)return{shouldBlock:!0,message:ur(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:Vt(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(ir(e||"",o.completion_promise)){cr(n,o.completion_promise,o.prompt);let a=Ce(n);return a?{shouldBlock:!0,message:Vt(a),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(tt(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 tt(n),xe(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=sr(n);return i?{shouldBlock:!0,message:`<ascent-continuation>
|
|
321
321
|
|
|
322
322
|
[ASCENT LOOP - ITERATION ${i.iteration}/${i.max_iterations}]
|
|
323
323
|
|
|
@@ -336,7 +336,7 @@ ${i.prompt?`Original task: ${i.prompt}`:""}
|
|
|
336
336
|
|
|
337
337
|
---
|
|
338
338
|
|
|
339
|
-
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function
|
|
339
|
+
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function Ca(e,t,n){let o=re(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return Io(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=Ao(t);return r?{shouldBlock:!0,message:wo(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Pa(e,t,n){let o=ke(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return Xt(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&&Tr(e)?(gr(t),Xt(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
|
|
340
340
|
|
|
341
341
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
342
342
|
|
|
@@ -359,11 +359,11 @@ DO NOT stop until Oracle has approved.
|
|
|
359
359
|
|
|
360
360
|
---
|
|
361
361
|
|
|
362
|
-
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=
|
|
362
|
+
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=mr(t);return r?{shouldBlock:!0,message:hr(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Da(e,t){let n=await ve(e,t);if(n.count===0)return null;let o=zo(n),r=o?`
|
|
363
363
|
|
|
364
364
|
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
365
365
|
|
|
366
|
-
${
|
|
366
|
+
${Po}
|
|
367
367
|
|
|
368
368
|
[Status: ${n.count} of ${n.total} tasks remaining]${r}
|
|
369
369
|
|
|
@@ -371,20 +371,20 @@ ${Ro}
|
|
|
371
371
|
|
|
372
372
|
---
|
|
373
373
|
|
|
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(),
|
|
374
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function kr(e,t){let n=t||process.cwd(),r=(await ve(e,n)).count>0,s=await xa(e,n);if(s?.shouldBlock)return s;let i=await Ca(e,n,r);if(i?.shouldBlock)return i;let c=await Pa(e,n,r);if(c?.shouldBlock)return c;if(r){let a=await Da(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function Er(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var ye=require("fs"),Qt=require("path"),yr=require("os");var Sr=require("crypto");function La(){let e=(0,Qt.join)((0,yr.homedir)(),".claude","todos");if(!(0,ye.existsSync)(e))return 0;let t=0;try{let n=(0,ye.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,ye.readFileSync)((0,Qt.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 Or(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=ge(t,n),r=La();if(r>0&&o.pending_completion){let s={id:(0,Sr.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};fe(s)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},he(t,o)}function Rr(){h({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await kr(t,n),r=Er(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),h({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await Or({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var ln=require("fs"),un=require("os"),De=require("path");var Y=require("fs"),U=require("path");var Zt=require("path"),_r=require("os"),Ma=(0,Zt.join)((0,_r.homedir)(),".olympus"),nt=(0,Zt.join)(Ma,"rules-injector"),Ir=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],Ar=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],wr=[".github/copilot-instructions.md"],Nr=/\.instructions\.md$/,vr=".claude/rules",br=[".md",".mdc"],en=["read","write","edit","multiedit"];function Ua(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function ja(e,t){return Ua(t)?Nr.test(e):br.some(n=>e.endsWith(n))}function on(e){let t;try{t=(0,Y.statSync)(e).isDirectory()?e:(0,U.dirname)(e)}catch{t=(0,U.dirname)(e)}for(;;){for(let o of Ir){let r=(0,U.join)(t,o);if((0,Y.existsSync)(r))return t}let n=(0,U.dirname)(t);if(n===t)return null;t=n}}function nn(e,t){if((0,Y.existsSync)(e))try{let n=(0,Y.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,U.join)(e,o.name);o.isDirectory()?nn(r,t):o.isFile()&&ja(o.name,e)&&t.push(r)}}catch{}}function tn(e){try{return(0,Y.realpathSync)(e)}catch{return e}}function rn(e,t,n){let o=[],r=new Set,s=(0,U.dirname)(n),i=0;for(;;){for(let[u,p]of Ar){let f=(0,U.join)(s,u,p),k=[];nn(f,k);for(let E of k){let S=tn(E);r.has(S)||(r.add(S),o.push({path:E,realPath:S,isGlobal:!1,distance:i}))}}if(e&&s===e)break;let l=(0,U.dirname)(s);if(l===s)break;s=l,i++}if(e)for(let l of wr){let u=(0,U.join)(e,l);if((0,Y.existsSync)(u))try{if((0,Y.statSync)(u).isFile()){let f=tn(u);r.has(f)||(r.add(f),o.push({path:u,realPath:f,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let c=(0,U.join)(t,vr),a=[];nn(c,a);for(let l of a){let u=tn(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 xr=require("crypto"),Cr=require("path");function $a(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function sn(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,Cr.relative)(n,t):t).replace(/\\/g,"/");for(let c of r)if($a(c,i))return{applies:!0,reason:`glob: ${c}`};return{applies:!1}}function Pr(e,t){return t.has(e)}function Dr(e){return(0,xr.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Lr(e,t){return t.has(e)}function an(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:Fa(o),body:r}}catch{return{metadata:{},body:e}}}function Fa(e){let t=e.split(`
|
|
375
|
+
`),n={},o=0;for(;o<t.length;){let r=t[o],s=r.indexOf(":");if(s===-1){o++;continue}let i=r.slice(0,s).trim(),c=r.slice(s+1).trim();if(i==="description")n.description=Pe(c);else if(i==="alwaysApply")n.alwaysApply=c==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:a,consumed:l}=Ha(c,t,o);n.globs=Ba(n.globs,a),o+=l;continue}o++}return n}function Pe(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function Ha(e,t,n){if(e.startsWith("["))return{value:Ga(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=Pe(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=Pe(e);return o.includes(",")?{value:o.split(",").map(s=>s.trim()).filter(s=>s.length>0),consumed:1}:{value:o,consumed:1}}function Ga(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(Pe(l)),o=""}else o+=a}let i=o.trim();return i&&n.push(Pe(i)),n}function Ba(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"),Mr=require("path");function cn(e){return(0,Mr.join)(nt,`${e}.json`)}function Ur(e){let t=cn(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 jr(e,t){(0,$.existsSync)(nt)||(0,$.mkdirSync)(nt,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,$.writeFileSync)(cn(e),JSON.stringify(n,null,2))}function $r(e){let t=cn(e);(0,$.existsSync)(t)&&(0,$.unlinkSync)(t)}function Fr(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Ur(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,De.resolve)(e,i):null}function r(i,c){let a=o(i);if(!a)return[];let l=on(a),u=n(c),p=(0,un.homedir)(),f=rn(l,p,a),k=[];for(let E of f)if(!Pr(E.realPath,u.realPaths))try{let S=(0,ln.readFileSync)(E.path,"utf-8"),{metadata:O,body:N}=an(S),P;if(E.isSingleFile)P="copilot-instructions (always apply)";else{let v=sn(O,a,l);if(!v.applies)continue;P=v.reason??"matched"}let d=Dr(N);if(Lr(d,u.contentHashes))continue;let w=l?(0,De.relative)(l,E.path):E.path;k.push({relativePath:w,matchReason:P,content:N,distance:E.distance}),u.realPaths.add(E.realPath),u.contentHashes.add(d)}catch{}return k.length>0&&(k.sort((E,S)=>E.distance-S.distance),jr(c,u)),k}function s(i){if(i.length===0)return"";let c="";for(let a of i)c+=`
|
|
376
376
|
|
|
377
377
|
[Rule: ${a.relativePath}]
|
|
378
378
|
[Match: ${a.matchReason}]
|
|
379
|
-
${a.content}`;return
|
|
379
|
+
${a.content}`;return c}return{processToolExecution:(i,c,a)=>{if(!en.includes(i.toLowerCase()))return"";let l=r(c,a);return s(l)},getRulesForFile:i=>{let c=o(i);if(!c)return[];let a=on(c),l=(0,un.homedir)(),u=rn(a,l,c),p=[];for(let f of u)try{let k=(0,ln.readFileSync)(f.path,"utf-8"),{metadata:E,body:S}=an(k),O;if(f.isSingleFile)O="copilot-instructions (always apply)";else{let P=sn(E,c,a);if(!P.applies)continue;O=P.reason??"matched"}let N=a?(0,De.relative)(a,f.path):f.path;p.push({relativePath:N,matchReason:O,content:S,distance:f.distance})}catch{}return p.sort((f,k)=>f.distance-k.distance)},clearSession:i=>{t.delete(i),$r(i)},isTrackedTool:i=>en.includes(i.toLowerCase())}}var rt=require("node:fs"),z=require("node:path");var F=require("node:fs"),Br=require("node:path");var pn=require("node:path"),Hr=require("node:os"),Ya=(0,pn.join)((0,Hr.homedir)(),".olympus"),ot=(0,pn.join)(Ya,"directory-readme"),Gr="README.md",dn=["read","write","edit","multiedit"];function fn(e){return(0,Br.join)(ot,`${e}.json`)}function Yr(e){let t=fn(e);if(!(0,F.existsSync)(t))return new Set;try{let n=(0,F.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function Wr(e,t){(0,F.existsSync)(ot)||(0,F.mkdirSync)(ot,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,F.writeFileSync)(fn(e),JSON.stringify(n,null,2))}function Vr(e){let t=fn(e);(0,F.existsSync)(t)&&(0,F.unlinkSync)(t)}var Kr=4,Wa=5e3;function Va(e,t=Wa){if(Math.ceil(e.length/Kr)<=t)return{result:e,truncated:!1};let o=t*Kr;return{result:e.slice(0,o),truncated:!0}}function Jr(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Yr(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,z.resolve)(e,i):null}function r(i){let c=[],a=i;for(;;){let l=(0,z.join)(a,Gr);if((0,rt.existsSync)(l)&&c.push(l),a===e)break;let u=(0,z.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,z.dirname)(a),u=n(c),p=r(l),f="";for(let k of p){let E=(0,z.dirname)(k);if(!u.has(E))try{let S=(0,rt.readFileSync)(k,"utf-8"),{result:O,truncated:N}=Va(S),P=N?`
|
|
380
380
|
|
|
381
|
-
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${
|
|
381
|
+
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${k}]`:"";f+=`
|
|
382
382
|
|
|
383
|
-
[Project README: ${
|
|
384
|
-
${O}${
|
|
383
|
+
[Project README: ${k}]
|
|
384
|
+
${O}${P}`,u.add(E)}catch{}}return f&&Wr(c,u),f}return{processToolExecution:(i,c,a)=>dn.includes(i.toLowerCase())?s(c,a):"",getReadmesForFile:i=>{let c=o(i);if(!c)return[];let a=(0,z.dirname)(c);return r(a)},clearSession:i=>{t.delete(i),Vr(i)},isTrackedTool:i=>dn.includes(i.toLowerCase())}}var qr="non-interactive-env",Xr={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"},mn={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
385
|
option1
|
|
386
386
|
option2
|
|
387
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
387
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var zr=mn.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function Ka(e){for(let t=0;t<zr.length;t++)if(zr[t].test(e))return mn.banned[t]}function Ja(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function qa(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${Ja(o)}`).join(" ")};`}var gn={name:qr,async beforeCommand(e){let t=Ka(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${qa(Xr)} ${e}`,warning:n}:{command:e,warning:n}}};var Tn=require("child_process");var Qr="olympus-orchestrator",Zr=".olympus/",es=["Write","Edit","write","edit"],ts=`
|
|
388
388
|
|
|
389
389
|
---
|
|
390
390
|
|
|
@@ -410,53 +410,7 @@ You should NOT:
|
|
|
410
410
|
3. Verify the subagent's work after completion
|
|
411
411
|
|
|
412
412
|
---
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
---
|
|
416
|
-
|
|
417
|
-
[CRITICAL SYSTEM DIRECTIVE - DELEGATION REQUIRED]
|
|
418
|
-
|
|
419
|
-
**STOP. YOU ARE VIOLATING ORCHESTRATOR PROTOCOL.**
|
|
420
|
-
|
|
421
|
-
You (orchestrator-olympus) are attempting to directly modify a file outside \`.olympus/\`.
|
|
422
|
-
|
|
423
|
-
**Path attempted:** $FILE_PATH
|
|
424
|
-
|
|
425
|
-
---
|
|
426
|
-
|
|
427
|
-
**THIS IS FORBIDDEN** (except for VERIFICATION purposes)
|
|
428
|
-
|
|
429
|
-
As an ORCHESTRATOR, you MUST:
|
|
430
|
-
1. **DELEGATE** all implementation work via the Task tool
|
|
431
|
-
2. **VERIFY** the work done by subagents (reading files is OK)
|
|
432
|
-
3. **COORDINATE** - you orchestrate, you don't implement
|
|
433
|
-
|
|
434
|
-
**ALLOWED direct file operations:**
|
|
435
|
-
- Files inside \`.olympus/\` (plans, drafts)
|
|
436
|
-
- Reading files for verification
|
|
437
|
-
- Running diagnostics/tests
|
|
438
|
-
|
|
439
|
-
**FORBIDDEN direct file operations:**
|
|
440
|
-
- Writing/editing source code
|
|
441
|
-
- Creating new files outside \`.olympus/\`
|
|
442
|
-
- Any implementation work
|
|
443
|
-
|
|
444
|
-
---
|
|
445
|
-
|
|
446
|
-
**IF THIS IS FOR VERIFICATION:**
|
|
447
|
-
Proceed if you are verifying subagent work by making a small fix.
|
|
448
|
-
But for any substantial changes, USE the Task tool.
|
|
449
|
-
|
|
450
|
-
**CORRECT APPROACH:**
|
|
451
|
-
\`\`\`
|
|
452
|
-
Task tool with subagent_type="olympian"
|
|
453
|
-
prompt="[specific single task with clear acceptance criteria]"
|
|
454
|
-
\`\`\`
|
|
455
|
-
|
|
456
|
-
DELEGATE. DON'T IMPLEMENT.
|
|
457
|
-
|
|
458
|
-
---
|
|
459
|
-
`,Kr=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
413
|
+
`;var ns=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
460
414
|
|
|
461
415
|
You have an active work plan with incomplete tasks. Continue working.
|
|
462
416
|
|
|
@@ -465,7 +419,7 @@ RULES:
|
|
|
465
419
|
- Mark each checkbox [x] in the plan file when done
|
|
466
420
|
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
467
421
|
- Do not stop until all tasks are complete
|
|
468
|
-
- If blocked, document the blocker and move to the next task`,
|
|
422
|
+
- If blocked, document the blocker and move to the next task`,os=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
469
423
|
|
|
470
424
|
Subagents FREQUENTLY claim completion when:
|
|
471
425
|
- Tests are actually FAILING
|
|
@@ -480,7 +434,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
480
434
|
3. Check build/typecheck - Must succeed
|
|
481
435
|
|
|
482
436
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
483
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
437
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,rs=`
|
|
484
438
|
|
|
485
439
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
486
440
|
|
|
@@ -503,37 +457,80 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
503
457
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
504
458
|
|
|
505
459
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
460
|
+
`,ss=`
|
|
461
|
+
|
|
462
|
+
================================================================================
|
|
463
|
+
HARD BLOCK: DELEGATION REQUIRED
|
|
464
|
+
================================================================================
|
|
465
|
+
|
|
466
|
+
You attempted to directly modify a source file. This operation is BLOCKED.
|
|
467
|
+
|
|
468
|
+
As an ORCHESTRATOR, you MUST delegate implementation work to subagents.
|
|
469
|
+
|
|
470
|
+
ALLOWED operations:
|
|
471
|
+
- Modify files in .olympus/ directory (plans, drafts, logs)
|
|
472
|
+
- Create test files (*.test.ts, *.spec.ts, __tests__/*)
|
|
473
|
+
- Verification edits (<10 lines on files from last 3 completed tasks)
|
|
474
|
+
|
|
475
|
+
BLOCKED operations:
|
|
476
|
+
- Direct source code modifications
|
|
477
|
+
- Creating new implementation files
|
|
478
|
+
- Large refactors
|
|
479
|
+
|
|
480
|
+
TO PROCEED:
|
|
481
|
+
1. Use the Task tool to delegate to an appropriate subagent:
|
|
482
|
+
- olympian: General implementation
|
|
483
|
+
- frontend-engineer: UI/UX work
|
|
484
|
+
- oracle: Debugging and architecture
|
|
485
|
+
|
|
486
|
+
2. Provide clear, atomic task with acceptance criteria
|
|
487
|
+
|
|
488
|
+
3. Verify subagent work after completion
|
|
489
|
+
|
|
490
|
+
Example delegation:
|
|
491
|
+
Task tool with subagent_type="olympian", prompt="Implement X with Y constraints"
|
|
492
|
+
|
|
493
|
+
================================================================================
|
|
494
|
+
|
|
495
|
+
This is a HARD BLOCK. The operation will NOT be executed.
|
|
496
|
+
Delegate to a subagent to proceed.
|
|
497
|
+
|
|
498
|
+
================================================================================
|
|
499
|
+
`;var Le=".olympus",st="quest.json",Xa=`${Le}/${st}`,is="notepads",za=`${Le}/${is}`;var W=require("fs"),it=require("path");function as(e){return(0,it.join)(e,Le,st)}function at(e){let t=as(e);if(!(0,W.existsSync)(t))return null;try{let n=(0,W.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function ct(e){if(!(0,W.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,W.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 Me=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}},od=new Me;var le=require("fs"),hn=require("path");function Ue(e,t){let n=t||process.cwd(),o=(0,hn.join)(n,".olympus","logs"),r=(0,hn.join)(o,"hook-violations.jsonl");try{(0,le.existsSync)(o)||(0,le.mkdirSync)(o,{recursive:!0});let s=JSON.stringify(e)+`
|
|
500
|
+
`;(0,le.appendFileSync)(r,s,"utf-8")}catch(s){console.error("[Hook Logging] Failed to log violation:",s)}}var cs=new Me;function ls(e){return e?e.replace(/\\/g,"/").includes(Zr):!0}function ec(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 tc(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
|
+
`).length,s=o.split(`
|
|
502
|
+
`).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 us(e){return es.includes(e)}function nc(e){try{let t=(0,Tn.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Tn.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let s of n.split(`
|
|
504
|
+
`)){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),p=a==="-"?0:parseInt(a,10);r.push({path:l,added:u,removed:p,status:o.get(l)??"modified"})}return r}catch{return[]}}function oc(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
509
506
|
No file changes detected.
|
|
510
507
|
`;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(`
|
|
511
|
-
`)}function
|
|
508
|
+
`)}function ps(e){let t=os;return e&&(t+=`
|
|
512
509
|
|
|
513
510
|
---
|
|
514
511
|
|
|
515
512
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
516
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
513
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function rc(e,t,n){let o=t.total-t.completed;return`
|
|
517
514
|
---
|
|
518
515
|
|
|
519
516
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
520
517
|
|
|
521
518
|
---
|
|
522
519
|
|
|
523
|
-
${
|
|
520
|
+
${ps(n)}
|
|
524
521
|
|
|
525
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
522
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function sc(e,t,n){return ns.replace(/{PLAN_NAME}/g,e)+`
|
|
526
523
|
|
|
527
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
524
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function ic(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!us(t))return{continue:!0};let s=n?.filePath??n?.path??n?.file;if(!s)return{continue:!0};let i=s.replace(/\\/g,"/");if(ls(i))return Ue({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(ec(i))return Ue({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let c=tc(t,n);return cs.isVerificationEdit(i,c)?(Ue({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}):(Ue({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:c,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:ss})}function ac(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:s}=e,i=r||process.cwd();if(us(n)){let c=o?.filePath??o?.path??o?.file;if(c&&!ls(c))return{continue:!0,modifiedOutput:t+ts}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let a=nc(i),l=a.map(f=>f.path);cs.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:s||`task-${Date.now()}`});let u=oc(a),p=at(i);if(p){let f=ct(p.active_plan);return{continue:!0,modifiedOutput:`
|
|
528
525
|
## SUBAGENT WORK COMPLETED
|
|
529
526
|
|
|
530
|
-
${
|
|
527
|
+
${u}
|
|
531
528
|
<system-reminder>
|
|
532
|
-
${
|
|
529
|
+
${rc(p.plan_name,f,s)}
|
|
533
530
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
534
531
|
<system-reminder>
|
|
535
|
-
${
|
|
536
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
532
|
+
${ps(s)}
|
|
533
|
+
</system-reminder>`}}return{continue:!0}}function cc(e){let t=at(e);if(!t)return{shouldContinue:!1};let n=ct(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:sc(t.plan_name,o,n.total)}}function lt(e){return{name:Qr,preTool:(t,n)=>ic({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>ac({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>cc(e),getSingleTaskDirective:()=>rs}}function ds(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function fs(){h({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=Fr(e.directory||process.cwd()),n=ds(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}}}),h({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=Jr(e.directory||process.cwd()),n=ds(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}}}),h({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!gn.beforeCommand)return{continue:!0};let n=await gn.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}}}}),h({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>lt(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var lc=["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"],uc=`
|
|
537
534
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
538
535
|
|
|
539
536
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -544,7 +541,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
544
541
|
4. CONTINUE with corrected action based on the real file content
|
|
545
542
|
|
|
546
543
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
547
|
-
`;function
|
|
544
|
+
`;function pc(e){let t=e.toLowerCase();return lc.some(n=>t.includes(n.toLowerCase()))}function ms(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:pc(t.output)?{...t,output:t.output+uc}:t}}var Ts=oe(require("fs"),1),pt=oe(require("path"),1),ks=require("os");var ut=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),kn=["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"],En=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
|
|
548
545
|
|
|
549
546
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
550
547
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -582,13 +579,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
582
579
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
583
580
|
|
|
584
581
|
Detected comments/docstrings:
|
|
585
|
-
`,
|
|
586
|
-
`;
|
|
587
|
-
`);o.lastIndex=0;let i;for(;(i=o.exec(e))!==null;){let
|
|
588
|
-
`).length,
|
|
582
|
+
`,yn={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},Sn={".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 dc(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function fc(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of ut){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>ut.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function mc(e){let t=e.text.toLowerCase().trim();for(let n of kn)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function gc(e){return{shouldSkip:!1}}function hc(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 Tc(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 kc=[dc,fc,mc,hc,Tc,gc];function On(e){return e.filter(t=>{for(let n of kc)if(n(t).shouldSkip)return!1;return!0})}var Ec=process.env.COMMENT_CHECKER_DEBUG==="1",yc=pt.join((0,ks.tmpdir)(),"comment-checker-debug.log");function ue(...e){if(Ec){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
583
|
+
`;Ts.appendFileSync(yc,t)}}function Sc(e){let t=pt.extname(e).toLowerCase();return Sn[t]}function Rn(e,t){let n=Sc(t);if(!n)return ue("unsupported language for:",t),[];let o=yn[n];if(!o)return ue("no pattern for language:",n),[];let r=[],s=e.split(`
|
|
584
|
+
`);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,p="line",f=!1;a.startsWith("/*")||a.startsWith("<!--")?p="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(p="docstring",f=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:p,isDocstring:f})}return r}function Oc(e,t){return Rn(e,t)}function gs(e,t,n){let o=Rn(e,t);if(n){let r=Rn(n,t),s=new Set(r.map(i=>i.text));return o.filter(i=>!s.has(i.text))}return o}function Rc(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=En;for(let[o,r]of t){n+=`
|
|
589
586
|
File: ${o}
|
|
590
587
|
`;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?"...":""}
|
|
591
|
-
`}}return n}function
|
|
588
|
+
`}}return n}function _c(e,t,n,o,r){let s=[];if(t)s=Oc(t,e);else if(o)s=gs(o,e,n);else if(r&&r.length>0)for(let c of r){let a=gs(c.new_string,e,c.old_string);s.push(...a)}let i=On(s);return ue(`found ${s.length} comments, ${i.length} flagged after filtering`),i.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:i.length,message:Rc(i),comments:i}}var je=new Map,Ic=6e4;function Ac(){let e=Date.now();for(let[t,n]of je)e-n.timestamp>Ic&&je.delete(t)}var hs=!1;function Es(e){return ue("createCommentCheckerHook called",{config:e}),hs||(hs=!0,setInterval(Ac,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 ue("registering pendingCall:",{callId:a,filePath:o,tool:n}),je.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 je)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&&je.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 ue("skipping due to tool failure in response"),null}let s=_c(o.filePath,o.content,o.oldString,o.newString,o.edits);return s.hasComments&&s.message?(ue("detected comments, returning message"),e?.customPrompt||s.message):null}}}var As=oe(require("fs"),1),ws=oe(require("path"),1),Ns=require("os");var Ss=[/(\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],Os=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],wc=[/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],Nc=/messages\.(\d+)/;function vc(e){return wc.some(t=>t.test(e))}function _n(e){for(let t of Ss){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 ys(e){let t=e.match(Nc);if(t)return parseInt(t[1],10)}function Se(e){if(vc(e))return!1;let t=e.toLowerCase();return Os.some(n=>t.includes(n.toLowerCase()))}function dt(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:ys(e)};if(Se(e)){let l=_n(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);Se(l)&&n.push(l)}catch{}let a=n.join(" ");if(!Se(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 p of l){let f=r.match(p);if(f)try{let k=JSON.parse(f[1]),E=k.error?.message||"",S=_n(E);if(S)return{currentTokens:S.current,maxTokens:S.max,requestId:k.request_id,errorType:k.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&Se(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=_n(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:ys(a)}:Se(a)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function In(e){return Se(e)}var An=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
592
589
|
|
|
593
590
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
594
591
|
|
|
@@ -613,7 +610,7 @@ Current Status:
|
|
|
613
610
|
- Context limit exceeded
|
|
614
611
|
- Further API calls will fail until context is reduced
|
|
615
612
|
- Action required before continuing
|
|
616
|
-
`,
|
|
613
|
+
`,wn="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",Nn=`API ERROR: Non-empty content validation failed.
|
|
617
614
|
|
|
618
615
|
This error typically occurs when:
|
|
619
616
|
- A message has empty text content
|
|
@@ -624,7 +621,7 @@ Suggested actions:
|
|
|
624
621
|
2. If the error persists, start a new session
|
|
625
622
|
|
|
626
623
|
The system will attempt automatic recovery.
|
|
627
|
-
`;var
|
|
624
|
+
`;var vn=`CONTEXT RECOVERY FAILED
|
|
628
625
|
|
|
629
626
|
All automatic recovery attempts have been exhausted.
|
|
630
627
|
Please start a new session to continue.
|
|
@@ -635,13 +632,13 @@ Before starting a new session:
|
|
|
635
632
|
3. Document the current state of the task
|
|
636
633
|
|
|
637
634
|
You can copy this conversation summary to continue in a new session.
|
|
638
|
-
`;var
|
|
639
|
-
`;
|
|
635
|
+
`;var bn={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var bc=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",xc=ws.join((0,Ns.tmpdir)(),"context-limit-recovery-debug.log");function ft(...e){if(bc){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
636
|
+
`;As.appendFileSync(xc,t)}}var mt=new Map,vs=3e5;function Rs(e){let t=mt.get(e),n=Date.now();return t&&n-t.lastErrorTime>vs&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},mt.set(e,t)),t}function Cc(){let e=Date.now();for(let[t,n]of mt)e-n.lastErrorTime>vs&&mt.delete(t)}var _s=!1;function bs(e){return ft("createContextLimitRecoveryHook called",{config:e}),_s||(_s=!0,setInterval(Cc,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=dt(t.tool_response);if(!n&&!In(t.tool_response))return null;ft("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=Rs(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=Is(n,o,e);return r.message?(ft("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=dt(t.error);if(!n)return{attempted:!1,success:!1};ft("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=Rs(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=Is(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function Is(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:Nn,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>bn.maxAttempts)return{message:vn,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=An;return e?.currentTokens&&e?.maxTokens&&(o+=`
|
|
640
637
|
Token Details:
|
|
641
638
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
642
639
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
643
640
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
644
|
-
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:
|
|
641
|
+
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:wn,errorType:e?.errorType||"token_limit_exceeded"}}var xs=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,Pc=/exceeds maximum allowed tokens/i;function Dc(e){let t=e.match(xs);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Lc(e,t){return e.toLowerCase()==="read"&&(xs.test(t)||Pc.test(t))}function Mc(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
|
|
645
642
|
|
|
646
643
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
647
644
|
|
|
@@ -671,7 +668,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
671
668
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
672
669
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
673
670
|
|
|
674
|
-
Proceed with one of these strategies.`.trim()}function
|
|
671
|
+
Proceed with one of these strategies.`.trim()}function Cs(){return{postToolUse:e=>{if(!e.tool_response||!Lc(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=Dc(e.tool_response);return Mc(t,n||void 0)}}}var js=oe(require("fs"),1),$s=oe(require("path"),1),Fs=require("os");var xn=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,gt=4,Cn=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
675
672
|
|
|
676
673
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
677
674
|
|
|
@@ -691,7 +688,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
|
|
|
691
688
|
|
|
692
689
|
Current Status: Context usage is high but recoverable.
|
|
693
690
|
Action recommended: Use /compact when convenient.
|
|
694
|
-
`,
|
|
691
|
+
`,Pn=`CRITICAL: CONTEXT WINDOW ALMOST FULL
|
|
695
692
|
|
|
696
693
|
Your context usage is critically high. Immediate action required:
|
|
697
694
|
|
|
@@ -710,8 +707,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
710
707
|
|
|
711
708
|
WARNING: Further messages may fail if context is not reduced.
|
|
712
709
|
Action required: Run /compact now.
|
|
713
|
-
`;var
|
|
714
|
-
`;
|
|
710
|
+
`;var Uc=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",jc=$s.join((0,Fs.tmpdir)(),"preemptive-compaction-debug.log");function Oe(...e){if(Uc){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
711
|
+
`;js.appendFileSync(jc,t)}}var ht=new Map;function $c(){let e=Date.now(),t=1800*1e3;for(let[n,o]of ht)e-o.lastWarningTime>t&&ht.delete(n)}var Ps=!1;function Hs(e){return Math.ceil(e.length/gt)}function Fc(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=xn,s=Hs(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 Tt(e){let t=ht.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},ht.set(e,t)),t}function Hc(e,t){let n=Tt(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,s=Date.now();return s-n.lastWarningTime<o?(Oe("skipping warning - cooldown active",{sessionId:e,elapsed:s-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(Oe("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Gc(e){let t=Tt(e);t.lastWarningTime=Date.now(),t.warningCount++}function Gs(e){return Oe("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(Ps||(Ps=!0,setInterval($c,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=Hs(t.tool_response),s=Tt(t.session_id);s.estimatedTokens+=r,Oe("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:s.estimatedTokens});let i=Fc("x".repeat(s.estimatedTokens*gt),e);return!i.isWarning||!Hc(t.session_id,e)?null:(Gc(t.session_id),Oe("injecting context warning",{sessionId:t.session_id,usageRatio:i.usageRatio,isCritical:i.isCritical}),e?.customMessage?e.customMessage:i.isCritical?Pn:Cn)},stop:t=>{let n=Tt(t.session_id);return n.warningCount>0&&(Oe("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var H=require("fs"),Ys=require("path");var Dn=require("path"),Bs=require("os"),Bc=(0,Dn.join)((0,Bs.homedir)(),".olympus"),kt=(0,Dn.join)(Bc,"agent-usage-reminder"),Ln=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"]),Mn=new Set(["task","call_omo_agent","olympus_task"]),Un=`
|
|
715
712
|
[Agent Usage Reminder]
|
|
716
713
|
|
|
717
714
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -735,7 +732,7 @@ WHY:
|
|
|
735
732
|
- Reduces context window usage in main session
|
|
736
733
|
|
|
737
734
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
738
|
-
`;function
|
|
735
|
+
`;function jn(e){return(0,Ys.join)(kt,`${e}.json`)}function $n(e){let t=jn(e);if(!(0,H.existsSync)(t))return null;try{let n=(0,H.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Et(e){(0,H.existsSync)(kt)||(0,H.mkdirSync)(kt,{recursive:!0});let t=jn(e.sessionID);(0,H.writeFileSync)(t,JSON.stringify(e,null,2))}function Fn(e){let t=jn(e);(0,H.existsSync)(t)&&(0,H.unlinkSync)(t)}function Yc(e){let t=e||process.cwd();return be(t)?.active?{active:!0,mode:"ascent"}:ke(t)?.active?{active:!0,mode:"olympus"}:re(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function Wc(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function Vc(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
|
|
739
736
|
|
|
740
737
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
741
738
|
|
|
@@ -761,25 +758,27 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
761
758
|
|
|
762
759
|
---
|
|
763
760
|
|
|
764
|
-
`}function
|
|
765
|
-
`;(0,Ks.appendFileSync)($s,t)}}function qs(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Js(e){let n=qs(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Xs(e){let t=qs(e);return t.includes("tool_use")&&t.includes("tool_result")?"tool_result_missing":t.includes("thinking")&&(t.includes("first block")||t.includes("must start with")||t.includes("preceeding")||t.includes("final block")||t.includes("cannot be thinking")||t.includes("expected")&&t.includes("found"))?"thinking_block_order":t.includes("thinking is disabled")&&t.includes("cannot contain")?"thinking_disabled_violation":t.includes("empty")&&(t.includes("content")||t.includes("message"))?"empty_content":null}function Lc(e){return Xs(e)!==null}function Dc(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Mc(e,t){b("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=K(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let o=Dc(n);return o.length===0?(b("No tool_use IDs found"),!1):(b("Found tool_use IDs to inject results for",o),!0)}async function Uc(e,t,n){b("recoverThinkingBlockOrder",{sessionID:e});let o=Js(n);if(o!==null){let i=Vs(e,o);if(i)return b("Found target message by index",{targetIndex:o,targetMessageID:i}),Un(e,i)}let r=Mn(e);if(r.length===0)return b("No orphan thinking messages found"),!1;b("Found orphan thinking messages",r);let s=!1;for(let i of r)Un(e,i)&&(s=!0);return s}async function jc(e,t){b("recoverThinkingDisabledViolation",{sessionID:e});let n=Dn(e);if(n.length===0)return b("No messages with thinking blocks found"),!1;b("Found messages with thinking blocks",n);let o=!1;for(let r of n)Ys(r)&&(o=!0);return o}async function $c(e,t,n){b("recoverEmptyContentMessage",{sessionID:e});let o=Js(n),r=t.info?.id,s=!1,i=Ws(e);for(let c of i)Me(c,H)&&(s=!0);let l=Bs(e);for(let c of l)De(e,c,H)&&(s=!0);if(o!==null){let c=Gs(e,o);if(c&&(Me(c,H)||De(e,c,H)))return!0}if(r&&(Me(r,H)||De(e,r,H)))return!0;let a=Ln(e);for(let c of a)Me(c,H)&&(s=!0),De(e,c,H)&&(s=!0);return s}async function Fc(e,t,n,o){b("handleSessionRecovery",{sessionID:e,error:t});let r=Xs(t);if(!r)return b("Not a recoverable error"),{attempted:!1,success:!1};b("Detected recoverable error type",r);try{let s=!1,i=n||{info:{},parts:[]};switch(r){case"tool_result_missing":s=await Mc(e,i);break;case"thinking_block_order":s=await Uc(e,i,t);break;case"thinking_disabled_violation":s=await jc(e,i);break;case"empty_content":s=await $c(e,i,t);break}b("Recovery result",{errorType:r,success:s});let l=o?.customMessages?.[r]||gt[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?l:void 0,errorType:r}}catch(s){return b("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function zs(e){return b("createSessionRecoveryHook",{config:e}),{onError:async t=>Fc(t.session_id,t.error,t.message,e),isRecoverable:t=>Lc(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||gt[t]?.message}}}function Qs(){let e=zs();T({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var G=require("fs"),ht=require("path"),Zs=require("os");var Ue=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let s=this.queues.get(t)??[];s.push(r),this.queues.set(t,s)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var Hc=1800*1e3,Oe=(0,ht.join)((0,Zs.homedir)(),".claude",".olympus","background-tasks"),Tt=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Ue(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,G.existsSync)(Oe)||(0,G.mkdirSync)(Oe,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,ht.join)(Oe,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,G.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,G.existsSync)(n)&&(0,G.unlinkSync)(n)}loadPersistedTasks(){if((0,G.existsSync)(Oe))try{let{readdirSync:t}=require("fs"),n=t(Oe);for(let o of n)if(o.endsWith(".json"))try{let r=(0,ht.join)(Oe,o),s=(0,G.readFileSync)(r,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??Hc;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let s=r.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(o):s.length!==r.length&&this.notifications.set(o,s)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(a=>a.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,l={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,l),this.persistTask(l),l}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let s=this.tasks.get(t);s&&(s.status=n,o&&(s.result=o),r&&(s.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(s=>s.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),s=Math.floor(r/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${r%60}s`:s>0?`${s}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let s=this.formatDuration(r.startedAt,r.completedAt),i=r.status.toUpperCase(),l=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${l}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
766
|
-
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},
|
|
767
|
-
`)}function
|
|
761
|
+
`}function Ws(){let e=new Map,t=new Map;function n(a){if(!e.has(a)){let u=$n(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(),Et(l)}function r(a){e.delete(a),Fn(a),t.delete(a)}function s(a,l,u){let p=t.get(a)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:a};return l.toLowerCase()==="task"?(p.consecutiveCount=0,t.set(a,p),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(p.consecutiveCount++,p.lastToolName=l,p.lastFilePath=u,t.set(a,p)),p.consecutiveCount)}return{"tool.execute.after":async(a,l)=>{let{tool:u,sessionID:p}=a,f=u.toLowerCase();if(Mn.has(f)){o(p),s(p,f,"");return}let k=a.properties||{},E=Wc(k),S=s(p,f,E||""),O=Yc();if(O.active){let P=Vc(S,O.mode);if(P){l.output=P+l.output;return}}if(!Ln.has(f))return;let N=n(p);N.agentUsed||(l.output+=Un,N.reminderCount++,N.updatedAt=Date.now(),Et(N))},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 Vs(){let e=process.cwd(),t=ms();h({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=Es();h({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=bs();h({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=Cs();h({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=Gs();h({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=Ws();h({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=lt(e);h({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 ri=require("node:fs");var T=require("node:fs"),M=require("node:path");var Re=require("node:path"),yt=require("node:os");function Kc(){return process.env.XDG_DATA_HOME??(0,Re.join)((0,yt.homedir)(),".local","share")}function Jc(){return(0,Re.join)(Kc(),"claude-code","storage")}var Ks=Jc(),$e=(0,Re.join)(Ks,"message"),_e=(0,Re.join)(Ks,"part"),ne=new Set(["thinking","redacted_thinking","reasoning"]),Js=new Set(["step-start","step-finish"]);var G="[user interrupted]",St={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 qs=process.env.SESSION_RECOVERY_DEBUG==="1",Xs=(0,Re.join)((0,yt.tmpdir)(),"session-recovery-debug.log");function qc(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function Xc(e){if(!(0,T.existsSync)($e))return"";let t=(0,M.join)($e,e);if((0,T.existsSync)(t))return t;for(let n of(0,T.readdirSync)($e)){let o=(0,M.join)($e,n,e);if((0,T.existsSync)(o))return o}return""}function Q(e){let t=Xc(e);if(!t||!(0,T.existsSync)(t))return[];let n=[];for(let o of(0,T.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,T.readFileSync)((0,M.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,M.join)(_e,e);if(!(0,T.existsSync)(t))return[];let n=[];for(let o of(0,T.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,T.readFileSync)((0,M.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function zs(e){return ne.has(e.type)||Js.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Qs(e){return J(e).some(zs)}function Fe(e,t,n){let o=(0,M.join)(_e,t);(0,T.existsSync)(o)||(0,T.mkdirSync)(o,{recursive:!0});let r=qc(),s={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,T.writeFileSync)((0,M.join)(o,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Hn(e){let t=Q(e),n=[];for(let o of t)Qs(o.id)||n.push(o.id);return n}function Zs(e,t){let n=Q(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(!Qs(s.id))return s.id}return null}function Gn(e){let t=Q(e),n=[];for(let o of t){if(o.role!=="assistant")continue;J(o.id).some(i=>ne.has(i.type))&&n.push(o.id)}return n}function ei(e){let t=Q(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=>ne.has(c.type)),i=r.some(zs);s&&!i&&n.push(o.id)}return n}function Bn(e){let t=Q(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];ne.has(i.type)||n.push(o.id)}return n}function zc(e,t){let n=Q(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(ne.has(c.type)){let a=c.thinking,l=c.text,u=a||l;if(u&&u.trim().length>0)return u}}return""}function Yn(e,t){let n=(0,M.join)(_e,t);(0,T.existsSync)(n)||(0,T.mkdirSync)(n,{recursive:!0});let o=zc(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,T.writeFileSync)((0,M.join)(n,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function ti(e){let t=(0,M.join)(_e,e);if(!(0,T.existsSync)(t))return!1;let n=!1;for(let o of(0,T.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,M.join)(t,o),s=(0,T.readFileSync)(r,"utf-8"),i=JSON.parse(s);ne.has(i.type)&&((0,T.unlinkSync)(r),n=!0)}catch{continue}return n}function He(e,t=G){let n=(0,M.join)(_e,e);if(!(0,T.existsSync)(n))return!1;let o=!1;for(let r of(0,T.readdirSync)(n))if(r.endsWith(".json"))try{let s=(0,M.join)(n,r),i=(0,T.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,T.writeFileSync)(s,JSON.stringify(a,null,2)),o=!0)}}catch{continue}return o}function ni(e){let t=Q(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 oi(e,t){let n=Q(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 ne.has(i.type)?null:o.id}function x(...e){if(qs){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
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()}},Wn;function Vn(e){return Wn||(Wn=new Rt(e)),Wn}function il(e){let t=e.status.toUpperCase(),n=al(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(`
|
|
764
|
+
`)}function al(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 cl(e){if(e.length===0)return"";let t=e.length===1?`
|
|
768
765
|
[BACKGROUND TASK COMPLETED]
|
|
769
766
|
`:`
|
|
770
767
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
771
|
-
`,n=e.map(o=>
|
|
768
|
+
`,n=e.map(o=>il(o)).join(`
|
|
772
769
|
|
|
773
770
|
`);return`${t}
|
|
774
771
|
${n}
|
|
775
|
-
`}function
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
`+"
|
|
781
|
-
`+"
|
|
772
|
+
`}function ll(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let s=(n?.formatNotification??cl)(o);return{hasNotifications:!0,tasks:o,message:s}}function pi(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Vn(),r=ll(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function di(){h({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 pi(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var Be=require("path"),C=require("fs"),ul=1e4;function fi(e){return(0,Be.join)(e,".olympus")}function mi(e){return(0,Be.join)(e,".olympus","archives")}function pl(e){let t=fi(e);(0,C.existsSync)(t)||(0,C.mkdirSync)(t,{recursive:!0});let n=mi(e);(0,C.existsSync)(n)||(0,C.mkdirSync)(n,{recursive:!0})}function dl(e,t,n=ul){if((0,C.existsSync)(e))try{let r=(0,C.readFileSync)(e,"utf-8").split(`
|
|
773
|
+
`).filter(s=>s.trim()).length;if(r>=n){let s=new Date().toISOString().replace(/[:.]/g,"-"),i=mi(t),c=(0,Be.join)(i,`token-metrics-${s}.jsonl`);(0,C.renameSync)(e,c),console.log(`[Olympus Token Metrics] Archived ${r} entries to ${c}`)}}catch(o){console.error(`[Olympus Token Metrics] Failed to rotate ${e}:`,o)}}async function Kn(e,t){let n=t||e.project_path||process.cwd();pl(n);let o=(0,Be.join)(fi(n),"token-metrics.jsonl");dl(o,n),(0,C.appendFileSync)(o,JSON.stringify(e)+`
|
|
774
|
+
`,"utf-8")}var qn=null,Jn=!1;async function fl(){if(!Jn)try{let{encode:e}=await import("gpt-tokenizer");qn=e,Jn=!0}catch{Jn=!0}}function ml(e){return Math.ceil(e.length/4)}function gl(e){return e==null?{text:"",inputType:"unknown"}:typeof e=="string"?{text:e,inputType:"string"}:Array.isArray(e)?{text:JSON.stringify(e),inputType:"array"}:typeof e=="object"?{text:JSON.stringify(e),inputType:"object"}:{text:String(e),inputType:"unknown"}}async function pe(e){if(!e||e.length===0)return 0;await fl();try{if(qn)return qn(e).length}catch{}return ml(e)}async function gi(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return pe(n.content);if("output"in n&&typeof n.output=="string")return pe(n.output);if("text"in n&&typeof n.text=="string")return pe(n.text);if("result"in n&&typeof n.result=="string")return pe(n.result)}let{text:t}=gl(e);return pe(t)}function hl(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 hi(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function Ti(){h({name:"tokenMetricsPrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{try{let t=hl(e),n=t?await pe(t):0,o=hi(e),r={timestamp:new Date().toISOString(),session_id:e.sessionId||"unknown",event_type:"prompt",input_tokens:n,model:o,project_path:e.directory};Kn(r,e.directory).catch(s=>{console.error("[Olympus Token Metrics] Failed to log prompt metric:",s)})}catch(t){console.error("[Olympus Token Metrics] Error in prompt handler:",t)}return{continue:!0}}}),h({name:"tokenMetricsToolUse",event:"PostToolUse",priority:70,handler:async e=>{try{if(!e.toolName)return{continue:!0};let t=e.toolOutput?await gi(e.toolOutput):0,n=hi(e),o={timestamp:new Date().toISOString(),session_id:e.sessionId||"unknown",event_type:"tool_use",output_tokens:t,model:n,tool_name:e.toolName,project_path:e.directory};Kn(o,e.directory).catch(r=>{console.error("[Olympus Token Metrics] Failed to log tool metric:",r)})}catch(t){console.error("[Olympus Token Metrics] Error in tool use handler:",t)}return{continue:!0}}})}var ki=!1;function Ei(){ki||(qo(),or(),Rr(),fs(),Vs(),li(),di(),Ti(),ki=!0)}var wt=require("fs"),Ni=require("os"),We=require("path");function _t(e,t=!1){let n=e.length,o=0,r="",s=0,i=16,c=0,a=0,l=0,u=0,p=0;function f(d,w){let v=0,y=0;for(;v<d||!w;){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++,v++}return v<d&&(y=-1),y}function k(d){o=d,r="",s=0,i=16,p=0}function E(){let d=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&Ae(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&Ae(e.charCodeAt(o)))for(o++;o<e.length&&Ae(e.charCodeAt(o));)o++;else return p=3,e.substring(d,o);let w=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&&Ae(e.charCodeAt(o))){for(o++;o<e.length&&Ae(e.charCodeAt(o));)o++;w=o}else p=3;return e.substring(d,w)}function S(){let d="",w=o;for(;;){if(o>=n){d+=e.substring(w,o),p=2;break}let v=e.charCodeAt(o);if(v===34){d+=e.substring(w,o),o++;break}if(v===92){if(d+=e.substring(w,o),o++,o>=n){p=2;break}switch(e.charCodeAt(o++)){case 34:d+='"';break;case 92:d+="\\";break;case 47:d+="/";break;case 98:d+="\b";break;case 102:d+="\f";break;case 110:d+=`
|
|
775
|
+
`;break;case 114:d+="\r";break;case 116:d+=" ";break;case 117:let m=f(4,!0);m>=0?d+=String.fromCharCode(m):p=4;break;default:p=5}w=o;continue}if(v>=0&&v<=31)if(Ye(v)){d+=e.substring(w,o),p=2;break}else p=6;o++}return d}function O(){if(r="",p=0,s=o,a=c,u=l,o>=n)return s=n,i=17;let d=e.charCodeAt(o);if(Xn(d)){do o++,r+=String.fromCharCode(d),d=e.charCodeAt(o);while(Xn(d));return i=15}if(Ye(d))return o++,r+=String.fromCharCode(d),d===13&&e.charCodeAt(o)===10&&(o++,r+=`
|
|
776
|
+
`),c++,l=o,i=14;switch(d){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=S(),i=10;case 47:let w=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Ye(e.charCodeAt(o));)o++;return r=e.substring(w,o),i=12}if(e.charCodeAt(o+1)===42){o+=2;let v=n-1,y=!1;for(;o<v;){let m=e.charCodeAt(o);if(m===42&&e.charCodeAt(o+1)===47){o+=2,y=!0;break}o++,Ye(m)&&(m===13&&e.charCodeAt(o)===10&&o++,c++,l=o)}return y||(o++,p=1),r=e.substring(w,o),i=13}return r+=String.fromCharCode(d),o++,i=16;case 45:if(r+=String.fromCharCode(d),o++,o===n||!Ae(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+=E(),i=11;default:for(;o<n&&N(d);)o++,d=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(d),o++,i=16}}function N(d){if(Xn(d)||Ye(d))return!1;switch(d){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function P(){let d;do d=O();while(d>=12&&d<=15);return d}return{setPosition:k,getPosition:()=>o,scan:t?P:O,getToken:()=>i,getTokenValue:()=>r,getTokenOffset:()=>s,getTokenLength:()=>o-s,getTokenStartLine:()=>a,getTokenStartCharacter:()=>s-u,getTokenError:()=>p}}function Xn(e){return e===32||e===9}function Ye(e){return e===10||e===13}function Ae(e){return e>=48&&e<=57}var yi;(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"})(yi||(yi={}));var kl=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),we=200,El={" ":{"\n":new Array(we).fill(0).map((e,t)=>`
|
|
777
|
+
`+" ".repeat(t)),"\r":new Array(we).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(we).fill(0).map((e,t)=>`\r
|
|
778
|
+
`+" ".repeat(t))}," ":{"\n":new Array(we).fill(0).map((e,t)=>`
|
|
779
|
+
`+" ".repeat(t)),"\r":new Array(we).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(we).fill(0).map((e,t)=>`\r
|
|
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(`
|
|
782
781
|
|
|
783
782
|
---
|
|
784
783
|
|
|
785
|
-
`):void 0,stopReason:
|
|
784
|
+
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}Ei();async function Dl(){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 xi(){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 Dl(),r;try{r=JSON.parse(o)}catch{r={}}let s=await bi(n,r);console.log(JSON.stringify(s)),process.exit(0)}var Nt=process.argv[1]||"",Ll=Nt.endsWith("entry.ts")||Nt.endsWith("entry.js")||Nt.endsWith("olympus-hooks.mjs")||Nt.includes("olympus-hooks");Ll&&xi().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|