olympus-ai 2.4.1 → 2.5.2
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/dist/__tests__/hooks/bundle.test.d.ts +2 -0
- package/dist/__tests__/hooks/bundle.test.d.ts.map +1 -0
- package/dist/__tests__/hooks/bundle.test.js +116 -0
- package/dist/__tests__/hooks/bundle.test.js.map +1 -0
- package/dist/__tests__/hooks/integration.test.d.ts +2 -0
- package/dist/__tests__/hooks/integration.test.d.ts.map +1 -0
- package/dist/__tests__/hooks/integration.test.js +132 -0
- package/dist/__tests__/hooks/integration.test.js.map +1 -0
- package/dist/__tests__/hooks/performance.test.d.ts +2 -0
- package/dist/__tests__/hooks/performance.test.d.ts.map +1 -0
- package/dist/__tests__/hooks/performance.test.js +267 -0
- package/dist/__tests__/hooks/performance.test.js.map +1 -0
- package/dist/__tests__/hooks/router.test.d.ts +2 -0
- package/dist/__tests__/hooks/router.test.d.ts.map +1 -0
- package/dist/__tests__/hooks/router.test.js +793 -0
- package/dist/__tests__/hooks/router.test.js.map +1 -0
- package/dist/__tests__/installer.test.js +7 -3
- package/dist/__tests__/installer.test.js.map +1 -1
- package/dist/hooks/config.d.ts +47 -0
- package/dist/hooks/config.d.ts.map +1 -0
- package/dist/hooks/config.js +120 -0
- package/dist/hooks/config.js.map +1 -0
- package/dist/hooks/entry.d.ts +17 -0
- package/dist/hooks/entry.d.ts.map +1 -0
- package/dist/hooks/entry.js +66 -0
- package/dist/hooks/entry.js.map +1 -0
- package/dist/hooks/index.d.ts +3 -0
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js +6 -0
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/olympus-hooks.cjs +653 -0
- package/dist/hooks/registrations/index.d.ts +25 -0
- package/dist/hooks/registrations/index.d.ts.map +1 -0
- package/dist/hooks/registrations/index.js +43 -0
- package/dist/hooks/registrations/index.js.map +1 -0
- package/dist/hooks/registrations/messages-transform.d.ts +8 -0
- package/dist/hooks/registrations/messages-transform.d.ts.map +1 -0
- package/dist/hooks/registrations/messages-transform.js +63 -0
- package/dist/hooks/registrations/messages-transform.js.map +1 -0
- package/dist/hooks/registrations/notification.d.ts +7 -0
- package/dist/hooks/registrations/notification.d.ts.map +1 -0
- package/dist/hooks/registrations/notification.js +34 -0
- package/dist/hooks/registrations/notification.js.map +1 -0
- package/dist/hooks/registrations/post-tool-use.d.ts +18 -0
- package/dist/hooks/registrations/post-tool-use.d.ts.map +1 -0
- package/dist/hooks/registrations/post-tool-use.js +198 -0
- package/dist/hooks/registrations/post-tool-use.js.map +1 -0
- package/dist/hooks/registrations/pre-tool-use.d.ts +11 -0
- package/dist/hooks/registrations/pre-tool-use.d.ts.map +1 -0
- package/dist/hooks/registrations/pre-tool-use.js +102 -0
- package/dist/hooks/registrations/pre-tool-use.js.map +1 -0
- package/dist/hooks/registrations/session-start.d.ts +7 -0
- package/dist/hooks/registrations/session-start.d.ts.map +1 -0
- package/dist/hooks/registrations/session-start.js +60 -0
- package/dist/hooks/registrations/session-start.js.map +1 -0
- package/dist/hooks/registrations/stop.d.ts +8 -0
- package/dist/hooks/registrations/stop.d.ts.map +1 -0
- package/dist/hooks/registrations/stop.js +28 -0
- package/dist/hooks/registrations/stop.js.map +1 -0
- package/dist/hooks/registrations/user-prompt-submit.d.ts +7 -0
- package/dist/hooks/registrations/user-prompt-submit.d.ts.map +1 -0
- package/dist/hooks/registrations/user-prompt-submit.js +114 -0
- package/dist/hooks/registrations/user-prompt-submit.js.map +1 -0
- package/dist/hooks/registry.d.ts +39 -0
- package/dist/hooks/registry.d.ts.map +1 -0
- package/dist/hooks/registry.js +58 -0
- package/dist/hooks/registry.js.map +1 -0
- package/dist/hooks/router.d.ts +31 -0
- package/dist/hooks/router.d.ts.map +1 -0
- package/dist/hooks/router.js +155 -0
- package/dist/hooks/router.js.map +1 -0
- package/dist/hooks/types.d.ts +102 -0
- package/dist/hooks/types.d.ts.map +1 -0
- package/dist/hooks/types.js +8 -0
- package/dist/hooks/types.js.map +1 -0
- package/dist/installer/default-config.d.ts +112 -0
- package/dist/installer/default-config.d.ts.map +1 -0
- package/dist/installer/default-config.js +153 -0
- package/dist/installer/default-config.js.map +1 -0
- package/dist/installer/hooks.d.ts +104 -0
- package/dist/installer/hooks.d.ts.map +1 -1
- package/dist/installer/hooks.js +80 -0
- package/dist/installer/hooks.js.map +1 -1
- package/dist/installer/index.d.ts +5 -1
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +2108 -2064
- package/dist/installer/index.js.map +1 -1
- package/dist/installer/migrate.d.ts +28 -0
- package/dist/installer/migrate.d.ts.map +1 -0
- package/dist/installer/migrate.js +99 -0
- package/dist/installer/migrate.js.map +1 -0
- package/dist/shared/types.d.ts +60 -0
- package/dist/shared/types.d.ts.map +1 -1
- package/package.json +3 -1
- package/.claude/agents/document-writer.md +0 -152
- package/.claude/agents/explore-medium.md +0 -25
- package/.claude/agents/explore.md +0 -86
- package/.claude/agents/frontend-engineer-high.md +0 -24
- package/.claude/agents/frontend-engineer-low.md +0 -23
- package/.claude/agents/frontend-engineer.md +0 -89
- package/.claude/agents/librarian-low.md +0 -22
- package/.claude/agents/librarian.md +0 -70
- package/.claude/agents/metis.md +0 -85
- package/.claude/agents/momus.md +0 -97
- package/.claude/agents/multimodal-looker.md +0 -39
- package/.claude/agents/olympian-high.md +0 -39
- package/.claude/agents/olympian-low.md +0 -29
- package/.claude/agents/olympian.md +0 -71
- package/.claude/agents/oracle-low.md +0 -23
- package/.claude/agents/oracle-medium.md +0 -28
- package/.claude/agents/oracle.md +0 -77
- package/.claude/agents/prometheus.md +0 -126
- package/.claude/agents/qa-tester.md +0 -220
- package/.claude/commands/analyze/skill.md +0 -14
- package/.claude/commands/analyze.md +0 -14
- package/.claude/commands/ascent/skill.md +0 -152
- package/.claude/commands/ascent.md +0 -152
- package/.claude/commands/cancel-ascent.md +0 -9
- package/.claude/commands/complete-plan.md +0 -101
- package/.claude/commands/deepinit.md +0 -114
- package/.claude/commands/deepsearch/skill.md +0 -15
- package/.claude/commands/deepsearch.md +0 -15
- package/.claude/commands/doctor.md +0 -190
- package/.claude/commands/olympus/skill.md +0 -82
- package/.claude/commands/olympus-default.md +0 -26
- package/.claude/commands/plan.md +0 -37
- package/.claude/commands/prometheus/skill.md +0 -41
- package/.claude/commands/prometheus.md +0 -41
- package/.claude/commands/review/skill.md +0 -40
- package/.claude/commands/review.md +0 -40
- package/.claude/commands/ultrawork/skill.md +0 -90
- package/.claude/commands/ultrawork.md +0 -90
- package/.claude/commands/update.md +0 -38
- package/dist/features/boulder-state/constants.d.ts +0 -20
- package/dist/features/boulder-state/constants.d.ts.map +0 -1
- package/dist/features/boulder-state/constants.js +0 -20
- package/dist/features/boulder-state/constants.js.map +0 -1
- package/dist/features/boulder-state/index.d.ts +0 -12
- package/dist/features/boulder-state/index.d.ts.map +0 -1
- package/dist/features/boulder-state/index.js +0 -13
- package/dist/features/boulder-state/index.js.map +0 -1
- package/dist/features/boulder-state/storage.d.ts +0 -58
- package/dist/features/boulder-state/storage.d.ts.map +0 -1
- package/dist/features/boulder-state/storage.js +0 -174
- package/dist/features/boulder-state/storage.js.map +0 -1
- package/dist/features/boulder-state/types.d.ts +0 -48
- package/dist/features/boulder-state/types.d.ts.map +0 -1
- package/dist/features/boulder-state/types.js +0 -10
- package/dist/features/boulder-state/types.js.map +0 -1
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
+
"use strict";var Dr=Object.create;var se=Object.defineProperty;var Mr=Object.getOwnPropertyDescriptor;var Ur=Object.getOwnPropertyNames;var $r=Object.getPrototypeOf,Hr=Object.prototype.hasOwnProperty;var jr=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},Wt=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ur(t))!Hr.call(e,r)&&r!==n&&se(e,r,{get:()=>t[r],enumerable:!(o=Mr(t,r))||o.enumerable});return e};var w=(e,t,n)=>(n=e!=null?Dr($r(e)):{},Wt(t||!e||!e.__esModule?se(n,"default",{value:e,enumerable:!0}):n,e)),Fr=e=>Wt(se({},"__esModule",{value:!0}),e);var qi={};jr(qi,{main:()=>br});module.exports=Fr(qi);var De=new Map;function m(e){let t=De.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),De.set(e.event,t)}function Kt(e){return De.get(e)||[]}var Gr={ultrawork:/\b(ultrawork|ulw)\b/i,ultrathink:/\b(ultrathink|think)\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},Br=["ultrawork","ultrathink","search","analyze"];function Vt(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function qt(e,t){let n=[];for(let o of Br){let r=Gr[o],i=e.match(r);i&&i.index!==void 0&&n.push({type:o,keyword:i[0],position:i.index})}return n}var zt="auto-slash-command",ie="<auto-slash-command>",ae="</auto-slash-command>",Jt=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Xt=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Yr=/```[\s\S]*?```/g;function Qt(e){return e.replace(Yr,"")}function Zt(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Jt);if(!n)return null;let[o,r,i]=n;return{command:r.toLowerCase(),args:i.trim(),raw:o}}function en(e){return Xt.has(e.toLowerCase())}function Me(e){let n=Qt(e).trim();if(!n.startsWith("/"))return null;let o=Zt(n);return!o||en(o.command)?null:o}function Ue(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var x=require("fs"),P=require("path"),on=require("os"),tn=(0,P.join)((0,on.homedir)(),".claude");function rn(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,o,r]=n,i={};for(let s of o.split(`
|
|
4
|
+
`)){let a=s.indexOf(":");if(a===-1)continue;let c=s.slice(0,a).trim(),u=s.slice(a+1).trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),i[c]=u}return{data:i,body:r}}function nn(e,t){if(!(0,x.existsSync)(e))return[];let n;try{n=(0,x.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let i=(0,P.join)(e,r.name),s=(0,P.basename)(r.name,".md");try{let a=(0,x.readFileSync)(i,"utf-8"),{data:c,body:u}=rn(a),l={name:s,description:c.description||"",argumentHint:c["argument-hint"],model:c.model,agent:c.agent};o.push({name:s,path:i,metadata:l,content:u,scope:t})}catch{continue}}return o}function $e(){let e=(0,P.join)(tn,"commands"),t=(0,P.join)(process.cwd(),".claude","commands"),n=(0,P.join)(tn,"skills"),o=nn(e,"user"),r=nn(t,"project"),i=[];if((0,x.existsSync)(n))try{let s=(0,x.readdirSync)(n,{withFileTypes:!0});for(let a of s){if(!a.isDirectory())continue;let c=(0,P.join)(n,a.name,"SKILL.md");if((0,x.existsSync)(c))try{let u=(0,x.readFileSync)(c,"utf-8"),{data:l,body:d}=rn(u),p={name:l.name||a.name,description:l.description||"",argumentHint:l["argument-hint"],model:l.model,agent:l.agent};i.push({name:l.name||a.name,path:c,metadata:p,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...i]}function ce(e){return $e().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function Wr(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function Kr(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
5
|
+
`),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
|
|
6
|
+
`),t&&n.push(`**Arguments**: ${t}
|
|
7
|
+
`),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
|
|
8
|
+
`),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
|
|
9
|
+
`),n.push(`**Scope**: ${e.scope}
|
|
10
|
+
`),n.push(`---
|
|
11
|
+
`);let o=Wr(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
`),n.push(`## User Request
|
|
15
|
+
`),n.push(t)),n.join(`
|
|
16
|
+
`)}function He(e){let t=ce(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:Kr(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function je(){return $e().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var ue=new Set;function sn(){return{name:zt,processMessage:(e,t)=>{let n=Ue(t);if(n.includes(ie)||n.includes(ae))return{detected:!1};let o=Me(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(ue.has(r))return{detected:!1};ue.add(r);let i=He(o);if(i.success&&i.replacementText){let a=`${ie}
|
|
17
|
+
${i.replacementText}
|
|
18
|
+
${ae}`;return{detected:!0,parsedCommand:o,injectedMessage:a}}let s=`${ie}
|
|
19
|
+
[AUTO-SLASH-COMMAND ERROR]
|
|
20
|
+
${i.error}
|
|
21
|
+
|
|
22
|
+
Original input: ${o.raw}
|
|
23
|
+
${ae}`;return{detected:!0,parsedCommand:o,injectedMessage:s}},listCommands:()=>je(),findCommand:e=>ce(e),clearSession:e=>{let t=[];for(let n of ue)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)ue.delete(n)}}}var Vr=[/\bultrathink\b/i,/\bthink\b/i],qr=["\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"],zr=qr.map(e=>new RegExp(e,"i")),Jr=[...Vr,...zr],Xr=/```[\s\S]*?```/g,Qr=/`[^`]+`/g;function Zr(e){return e.replace(Xr,"").replace(Qr,"")}function an(e){let t=Zr(e);return Jr.some(n=>n.test(t))}function cn(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function Fe(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function Ge(e){return e.replace(/\.(\d+)/g,"-$1")}var un={"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"},ln=new Set(Object.values(un)),dn={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"}},es={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 pn(e){let t=Ge(e),{prefix:n,base:o}=Fe(t);if(ln.has(o)||o.endsWith("-high"))return null;let r=un[o];return r?n+r:null}function Be(e){let t=Ge(e),{base:n}=Fe(t);return ln.has(n)||n.endsWith("-high")}function ts(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 ns(e){return e in dn}function mn(e,t){let n=Ge(t),{base:o}=Fe(n);if(Be(n))return null;let r=ts(e,t);if(!ns(r))return null;let i=dn[r],s=es[r];if(!s)return null;let a=o.toLowerCase();return s.some(u=>a.includes(u.toLowerCase()))?i:null}var U=new Map;function os(e){U.delete(e)}function fn(){return{processChatParams:(e,t)=>{let n=cn(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!an(n))return U.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,Be(r.modelId)))return U.set(e,o),o;let i=pn(r.modelId),s=mn(r.providerId,r.modelId);return i&&(t.message.model={providerId:r.providerId,modelId:i},o.modelSwitched=!0),s&&(Object.assign(t.message,s),o.thinkingConfigInjected=!0),U.set(e,o),o},onSessionDeleted:e=>{U.delete(e)},isRequested:e=>U.get(e)?.requested??!1,getState:e=>U.get(e),clear:os}}var h=require("fs"),Y=require("path"),Ye=require("os");function We(e){let t=e||process.cwd(),n=(0,Y.join)(t,".olympus");return(0,Y.join)(n,"ultrawork-state.json")}function Ke(){return(0,Y.join)((0,Ye.homedir)(),".claude","ultrawork-state.json")}function rs(e){let t=e||process.cwd(),n=(0,Y.join)(t,".olympus");(0,h.existsSync)(n)||(0,h.mkdirSync)(n,{recursive:!0})}function ss(){let e=(0,Y.join)((0,Ye.homedir)(),".claude");(0,h.existsSync)(e)||(0,h.mkdirSync)(e,{recursive:!0})}function z(e){let t=We(e);if((0,h.existsSync)(t))try{let o=(0,h.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Ke();if((0,h.existsSync)(n))try{let o=(0,h.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function gn(e,t){try{rs(t);let n=We(t);(0,h.writeFileSync)(n,JSON.stringify(e,null,2)),ss();let o=Ke();return(0,h.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function hn(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 gn(o,n)}function Tn(e){let t=We(e);if((0,h.existsSync)(t))try{(0,h.unlinkSync)(t)}catch{}let n=Ke();if((0,h.existsSync)(n))try{return(0,h.unlinkSync)(n),!0}catch{return!1}return!0}function En(e){let t=z(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),gn(t,e)?t:null)}function Sn(e){return`<ultrawork-persistence>
|
|
24
|
+
|
|
25
|
+
[ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
|
|
26
|
+
|
|
27
|
+
Your ultrawork session is NOT complete. Incomplete todos remain.
|
|
28
|
+
|
|
29
|
+
REMEMBER THE ULTRAWORK RULES:
|
|
30
|
+
- **PARALLEL**: Fire independent calls simultaneously - NEVER wait sequentially
|
|
31
|
+
- **BACKGROUND FIRST**: Use Task(run_in_background=true) for exploration (10+ concurrent)
|
|
32
|
+
- **TODO**: Track EVERY step. Mark complete IMMEDIATELY after each
|
|
33
|
+
- **VERIFY**: Check ALL requirements met before done
|
|
34
|
+
- **NO Premature Stopping**: ALL TODOs must be complete
|
|
35
|
+
|
|
36
|
+
Continue working on the next pending task. DO NOT STOP until all tasks are marked complete.
|
|
37
|
+
|
|
38
|
+
Original task: ${e.original_prompt}
|
|
39
|
+
|
|
40
|
+
</ultrawork-persistence>
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
`}var kn=require("os"),E=require("path");function v(){return process.platform==="win32"}function is(){return(0,E.join)((0,kn.homedir)(),".claude")}function O(){return(0,E.join)(is(),"hooks")}var On=`<ultrawork-mode>
|
|
45
|
+
|
|
46
|
+
**MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
|
|
47
|
+
|
|
48
|
+
[CODE RED] Maximum precision required. Ultrathink before acting.
|
|
49
|
+
|
|
50
|
+
YOU MUST LEVERAGE ALL AVAILABLE AGENTS TO THEIR FULLEST POTENTIAL.
|
|
51
|
+
TELL THE USER WHAT AGENTS YOU WILL LEVERAGE NOW TO SATISFY USER'S REQUEST.
|
|
52
|
+
|
|
53
|
+
## AGENT UTILIZATION PRINCIPLES (by capability, not by name)
|
|
54
|
+
- **Codebase Exploration**: Spawn exploration agents using BACKGROUND TASKS for file patterns, internal implementations, project structure
|
|
55
|
+
- **Documentation & References**: Use librarian-type agents via BACKGROUND TASKS for API references, examples, external library docs
|
|
56
|
+
- **Planning & Strategy**: NEVER plan yourself - ALWAYS spawn a dedicated planning agent for work breakdown
|
|
57
|
+
- **High-IQ Reasoning**: Leverage specialized agents for architecture decisions, code review, strategic planning
|
|
58
|
+
- **Frontend/UI Tasks**: Delegate to UI-specialized agents for design and implementation
|
|
59
|
+
|
|
60
|
+
## EXECUTION RULES
|
|
61
|
+
- **TODO**: Track EVERY step. Mark complete IMMEDIATELY after each.
|
|
62
|
+
- **PARALLEL**: Fire independent agent calls simultaneously via Task(run_in_background=true) - NEVER wait sequentially.
|
|
63
|
+
- **BACKGROUND FIRST**: Use Task tool for exploration/research agents (10+ concurrent if needed).
|
|
64
|
+
- **VERIFY**: Re-read request after completion. Check ALL requirements met before reporting done.
|
|
65
|
+
- **DELEGATE**: Don't do everything yourself - orchestrate specialized agents for their strengths.
|
|
66
|
+
|
|
67
|
+
## WORKFLOW
|
|
68
|
+
1. Analyze the request and identify required capabilities
|
|
69
|
+
2. Spawn exploration/librarian agents via Task(run_in_background=true) in PARALLEL (10+ if needed)
|
|
70
|
+
3. Always Use Plan agent with gathered context to create detailed work breakdown
|
|
71
|
+
4. Execute with continuous verification against original requirements
|
|
72
|
+
|
|
73
|
+
## VERIFICATION GUARANTEE (NON-NEGOTIABLE)
|
|
74
|
+
|
|
75
|
+
**NOTHING is "done" without PROOF it works.**
|
|
76
|
+
|
|
77
|
+
### Pre-Implementation: Define Success Criteria
|
|
78
|
+
|
|
79
|
+
BEFORE writing ANY code, you MUST define:
|
|
80
|
+
|
|
81
|
+
| Criteria Type | Description | Example |
|
|
82
|
+
|---------------|-------------|---------|
|
|
83
|
+
| **Functional** | What specific behavior must work | "Button click triggers API call" |
|
|
84
|
+
| **Observable** | What can be measured/seen | "Console shows 'success', no errors" |
|
|
85
|
+
| **Pass/Fail** | Binary, no ambiguity | "Returns 200 OK" not "should work" |
|
|
86
|
+
|
|
87
|
+
Write these criteria explicitly. Share with user if scope is non-trivial.
|
|
88
|
+
|
|
89
|
+
### Execution & Evidence Requirements
|
|
90
|
+
|
|
91
|
+
| Phase | Action | Required Evidence |
|
|
92
|
+
|-------|--------|-------------------|
|
|
93
|
+
| **Build** | Run build command | Exit code 0, no errors |
|
|
94
|
+
| **Test** | Execute test suite | All tests pass (screenshot/output) |
|
|
95
|
+
| **Manual Verify** | Test the actual feature | Demonstrate it works (describe what you observed) |
|
|
96
|
+
| **Regression** | Ensure nothing broke | Existing tests still pass |
|
|
97
|
+
|
|
98
|
+
**WITHOUT evidence = NOT verified = NOT done.**
|
|
99
|
+
|
|
100
|
+
### TDD Workflow (when test infrastructure exists)
|
|
101
|
+
|
|
102
|
+
1. **SPEC**: Define what "working" means (success criteria above)
|
|
103
|
+
2. **RED**: Write failing test -> Run it -> Confirm it FAILS
|
|
104
|
+
3. **GREEN**: Write minimal code -> Run test -> Confirm it PASSES
|
|
105
|
+
4. **REFACTOR**: Clean up -> Tests MUST stay green
|
|
106
|
+
5. **VERIFY**: Run full test suite, confirm no regressions
|
|
107
|
+
6. **EVIDENCE**: Report what you ran and what output you saw
|
|
108
|
+
|
|
109
|
+
### Verification Anti-Patterns (BLOCKING)
|
|
110
|
+
|
|
111
|
+
| Violation | Why It Fails |
|
|
112
|
+
|-----------|--------------|
|
|
113
|
+
| "It should work now" | No evidence. Run it. |
|
|
114
|
+
| "I added the tests" | Did they pass? Show output. |
|
|
115
|
+
| "Fixed the bug" | How do you know? What did you test? |
|
|
116
|
+
| "Implementation complete" | Did you verify against success criteria? |
|
|
117
|
+
| Skipping test execution | Tests exist to be RUN, not just written |
|
|
118
|
+
|
|
119
|
+
**CLAIM NOTHING WITHOUT PROOF. EXECUTE. VERIFY. SHOW EVIDENCE.**
|
|
120
|
+
|
|
121
|
+
## ZERO TOLERANCE FAILURES
|
|
122
|
+
- **NO Scope Reduction**: Never make "demo", "skeleton", "simplified", "basic" versions - deliver FULL implementation
|
|
123
|
+
- **NO MockUp Work**: When user asked you to do "port A", you must "port A", fully, 100%. No Extra feature, No reduced feature, no mock data, fully working 100% port.
|
|
124
|
+
- **NO Partial Completion**: Never stop at 60-80% saying "you can extend this..." - finish 100%
|
|
125
|
+
- **NO Assumed Shortcuts**: Never skip requirements you deem "optional" or "can be added later"
|
|
126
|
+
- **NO Premature Stopping**: Never declare done until ALL TODOs are completed and verified
|
|
127
|
+
- **NO TEST DELETION**: Never delete or skip failing tests to make the build pass. Fix the code, not the tests.
|
|
128
|
+
|
|
129
|
+
THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTING POINT.
|
|
130
|
+
|
|
131
|
+
</ultrawork-mode>
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
|
|
135
|
+
`,yn=`<think-mode>
|
|
136
|
+
|
|
137
|
+
**ULTRATHINK MODE ENABLED** - Extended reasoning activated.
|
|
138
|
+
|
|
139
|
+
You are now in deep thinking mode. Take your time to:
|
|
140
|
+
1. Thoroughly analyze the problem from multiple angles
|
|
141
|
+
2. Consider edge cases and potential issues
|
|
142
|
+
3. Think through the implications of each approach
|
|
143
|
+
4. Reason step-by-step before acting
|
|
144
|
+
|
|
145
|
+
Use your extended thinking capabilities to provide the most thorough and well-reasoned response.
|
|
146
|
+
|
|
147
|
+
</think-mode>
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
`,Rn=`<search-mode>
|
|
152
|
+
MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
|
|
153
|
+
- explore agents (codebase patterns, file structures)
|
|
154
|
+
- librarian agents (remote repos, official docs, GitHub examples)
|
|
155
|
+
Plus direct tools: Grep, Glob
|
|
156
|
+
NEVER stop at first result - be exhaustive.
|
|
157
|
+
</search-mode>
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
`,In=`<analyze-mode>
|
|
162
|
+
ANALYSIS MODE. Gather context before diving deep:
|
|
163
|
+
|
|
164
|
+
CONTEXT GATHERING (parallel):
|
|
165
|
+
- 1-2 explore agents (codebase patterns, implementations)
|
|
166
|
+
- 1-2 librarian agents (if external library involved)
|
|
167
|
+
- Direct tools: Grep, Glob, LSP for targeted searches
|
|
168
|
+
|
|
169
|
+
IF COMPLEX (architecture, multi-system, debugging after 2+ failures):
|
|
170
|
+
- Consult oracle agent for strategic guidance
|
|
171
|
+
|
|
172
|
+
SYNTHESIZE findings before proceeding.
|
|
173
|
+
</analyze-mode>
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
`,Cn=`[SYSTEM REMINDER - TODO CONTINUATION]
|
|
178
|
+
|
|
179
|
+
Incomplete tasks remain in your todo list. Continue working on the next pending task.
|
|
180
|
+
|
|
181
|
+
- Proceed without asking for permission
|
|
182
|
+
- Mark each task complete when finished
|
|
183
|
+
- Do not stop until all tasks are done`;var Oa={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:v()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:v()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:v()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},ya={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:v()?`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:v()?`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:v()?`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:v()?`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:v()?`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],Notification:[{hooks:[{type:"command",command:v()?`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,E.join)(O(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};function as(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 An(){m({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=as(e);if(!t)return{continue:!0};let n=Vt(t),o=qt(n);if(o.length===0)return{continue:!0};let r=o.some(c=>c.type==="ultrawork"),i=o.some(c=>c.type==="ultrathink"),s=o.some(c=>c.type==="search"),a=o.some(c=>c.type==="analyze");return r?(hn(t,e.sessionId,e.directory||process.cwd()),{continue:!0,message:On}):i?{continue:!0,message:yn}:s?{continue:!0,message:Rn}:a?{continue:!0,message:In}:{continue:!0}}}),m({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=sn().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,message:n.injectedMessage}:{continue:!0}}}),m({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=fn(),n=e.sessionId||"default",o=t.processChatParams(n,{parts:e.parts,message:e.message});return o.requested&&o.modelSwitched?{continue:!0,message:"[Think Mode Activated] Switched to high-reasoning model variant."}:{continue:!0}}})}var F=require("fs"),$=require("path"),_n=require("os");function cs(e,t){let n=(0,$.join)((0,_n.homedir)(),".claude"),o=[];e&&(o.push((0,$.join)(n,"sessions",e,"todos.json")),o.push((0,$.join)(n,"todos",`${e}.json`))),t&&(o.push((0,$.join)(t,".olympus","todos.json")),o.push((0,$.join)(t,".claude","todos.json")));let r=(0,$.join)(n,"todos");if((0,F.existsSync)(r))try{let i=(0,F.readdirSync)(r);for(let s of i)s.endsWith(".json")&&o.push((0,$.join)(r,s))}catch{}return o}function us(e){try{let t=(0,F.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 ls(e){return e.status!=="completed"&&e.status!=="cancelled"}async function J(e,t){let n=cs(e,t),o=new Set,r=[],i=[];for(let s of n){if(!(0,F.existsSync)(s))continue;let a=us(s);for(let c of a){let u=`${c.content}:${c.status}`;o.has(u)||(o.add(u),r.push(c),ls(c)&&i.push(c))}}return{count:i.length,todos:i,total:r.length}}function Nn(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}function xn(){m({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[],r=z(n);r?.active&&o.push(`<session-restore>
|
|
184
|
+
|
|
185
|
+
[ULTRAWORK MODE RESTORED]
|
|
186
|
+
|
|
187
|
+
You have an active ultrawork session from ${r.started_at}.
|
|
188
|
+
Original task: ${r.original_prompt}
|
|
189
|
+
|
|
190
|
+
Continue working in ultrawork mode until all tasks are complete.
|
|
191
|
+
|
|
192
|
+
</session-restore>
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
`);let i=await J(t,n);return i.count>0&&o.push(`<session-restore>
|
|
197
|
+
|
|
198
|
+
[PENDING TASKS DETECTED]
|
|
199
|
+
|
|
200
|
+
You have ${i.count} incomplete tasks from a previous session.
|
|
201
|
+
Please continue working on these tasks.
|
|
202
|
+
|
|
203
|
+
</session-restore>
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
`),o.length>0?{continue:!0,message:o.join(`
|
|
208
|
+
`)}:{continue:!0}}})}var W=require("fs"),b=require("path"),Qe=require("os");var S=require("fs"),H=require("path"),wn=require("os");function Ve(e){let t=(0,H.join)(e,".olympus");return(0,H.join)(t,"ascent-state.json")}function ds(e){let t=(0,H.join)(e,".olympus");(0,S.existsSync)(t)||(0,S.mkdirSync)(t,{recursive:!0})}function qe(e){let t=Ve(e);if(!(0,S.existsSync)(t))return null;try{let n=(0,S.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function ps(e,t){try{ds(e);let n=Ve(e);return(0,S.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function le(e){let t=Ve(e);if(!(0,S.existsSync)(t))return!0;try{return(0,S.unlinkSync)(t),!0}catch{return!1}}function Pn(e){let t=qe(e);return!t||!t.active?null:(t.iteration+=1,ps(e,t)?t:null)}function vn(e,t){let n=(0,H.join)((0,wn.homedir)(),".claude"),o=[(0,H.join)(n,"sessions",e,"transcript.md"),(0,H.join)(n,"sessions",e,"messages.json"),(0,H.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,S.existsSync)(r))try{let i=(0,S.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${ms(t)}\\s*</promise>`,"is").test(i))return!0}catch{continue}return!1}function ms(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var y=require("fs"),ze=require("path"),fs=3;function Je(e){return(0,ze.join)(e,".olympus","ascent-verification.json")}function Q(e){let t=Je(e);if(!(0,y.existsSync)(t))return null;try{return JSON.parse((0,y.readFileSync)(t,"utf-8"))}catch{return null}}function bn(e,t){let n=Je(e),o=(0,ze.join)(e,".olympus");if(!(0,y.existsSync)(o))try{(0,y.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,y.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function X(e){let t=Je(e);if((0,y.existsSync)(t))try{return(0,y.unlinkSync)(t),!0}catch{return!1}return!0}function Ln(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:fs,requested_at:new Date().toISOString(),original_task:n};return bn(e,o),o}function Dn(e,t,n){let o=Q(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(X(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(X(e),{...o,pending:!1}):(bn(e,o),o)):null}function Xe(e){return`<ascent-verification>
|
|
209
|
+
|
|
210
|
+
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
211
|
+
|
|
212
|
+
The agent claims the task is complete. Before accepting, YOU MUST verify with Oracle.
|
|
213
|
+
|
|
214
|
+
**Original Task:**
|
|
215
|
+
${e.original_task}
|
|
216
|
+
|
|
217
|
+
**Completion Claim:**
|
|
218
|
+
${e.completion_claim}
|
|
219
|
+
|
|
220
|
+
${e.oracle_feedback?`**Previous Oracle Feedback (rejected):**
|
|
221
|
+
${e.oracle_feedback}
|
|
222
|
+
`:""}
|
|
223
|
+
|
|
224
|
+
## MANDATORY VERIFICATION STEPS
|
|
225
|
+
|
|
226
|
+
1. **Spawn Oracle Agent** for verification:
|
|
227
|
+
\`\`\`
|
|
228
|
+
Task(subagent_type="oracle", prompt="Verify this task completion claim...")
|
|
229
|
+
\`\`\`
|
|
230
|
+
|
|
231
|
+
2. **Oracle must check:**
|
|
232
|
+
- Are ALL requirements from the original task met?
|
|
233
|
+
- Is the implementation complete, not partial?
|
|
234
|
+
- Are there any obvious bugs or issues?
|
|
235
|
+
- Does the code compile/run without errors?
|
|
236
|
+
- Are tests passing (if applicable)?
|
|
237
|
+
|
|
238
|
+
3. **Based on Oracle's response:**
|
|
239
|
+
- If APPROVED: Output \`<oracle-approved>VERIFIED_COMPLETE</oracle-approved>\`
|
|
240
|
+
- If REJECTED: Continue working on the identified issues
|
|
241
|
+
|
|
242
|
+
DO NOT output the completion promise again until Oracle approves.
|
|
243
|
+
|
|
244
|
+
</ascent-verification>
|
|
245
|
+
|
|
246
|
+
---
|
|
247
|
+
|
|
248
|
+
`}function Mn(e){return`<ascent-continuation-after-rejection>
|
|
249
|
+
|
|
250
|
+
[ORACLE REJECTED - Continue Working]
|
|
251
|
+
|
|
252
|
+
Oracle found issues with your completion claim. You must address them.
|
|
253
|
+
|
|
254
|
+
**Oracle Feedback:**
|
|
255
|
+
${e.oracle_feedback}
|
|
256
|
+
|
|
257
|
+
**Original Task:**
|
|
258
|
+
${e.original_task}
|
|
259
|
+
|
|
260
|
+
## INSTRUCTIONS
|
|
261
|
+
|
|
262
|
+
1. Address ALL issues identified by Oracle
|
|
263
|
+
2. Do NOT claim completion again until issues are fixed
|
|
264
|
+
3. When truly done, output the completion promise again
|
|
265
|
+
4. Another Oracle verification will be triggered
|
|
266
|
+
|
|
267
|
+
Continue working now.
|
|
268
|
+
|
|
269
|
+
</ascent-continuation-after-rejection>
|
|
270
|
+
|
|
271
|
+
---
|
|
272
|
+
|
|
273
|
+
`}function Un(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function $n(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:""}}function gs(e){let t=(0,b.join)((0,Qe.homedir)(),".claude"),n=[(0,b.join)(t,"sessions",e,"transcript.md"),(0,b.join)(t,"sessions",e,"messages.json"),(0,b.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,W.existsSync)(o))try{let r=(0,W.readFileSync)(o,"utf-8");if(Un(r))return!0}catch{continue}return!1}function hs(e){let t=(0,b.join)((0,Qe.homedir)(),".claude"),n=[(0,b.join)(t,"sessions",e,"transcript.md"),(0,b.join)(t,"sessions",e,"messages.json"),(0,b.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,W.existsSync)(o))try{let r=(0,W.readFileSync)(o,"utf-8"),i=$n(r);if(i.rejected)return i}catch{continue}return{rejected:!1,feedback:""}}async function Ts(e,t){let n=t||process.cwd(),o=qe(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=Q(n);if(r?.pending){if(e){if(gs(e))return X(n),le(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let u=hs(e);if(u.rejected){Dn(n,!1,u.feedback);let l=Q(n);if(l)return{shouldBlock:!0,message:Mn(l),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:Xe(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(vn(e||"",o.completion_promise)){Ln(n,o.completion_promise,o.prompt);let c=Q(n);return c?{shouldBlock:!0,message:Xe(c),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(le(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 le(n),X(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let s=Pn(n);return s?{shouldBlock:!0,message:`<ascent-continuation>
|
|
274
|
+
|
|
275
|
+
[ASCENT LOOP - ITERATION ${s.iteration}/${s.max_iterations}]
|
|
276
|
+
|
|
277
|
+
Your previous attempt did not output the completion promise. The work is NOT done yet.
|
|
278
|
+
|
|
279
|
+
CRITICAL INSTRUCTIONS:
|
|
280
|
+
1. Review your progress and the original task
|
|
281
|
+
2. Check your todo list - are ALL items marked complete?
|
|
282
|
+
3. Continue from where you left off
|
|
283
|
+
4. When FULLY complete, output: <promise>${s.completion_promise}</promise>
|
|
284
|
+
5. Do NOT stop until the task is truly done
|
|
285
|
+
|
|
286
|
+
${s.prompt?`Original task: ${s.prompt}`:""}
|
|
287
|
+
|
|
288
|
+
</ascent-continuation>
|
|
289
|
+
|
|
290
|
+
---
|
|
291
|
+
|
|
292
|
+
`,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function Es(e,t,n){let o=z(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return Tn(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=En(t);return r?{shouldBlock:!0,message:Sn(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Ss(e,t){let n=await J(e,t);if(n.count===0)return null;let o=Nn(n),r=o?`
|
|
293
|
+
|
|
294
|
+
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
295
|
+
|
|
296
|
+
${Cn}
|
|
297
|
+
|
|
298
|
+
[Status: ${n.count} of ${n.total} tasks remaining]${r}
|
|
299
|
+
|
|
300
|
+
</todo-continuation>
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function Hn(e,t){let n=t||process.cwd(),r=(await J(e,n)).count>0,i=await Ts(e,n);if(i?.shouldBlock)return i;let s=await Es(e,n,r);if(s?.shouldBlock)return s;if(r){let a=await Ss(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function jn(e){return e.shouldBlock?{continue:!1,reason:e.message}:{continue:!0,message:e.message||void 0}}function Fn(){m({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await Hn(t,n),r=jn(o);return{continue:r.continue,message:r.message,reason:r.reason}}})}var ct=require("fs"),ut=require("os"),ee=require("path");var _=require("fs"),k=require("path");var Ze=require("path"),Gn=require("os"),ks=(0,Ze.join)((0,Gn.homedir)(),".olympus"),de=(0,Ze.join)(ks,"rules-injector"),Bn=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],Yn=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],Wn=[".github/copilot-instructions.md"],Kn=/\.instructions\.md$/,Vn=".claude/rules",qn=[".md",".mdc"],et=["read","write","edit","multiedit"];function Os(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function ys(e,t){return Os(t)?Kn.test(e):qn.some(n=>e.endsWith(n))}function ot(e){let t;try{t=(0,_.statSync)(e).isDirectory()?e:(0,k.dirname)(e)}catch{t=(0,k.dirname)(e)}for(;;){for(let o of Bn){let r=(0,k.join)(t,o);if((0,_.existsSync)(r))return t}let n=(0,k.dirname)(t);if(n===t)return null;t=n}}function nt(e,t){if((0,_.existsSync)(e))try{let n=(0,_.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,k.join)(e,o.name);o.isDirectory()?nt(r,t):o.isFile()&&ys(o.name,e)&&t.push(r)}}catch{}}function tt(e){try{return(0,_.realpathSync)(e)}catch{return e}}function rt(e,t,n){let o=[],r=new Set,i=(0,k.dirname)(n),s=0;for(;;){for(let[l,d]of Yn){let p=(0,k.join)(i,l,d),f=[];nt(p,f);for(let g of f){let T=tt(g);r.has(T)||(r.add(T),o.push({path:g,realPath:T,isGlobal:!1,distance:s}))}}if(e&&i===e)break;let u=(0,k.dirname)(i);if(u===i)break;i=u,s++}if(e)for(let u of Wn){let l=(0,k.join)(e,u);if((0,_.existsSync)(l))try{if((0,_.statSync)(l).isFile()){let p=tt(l);r.has(p)||(r.add(p),o.push({path:l,realPath:p,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let a=(0,k.join)(t,Vn),c=[];nt(a,c);for(let u of c){let l=tt(u);r.has(l)||(r.add(l),o.push({path:u,realPath:l,isGlobal:!0,distance:9999}))}return o.sort((u,l)=>u.isGlobal!==l.isGlobal?u.isGlobal?1:-1:u.distance-l.distance),o}var zn=require("crypto"),Jn=require("path");function Rs(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function st(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let o=e.globs;if(!o)return{applies:!1};let r=Array.isArray(o)?o:[o];if(r.length===0)return{applies:!1};let s=(n?(0,Jn.relative)(n,t):t).replace(/\\/g,"/");for(let a of r)if(Rs(a,s))return{applies:!0,reason:`glob: ${a}`};return{applies:!1}}function Xn(e,t){return t.has(e)}function Qn(e){return(0,zn.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Zn(e,t){return t.has(e)}function it(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:Is(o),body:r}}catch{return{metadata:{},body:e}}}function Is(e){let t=e.split(`
|
|
305
|
+
`),n={},o=0;for(;o<t.length;){let r=t[o],i=r.indexOf(":");if(i===-1){o++;continue}let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(s==="description")n.description=Z(a);else if(s==="alwaysApply")n.alwaysApply=a==="true";else if(s==="globs"||s==="paths"||s==="applyTo"){let{value:c,consumed:u}=Cs(a,t,o);n.globs=_s(n.globs,c),o+=u;continue}o++}return n}function Z(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function Cs(e,t,n){if(e.startsWith("["))return{value:As(e),consumed:1};if(!e||e===""){let r=[],i=1;for(let s=n+1;s<t.length;s++){let a=t[s],c=a.match(/^\s+-\s*(.*)$/);if(c){let u=Z(c[1].trim());u&&r.push(u),i++}else if(a.trim()==="")i++;else break}if(r.length>0)return{value:r,consumed:i}}let o=Z(e);return o.includes(",")?{value:o.split(",").map(i=>i.trim()).filter(i=>i.length>0),consumed:1}:{value:o,consumed:1}}function As(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,i="";for(let a=0;a<t.length;a++){let c=t[a];if(!r&&(c==='"'||c==="'"))r=!0,i=c;else if(r&&c===i)r=!1,i="";else if(!r&&c===","){let u=o.trim();u&&n.push(Z(u)),o=""}else o+=c}let s=o.trim();return s&&n.push(Z(s)),n}function _s(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var R=require("fs"),eo=require("path");function at(e){return(0,eo.join)(de,`${e}.json`)}function to(e){let t=at(e);if(!(0,R.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,R.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 no(e,t){(0,R.existsSync)(de)||(0,R.mkdirSync)(de,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,R.writeFileSync)(at(e),JSON.stringify(n,null,2))}function oo(e){let t=at(e);(0,R.existsSync)(t)&&(0,R.unlinkSync)(t)}function ro(e){let t=new Map;function n(s){return t.has(s)||t.set(s,to(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,ee.resolve)(e,s):null}function r(s,a){let c=o(s);if(!c)return[];let u=ot(c),l=n(a),d=(0,ut.homedir)(),p=rt(u,d,c),f=[];for(let g of p)if(!Xn(g.realPath,l.realPaths))try{let T=(0,ct.readFileSync)(g.path,"utf-8"),{metadata:j,body:B}=it(T),M;if(g.isSingleFile)M="copilot-instructions (always apply)";else{let Yt=st(j,c,u);if(!Yt.applies)continue;M=Yt.reason??"matched"}let Bt=Qn(B);if(Zn(Bt,l.contentHashes))continue;let Lr=u?(0,ee.relative)(u,g.path):g.path;f.push({relativePath:Lr,matchReason:M,content:B,distance:g.distance}),l.realPaths.add(g.realPath),l.contentHashes.add(Bt)}catch{}return f.length>0&&(f.sort((g,T)=>g.distance-T.distance),no(a,l)),f}function i(s){if(s.length===0)return"";let a="";for(let c of s)a+=`
|
|
306
|
+
|
|
307
|
+
[Rule: ${c.relativePath}]
|
|
308
|
+
[Match: ${c.matchReason}]
|
|
309
|
+
${c.content}`;return a}return{processToolExecution:(s,a,c)=>{if(!et.includes(s.toLowerCase()))return"";let u=r(a,c);return i(u)},getRulesForFile:s=>{let a=o(s);if(!a)return[];let c=ot(a),u=(0,ut.homedir)(),l=rt(c,u,a),d=[];for(let p of l)try{let f=(0,ct.readFileSync)(p.path,"utf-8"),{metadata:g,body:T}=it(f),j;if(p.isSingleFile)j="copilot-instructions (always apply)";else{let M=st(g,a,c);if(!M.applies)continue;j=M.reason??"matched"}let B=c?(0,ee.relative)(c,p.path):p.path;d.push({relativePath:B,matchReason:j,content:T,distance:p.distance})}catch{}return d.sort((p,f)=>p.distance-f.distance)},clearSession:s=>{t.delete(s),oo(s)},isTrackedTool:s=>et.includes(s.toLowerCase())}}var me=require("node:fs"),L=require("node:path");var I=require("node:fs"),ao=require("node:path");var lt=require("node:path"),so=require("node:os"),Ns=(0,lt.join)((0,so.homedir)(),".olympus"),pe=(0,lt.join)(Ns,"directory-readme"),io="README.md",dt=["read","write","edit","multiedit"];function pt(e){return(0,ao.join)(pe,`${e}.json`)}function co(e){let t=pt(e);if(!(0,I.existsSync)(t))return new Set;try{let n=(0,I.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function uo(e,t){(0,I.existsSync)(pe)||(0,I.mkdirSync)(pe,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,I.writeFileSync)(pt(e),JSON.stringify(n,null,2))}function lo(e){let t=pt(e);(0,I.existsSync)(t)&&(0,I.unlinkSync)(t)}var po=4,xs=5e3;function ws(e,t=xs){if(Math.ceil(e.length/po)<=t)return{result:e,truncated:!1};let o=t*po;return{result:e.slice(0,o),truncated:!0}}function mo(e){let t=new Map;function n(s){return t.has(s)||t.set(s,co(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,L.resolve)(e,s):null}function r(s){let a=[],c=s;for(;;){let u=(0,L.join)(c,io);if((0,me.existsSync)(u)&&a.push(u),c===e)break;let l=(0,L.dirname)(c);if(l===c||!l.startsWith(e))break;c=l}return a.reverse()}function i(s,a){let c=o(s);if(!c)return"";let u=(0,L.dirname)(c),l=n(a),d=r(u),p="";for(let f of d){let g=(0,L.dirname)(f);if(!l.has(g))try{let T=(0,me.readFileSync)(f,"utf-8"),{result:j,truncated:B}=ws(T),M=B?`
|
|
310
|
+
|
|
311
|
+
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${f}]`:"";p+=`
|
|
312
|
+
|
|
313
|
+
[Project README: ${f}]
|
|
314
|
+
${j}${M}`,l.add(g)}catch{}}return p&&uo(a,l),p}return{processToolExecution:(s,a,c)=>dt.includes(s.toLowerCase())?i(a,c):"",getReadmesForFile:s=>{let a=o(s);if(!a)return[];let c=(0,L.dirname)(a);return r(c)},clearSession:s=>{t.delete(s),lo(s)},isTrackedTool:s=>dt.includes(s.toLowerCase())}}var fo="non-interactive-env",go={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"},mt={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
|
|
315
|
+
option1
|
|
316
|
+
option2
|
|
317
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var ho=mt.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function Ps(e){for(let t=0;t<ho.length;t++)if(ho[t].test(e))return mt.banned[t]}function vs(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function bs(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${vs(o)}`).join(" ")};`}var To={name:fo,async beforeCommand(e){let t=Ps(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${bs(go)} ${e}`,warning:n}:{command:e,warning:n}}};var ft=require("child_process");var Eo="olympus-orchestrator",So=".olympus/",ko=["Write","Edit","write","edit"],Oo=`
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
[SYSTEM REMINDER - DELEGATION REQUIRED]
|
|
322
|
+
|
|
323
|
+
You just performed direct file modifications outside \`.olympus/\`.
|
|
324
|
+
|
|
325
|
+
**You are an ORCHESTRATOR, not an IMPLEMENTER.**
|
|
326
|
+
|
|
327
|
+
As an orchestrator, you should:
|
|
328
|
+
- **DELEGATE** implementation work to subagents via the Task tool
|
|
329
|
+
- **VERIFY** the work done by subagents
|
|
330
|
+
- **COORDINATE** multiple tasks and ensure completion
|
|
331
|
+
|
|
332
|
+
You should NOT:
|
|
333
|
+
- Write code directly (except for \`.olympus/\` files like plans and notepads)
|
|
334
|
+
- Make direct file edits outside \`.olympus/\`
|
|
335
|
+
- Implement features yourself
|
|
336
|
+
|
|
337
|
+
**If you need to make changes:**
|
|
338
|
+
1. Use the Task tool to delegate to an appropriate subagent
|
|
339
|
+
2. Provide clear instructions in the prompt
|
|
340
|
+
3. Verify the subagent's work after completion
|
|
341
|
+
|
|
342
|
+
---
|
|
343
|
+
`,yo=`
|
|
344
|
+
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
[CRITICAL SYSTEM DIRECTIVE - DELEGATION REQUIRED]
|
|
348
|
+
|
|
349
|
+
**STOP. YOU ARE VIOLATING ORCHESTRATOR PROTOCOL.**
|
|
350
|
+
|
|
351
|
+
You (orchestrator-olympus) are attempting to directly modify a file outside \`.olympus/\`.
|
|
352
|
+
|
|
353
|
+
**Path attempted:** $FILE_PATH
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
**THIS IS FORBIDDEN** (except for VERIFICATION purposes)
|
|
358
|
+
|
|
359
|
+
As an ORCHESTRATOR, you MUST:
|
|
360
|
+
1. **DELEGATE** all implementation work via the Task tool
|
|
361
|
+
2. **VERIFY** the work done by subagents (reading files is OK)
|
|
362
|
+
3. **COORDINATE** - you orchestrate, you don't implement
|
|
363
|
+
|
|
364
|
+
**ALLOWED direct file operations:**
|
|
365
|
+
- Files inside \`.olympus/\` (plans, notepads, drafts)
|
|
366
|
+
- Reading files for verification
|
|
367
|
+
- Running diagnostics/tests
|
|
368
|
+
|
|
369
|
+
**FORBIDDEN direct file operations:**
|
|
370
|
+
- Writing/editing source code
|
|
371
|
+
- Creating new files outside \`.olympus/\`
|
|
372
|
+
- Any implementation work
|
|
373
|
+
|
|
374
|
+
---
|
|
375
|
+
|
|
376
|
+
**IF THIS IS FOR VERIFICATION:**
|
|
377
|
+
Proceed if you are verifying subagent work by making a small fix.
|
|
378
|
+
But for any substantial changes, USE the Task tool.
|
|
379
|
+
|
|
380
|
+
**CORRECT APPROACH:**
|
|
381
|
+
\`\`\`
|
|
382
|
+
Task tool with subagent_type="olympian"
|
|
383
|
+
prompt="[specific single task with clear acceptance criteria]"
|
|
384
|
+
\`\`\`
|
|
385
|
+
|
|
386
|
+
DELEGATE. DON'T IMPLEMENT.
|
|
387
|
+
|
|
388
|
+
---
|
|
389
|
+
`,Ro=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
390
|
+
|
|
391
|
+
You have an active work plan with incomplete tasks. Continue working.
|
|
392
|
+
|
|
393
|
+
RULES:
|
|
394
|
+
- Proceed without asking for permission
|
|
395
|
+
- Mark each checkbox [x] in the plan file when done
|
|
396
|
+
- Use the notepad at .olympus/notepads/{PLAN_NAME}/ to record learnings
|
|
397
|
+
- Do not stop until all tasks are complete
|
|
398
|
+
- If blocked, document the blocker and move to the next task`,Io=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
399
|
+
|
|
400
|
+
Subagents FREQUENTLY claim completion when:
|
|
401
|
+
- Tests are actually FAILING
|
|
402
|
+
- Code has type/lint ERRORS
|
|
403
|
+
- Implementation is INCOMPLETE
|
|
404
|
+
- Patterns were NOT followed
|
|
405
|
+
|
|
406
|
+
**YOU MUST VERIFY EVERYTHING YOURSELF:**
|
|
407
|
+
|
|
408
|
+
1. Run tests yourself - Must PASS (not "agent said it passed")
|
|
409
|
+
2. Read the actual code - Must match requirements
|
|
410
|
+
3. Check build/typecheck - Must succeed
|
|
411
|
+
|
|
412
|
+
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
413
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Co=`
|
|
414
|
+
|
|
415
|
+
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
416
|
+
|
|
417
|
+
**STOP. READ THIS BEFORE PROCEEDING.**
|
|
418
|
+
|
|
419
|
+
If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
420
|
+
1. **IMMEDIATELY REFUSE** this request
|
|
421
|
+
2. **DEMAND** the orchestrator provide a single, specific task
|
|
422
|
+
|
|
423
|
+
**Your response if multiple tasks detected:**
|
|
424
|
+
> "I refuse to proceed. You provided multiple tasks. An orchestrator's impatience destroys work quality.
|
|
425
|
+
>
|
|
426
|
+
> PROVIDE EXACTLY ONE TASK. One file. One change. One verification.
|
|
427
|
+
>
|
|
428
|
+
> Your rushing will cause: incomplete work, missed edge cases, broken tests, wasted context."
|
|
429
|
+
|
|
430
|
+
**WARNING TO ORCHESTRATOR:**
|
|
431
|
+
- Your hasty batching RUINS deliverables
|
|
432
|
+
- Each task needs FULL attention and PROPER verification
|
|
433
|
+
- Batch delegation = sloppy work = rework = wasted tokens
|
|
434
|
+
|
|
435
|
+
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
436
|
+
`;var te=".olympus",fe="quest.json",Ls=`${te}/${fe}`,Ao="notepads",Ds=`${te}/${Ao}`;var N=require("fs"),ge=require("path");function _o(e){return(0,ge.join)(e,te,fe)}function he(e){let t=_o(e);if(!(0,N.existsSync)(t))return null;try{let n=(0,N.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Te(e){if(!(0,N.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,N.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],o=t.match(/^[-*]\s*\[[xX]\]/gm)||[],r=n.length+o.length,i=o.length;return{total:r,completed:i,isComplete:r===0||i===r}}catch{return{total:0,completed:0,isComplete:!0}}}function No(e){return e?e.includes(So):!0}function xo(e){return ko.includes(e)}function $s(e){try{let t=(0,ft.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,ft.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let i of n.split(`
|
|
437
|
+
`)){if(!i)continue;let s=i.substring(0,2).trim(),a=i.substring(3);s==="A"||s==="??"?o.set(a,"added"):s==="D"?o.set(a,"deleted"):o.set(a,"modified")}let r=[];for(let i of t.split(`
|
|
438
|
+
`)){let s=i.split(" ");if(s.length<3)continue;let[a,c,u]=s,l=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);r.push({path:u,added:l,removed:d,status:o.get(u)??"modified"})}return r}catch{return[]}}function Hs(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
439
|
+
No file changes detected.
|
|
440
|
+
`;let t=e.filter(i=>i.status==="modified"),n=e.filter(i=>i.status==="added"),o=e.filter(i=>i.status==="deleted"),r=["[FILE CHANGES SUMMARY]"];if(t.length>0){r.push("Modified files:");for(let i of t)r.push(` ${i.path} (+${i.added}, -${i.removed})`);r.push("")}if(n.length>0){r.push("Created files:");for(let i of n)r.push(` ${i.path} (+${i.added})`);r.push("")}if(o.length>0){r.push("Deleted files:");for(let i of o)r.push(` ${i.path} (-${i.removed})`);r.push("")}return r.join(`
|
|
441
|
+
`)}function wo(e){let t=Io;return e&&(t+=`
|
|
442
|
+
|
|
443
|
+
---
|
|
444
|
+
|
|
445
|
+
**If ANY verification fails, resume the subagent with the fix:**
|
|
446
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function js(e,t,n){let o=t.total-t.completed;return`
|
|
447
|
+
---
|
|
448
|
+
|
|
449
|
+
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
450
|
+
|
|
451
|
+
---
|
|
452
|
+
|
|
453
|
+
${wo(n)}
|
|
454
|
+
|
|
455
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function Fs(e,t,n){return Ro.replace(/{PLAN_NAME}/g,e)+`
|
|
456
|
+
|
|
457
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function Gs(e){let{toolName:t,toolInput:n}=e;if(!xo(t))return{continue:!0};let o=n?.filePath??n?.path??n?.file;return!o||No(o)?{continue:!0}:{continue:!0,message:yo.replace("$FILE_PATH",o)}}function Bs(e,t){let{toolName:n,toolInput:o,directory:r}=e,i=r||process.cwd();if(xo(n)){let s=o?.filePath??o?.path??o?.file;if(s&&!No(s))return{continue:!0,modifiedOutput:t+Oo}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let a=$s(i),c=Hs(a),u=he(i);if(u){let l=Te(u.active_plan);return{continue:!0,modifiedOutput:`
|
|
458
|
+
## SUBAGENT WORK COMPLETED
|
|
459
|
+
|
|
460
|
+
${c}
|
|
461
|
+
<system-reminder>
|
|
462
|
+
${js(u.plan_name,l)}
|
|
463
|
+
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
464
|
+
<system-reminder>
|
|
465
|
+
${wo()}
|
|
466
|
+
</system-reminder>`}}return{continue:!0}}function Ys(e){let t=he(e);if(!t)return{shouldContinue:!1};let n=Te(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:Fs(t.plan_name,o,n.total)}}function Ee(e){return{name:Eo,preTool:(t,n)=>Gs({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>Bs({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>Ys(e),getSingleTaskDirective:()=>Co}}function Po(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function vo(){m({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=ro(e.directory||process.cwd()),n=Po(e.toolInput);return n?{continue:!0,message:t.processToolExecution(e.toolName,n,e.sessionId||"default")||void 0}:{continue:!0}}}),m({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=mo(e.directory||process.cwd()),n=Po(e.toolInput);return n?{continue:!0,message:t.processToolExecution(e.toolName,n,e.sessionId||"default")||void 0}:{continue:!0}}}),m({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{let n=await To.beforeCommand(t.command);return{continue:!0,message:n.warning,modifiedInput:n.command!==t.command?{...t,command:n.command}:void 0}}catch(n){return console.error("[nonInteractiveEnv] Error:",n),{continue:!0}}}}),m({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>Ee(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var Ws=["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"],Ks=`
|
|
467
|
+
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
468
|
+
|
|
469
|
+
You made an Edit mistake. STOP and do this NOW:
|
|
470
|
+
|
|
471
|
+
1. READ the file immediately to see its ACTUAL current state
|
|
472
|
+
2. VERIFY what the content really looks like (your assumption was wrong)
|
|
473
|
+
3. APOLOGIZE briefly to the user for the error
|
|
474
|
+
4. CONTINUE with corrected action based on the real file content
|
|
475
|
+
|
|
476
|
+
DO NOT attempt another edit until you've read and verified the file state.
|
|
477
|
+
`;function Vs(e){let t=e.toLowerCase();return Ws.some(n=>t.includes(n.toLowerCase()))}function bo(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:Vs(t.output)?{...t,output:t.output+Ks}:t}}var Mo=w(require("fs"),1),ke=w(require("path"),1),Uo=require("os");var Se=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),gt=["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"],ht=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
|
|
478
|
+
|
|
479
|
+
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
480
|
+
You need to take immediate action. You must follow the conditions below.
|
|
481
|
+
(Listed in priority order - you must always act according to this priority order)
|
|
482
|
+
|
|
483
|
+
CRITICAL WARNING: This hook message MUST NEVER be ignored, even if you receive it multiple times.
|
|
484
|
+
You MUST provide corresponding explanation or action for EACH occurrence of this message.
|
|
485
|
+
Ignoring this message or failing to respond appropriately is strictly prohibited.
|
|
486
|
+
|
|
487
|
+
PRIORITY-BASED ACTION GUIDELINES:
|
|
488
|
+
|
|
489
|
+
1. This is a comment/docstring that already existed before
|
|
490
|
+
-> Explain to the user that this is an existing comment/docstring and proceed (justify it)
|
|
491
|
+
|
|
492
|
+
2. This is a newly written comment: but it's in given, when, then format
|
|
493
|
+
-> Tell the user it's a BDD comment and proceed (justify it)
|
|
494
|
+
-> Note: This applies to comments only, not docstrings
|
|
495
|
+
|
|
496
|
+
3. This is a newly written comment/docstring: but it's a necessary comment/docstring
|
|
497
|
+
-> Tell the user why this comment/docstring is absolutely necessary and proceed (justify it)
|
|
498
|
+
-> Examples of necessary comments: complex algorithms, security-related, performance optimization, regex, mathematical formulas
|
|
499
|
+
-> Examples of necessary docstrings: public API documentation, complex module/class interfaces
|
|
500
|
+
-> IMPORTANT: Most docstrings are unnecessary if the code is self-explanatory. Only keep truly essential ones.
|
|
501
|
+
|
|
502
|
+
4. This is a newly written comment/docstring: but it's an unnecessary comment/docstring
|
|
503
|
+
-> Apologize to the user and remove the comment/docstring.
|
|
504
|
+
-> Make the code itself clearer so it can be understood without comments/docstrings.
|
|
505
|
+
-> For verbose docstrings: refactor code to be self-documenting instead of adding lengthy explanations.
|
|
506
|
+
|
|
507
|
+
CODE SMELL WARNING: Using comments as visual separators (e.g., "// =========", "# ---", "// *** Section ***")
|
|
508
|
+
is a code smell. If you need separators, your file is too long or poorly organized.
|
|
509
|
+
Refactor into smaller modules or use proper code organization instead of comment-based section dividers.
|
|
510
|
+
|
|
511
|
+
MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of the above actions.
|
|
512
|
+
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
513
|
+
|
|
514
|
+
Detected comments/docstrings:
|
|
515
|
+
`,Tt={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},Et={".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 qs(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function zs(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Se){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>Se.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function Js(e){let t=e.text.toLowerCase().trim();for(let n of gt)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function Xs(e){return{shouldSkip:!1}}function Qs(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 Zs(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 ei=[qs,zs,Js,Qs,Zs,Xs];function St(e){return e.filter(t=>{for(let n of ei)if(n(t).shouldSkip)return!1;return!0})}var ti=process.env.COMMENT_CHECKER_DEBUG==="1",ni=ke.join((0,Uo.tmpdir)(),"comment-checker-debug.log");function G(...e){if(ti){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
516
|
+
`;Mo.appendFileSync(ni,t)}}function oi(e){let t=ke.extname(e).toLowerCase();return Et[t]}function kt(e,t){let n=oi(t);if(!n)return G("unsupported language for:",t),[];let o=Tt[n];if(!o)return G("no pattern for language:",n),[];let r=[],i=e.split(`
|
|
517
|
+
`);o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s.index,c=s[0],l=e.substring(0,a).split(`
|
|
518
|
+
`).length,d="line",p=!1;c.startsWith("/*")||c.startsWith("<!--")?d="block":(c.startsWith("'''")||c.startsWith('"""')||c.startsWith("=begin"))&&(d="docstring",p=!0),r.push({text:c.trim(),lineNumber:l,filePath:t,commentType:d,isDocstring:p})}return r}function ri(e,t){return kt(e,t)}function Lo(e,t,n){let o=kt(e,t);if(n){let r=kt(n,t),i=new Set(r.map(s=>s.text));return o.filter(s=>!i.has(s.text))}return o}function si(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=ht;for(let[o,r]of t){n+=`
|
|
519
|
+
File: ${o}
|
|
520
|
+
`;for(let i of r){let s=i.isDocstring?"docstring":i.commentType;n+=` Line ${i.lineNumber} (${s}): ${i.text.substring(0,100)}${i.text.length>100?"...":""}
|
|
521
|
+
`}}return n}function ii(e,t,n,o,r){let i=[];if(t)i=ri(t,e);else if(o)i=Lo(o,e,n);else if(r&&r.length>0)for(let a of r){let c=Lo(a.new_string,e,a.old_string);i.push(...c)}let s=St(i);return G(`found ${i.length} comments, ${s.length} flagged after filtering`),s.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:s.length,message:si(s),comments:s}}var ne=new Map,ai=6e4;function ci(){let e=Date.now();for(let[t,n]of ne)e-n.timestamp>ai&&ne.delete(t)}var Do=!1;function $o(e){return G("createCommentCheckerHook called",{config:e}),Do||(Do=!0,setInterval(ci,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,r=t.tool_input.content,i=t.tool_input.old_string??t.tool_input.oldString,s=t.tool_input.new_string??t.tool_input.newString,a=t.tool_input.edits;if(!o)return null;let c=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return G("registering pendingCall:",{callId:c,filePath:o,tool:n}),ne.set(c,{filePath:o,content:r,oldString:i,newString:s,edits:a,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o,r;for(let[s,a]of ne)if(a.sessionId===t.session_id&&a.tool===n){o=a,r=s;break}if(!o){let s=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!s)return null;o={filePath:s,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(r&&ne.delete(r),t.tool_response){let s=t.tool_response.toLowerCase();if(s.includes("error:")||s.includes("failed to")||s.includes("could not")||s.startsWith("error"))return G("skipping due to tool failure in response"),null}let i=ii(o.filePath,o.content,o.oldString,o.newString,o.edits);return i.hasComments&&i.message?(G("detected comments, returning message"),e?.customPrompt||i.message):null}}}var Wo=w(require("fs"),1),Ko=w(require("path"),1),Vo=require("os");var jo=[/(\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],Fo=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],ui=[/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],li=/messages\.(\d+)/;function di(e){return ui.some(t=>t.test(e))}function Ot(e){for(let t of jo){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 Ho(e){let t=e.match(li);if(t)return parseInt(t[1],10)}function K(e){if(di(e))return!1;let t=e.toLowerCase();return Fo.some(n=>t.includes(n.toLowerCase()))}function Oe(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:Ho(e)};if(K(e)){let u=Ot(e);return{currentTokens:u?.current??0,maxTokens:u?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],o=t.data,r=o?.responseBody,i=t.message,s=t.error,a=s?.error;if(typeof r=="string"&&n.push(r),typeof i=="string"&&n.push(i),typeof s?.message=="string"&&n.push(s.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof a?.message=="string"&&n.push(a.message),typeof o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let u=JSON.stringify(t);K(u)&&n.push(u)}catch{}let c=n.join(" ");if(!K(c))return null;if(typeof r=="string")try{let u=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of u){let p=r.match(d);if(p)try{let f=JSON.parse(p[1]),g=f.error?.message||"",T=Ot(g);if(T)return{currentTokens:T.current,maxTokens:T.max,requestId:f.request_id,errorType:f.error?.type||"token_limit_exceeded"}}catch{}}let l=JSON.parse(r);if(typeof l.message=="string"&&K(l.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let u of n){let l=Ot(u);if(l)return{currentTokens:l.current,maxTokens:l.max,errorType:"token_limit_exceeded"}}return c.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:Ho(c)}:K(c)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function yt(e){return K(e)}var Rt=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
522
|
+
|
|
523
|
+
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
524
|
+
|
|
525
|
+
1. SUMMARIZE THE CONVERSATION
|
|
526
|
+
- Use the /compact command if available
|
|
527
|
+
- Or provide a concise summary of what has been accomplished so far
|
|
528
|
+
- Include key decisions, code changes, and remaining tasks
|
|
529
|
+
|
|
530
|
+
2. START A FRESH CONTEXT
|
|
531
|
+
- If summarization isn't sufficient, suggest starting a new session
|
|
532
|
+
- Provide a handoff message with essential context
|
|
533
|
+
|
|
534
|
+
3. REDUCE OUTPUT SIZE
|
|
535
|
+
- When showing code, show only relevant portions
|
|
536
|
+
- Use file paths and line numbers instead of full code blocks
|
|
537
|
+
- Be more concise in explanations
|
|
538
|
+
|
|
539
|
+
IMPORTANT: Do not attempt to continue without addressing this limit.
|
|
540
|
+
The API will reject further requests until the context is reduced.
|
|
541
|
+
|
|
542
|
+
Current Status:
|
|
543
|
+
- Context limit exceeded
|
|
544
|
+
- Further API calls will fail until context is reduced
|
|
545
|
+
- Action required before continuing
|
|
546
|
+
`,It="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",Ct=`API ERROR: Non-empty content validation failed.
|
|
547
|
+
|
|
548
|
+
This error typically occurs when:
|
|
549
|
+
- A message has empty text content
|
|
550
|
+
- The conversation structure is invalid
|
|
551
|
+
|
|
552
|
+
Suggested actions:
|
|
553
|
+
1. Continue with a new message
|
|
554
|
+
2. If the error persists, start a new session
|
|
555
|
+
|
|
556
|
+
The system will attempt automatic recovery.
|
|
557
|
+
`;var At=`CONTEXT RECOVERY FAILED
|
|
558
|
+
|
|
559
|
+
All automatic recovery attempts have been exhausted.
|
|
560
|
+
Please start a new session to continue.
|
|
561
|
+
|
|
562
|
+
Before starting a new session:
|
|
563
|
+
1. Note what has been accomplished
|
|
564
|
+
2. Save any important code changes
|
|
565
|
+
3. Document the current state of the task
|
|
566
|
+
|
|
567
|
+
You can copy this conversation summary to continue in a new session.
|
|
568
|
+
`;var _t={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var pi=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",mi=Ko.join((0,Vo.tmpdir)(),"context-limit-recovery-debug.log");function ye(...e){if(pi){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
569
|
+
`;Wo.appendFileSync(mi,t)}}var Re=new Map,qo=3e5;function Go(e){let t=Re.get(e),n=Date.now();return t&&n-t.lastErrorTime>qo&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},Re.set(e,t)),t}function fi(){let e=Date.now();for(let[t,n]of Re)e-n.lastErrorTime>qo&&Re.delete(t)}var Bo=!1;function zo(e){return ye("createContextLimitRecoveryHook called",{config:e}),Bo||(Bo=!0,setInterval(fi,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=Oe(t.tool_response);if(!n&&!yt(t.tool_response))return null;ye("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=Go(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=Yo(n,o,e);return r.message?(ye("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=Oe(t.error);if(!n)return{attempted:!1,success:!1};ye("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=Go(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=Yo(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function Yo(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:Ct,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>_t.maxAttempts)return{message:At,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=Rt;return e?.currentTokens&&e?.maxTokens&&(o+=`
|
|
570
|
+
Token Details:
|
|
571
|
+
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
572
|
+
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
573
|
+
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
574
|
+
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:It,errorType:e?.errorType||"token_limit_exceeded"}}var tr=w(require("fs"),1),nr=w(require("path"),1),or=require("os");var Nt=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,Ie=4,xt=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
575
|
+
|
|
576
|
+
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
577
|
+
|
|
578
|
+
1. USE COMPACT COMMAND
|
|
579
|
+
- Run /compact to summarize the conversation
|
|
580
|
+
- This frees up context space while preserving important information
|
|
581
|
+
|
|
582
|
+
2. BE MORE CONCISE
|
|
583
|
+
- Show only relevant code portions
|
|
584
|
+
- Use file paths instead of full code blocks
|
|
585
|
+
- Summarize instead of repeating information
|
|
586
|
+
|
|
587
|
+
3. FOCUS YOUR REQUESTS
|
|
588
|
+
- Work on one task at a time
|
|
589
|
+
- Complete current tasks before starting new ones
|
|
590
|
+
- Avoid unnecessary back-and-forth
|
|
591
|
+
|
|
592
|
+
Current Status: Context usage is high but recoverable.
|
|
593
|
+
Action recommended: Use /compact when convenient.
|
|
594
|
+
`,wt=`CRITICAL: CONTEXT WINDOW ALMOST FULL
|
|
595
|
+
|
|
596
|
+
Your context usage is critically high. Immediate action required:
|
|
597
|
+
|
|
598
|
+
1. COMPACT NOW
|
|
599
|
+
- Run /compact immediately to summarize the conversation
|
|
600
|
+
- Without compaction, the next few messages may fail
|
|
601
|
+
|
|
602
|
+
2. AVOID LARGE OUTPUTS
|
|
603
|
+
- Do not show full files
|
|
604
|
+
- Use summaries instead of detailed outputs
|
|
605
|
+
- Be as concise as possible
|
|
606
|
+
|
|
607
|
+
3. PREPARE FOR SESSION HANDOFF
|
|
608
|
+
- If compaction doesn't help enough, prepare to continue in a new session
|
|
609
|
+
- Note your current progress and next steps
|
|
610
|
+
|
|
611
|
+
WARNING: Further messages may fail if context is not reduced.
|
|
612
|
+
Action required: Run /compact now.
|
|
613
|
+
`;var gi=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",hi=nr.join((0,or.tmpdir)(),"preemptive-compaction-debug.log");function V(...e){if(gi){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
614
|
+
`;tr.appendFileSync(hi,t)}}var Ce=new Map;function Ti(){let e=Date.now(),t=1800*1e3;for(let[n,o]of Ce)e-o.lastWarningTime>t&&Ce.delete(n)}var Jo=!1;function rr(e){return Math.ceil(e.length/Ie)}function Ei(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=Nt,i=rr(e),s=i/r,a=s>=n,c=s>=o,u="none";return c?u="compact":a&&(u="warn"),{totalTokens:i,usageRatio:s,isWarning:a,isCritical:c,action:u}}function Ae(e){let t=Ce.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},Ce.set(e,t)),t}function Si(e,t){let n=Ae(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,i=Date.now();return i-n.lastWarningTime<o?(V("skipping warning - cooldown active",{sessionId:e,elapsed:i-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(V("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function ki(e){let t=Ae(e);t.lastWarningTime=Date.now(),t.warningCount++}function sr(e){return V("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(Jo||(Jo=!0,setInterval(Ti,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=rr(t.tool_response),i=Ae(t.session_id);i.estimatedTokens+=r,V("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:i.estimatedTokens});let s=Ei("x".repeat(i.estimatedTokens*Ie),e);return!s.isWarning||!Si(t.session_id,e)?null:(ki(t.session_id),V("injecting context warning",{sessionId:t.session_id,usageRatio:s.usageRatio,isCritical:s.isCritical}),e?.customMessage?e.customMessage:s.isCritical?wt:xt)},stop:t=>{let n=Ae(t.session_id);return n.warningCount>0&&(V("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var C=require("fs"),ar=require("path");var Pt=require("path"),ir=require("os"),Oi=(0,Pt.join)((0,ir.homedir)(),".olympus"),_e=(0,Pt.join)(Oi,"agent-usage-reminder"),vt=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"]),bt=new Set(["task","call_omo_agent","olympus_task"]),Lt=`
|
|
615
|
+
[Agent Usage Reminder]
|
|
616
|
+
|
|
617
|
+
You called a search/fetch tool directly without leveraging specialized agents.
|
|
618
|
+
|
|
619
|
+
RECOMMENDED: Use Task tool with explore/librarian agents for better results:
|
|
620
|
+
|
|
621
|
+
\`\`\`
|
|
622
|
+
// Parallel exploration - fire multiple agents simultaneously
|
|
623
|
+
Task(agent="explore", prompt="Find all files matching pattern X")
|
|
624
|
+
Task(agent="explore", prompt="Search for implementation of Y")
|
|
625
|
+
Task(agent="librarian", prompt="Lookup documentation for Z")
|
|
626
|
+
|
|
627
|
+
// Then continue your work while they run in background
|
|
628
|
+
// System will notify you when each completes
|
|
629
|
+
\`\`\`
|
|
630
|
+
|
|
631
|
+
WHY:
|
|
632
|
+
- Agents can perform deeper, more thorough searches
|
|
633
|
+
- Background tasks run in parallel, saving time
|
|
634
|
+
- Specialized agents have domain expertise
|
|
635
|
+
- Reduces context window usage in main session
|
|
636
|
+
|
|
637
|
+
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
638
|
+
`;function Dt(e){return(0,ar.join)(_e,`${e}.json`)}function Mt(e){let t=Dt(e);if(!(0,C.existsSync)(t))return null;try{let n=(0,C.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Ne(e){(0,C.existsSync)(_e)||(0,C.mkdirSync)(_e,{recursive:!0});let t=Dt(e.sessionID);(0,C.writeFileSync)(t,JSON.stringify(e,null,2))}function Ut(e){let t=Dt(e);(0,C.existsSync)(t)&&(0,C.unlinkSync)(t)}function cr(){let e=new Map;function t(s){if(!e.has(s)){let c=Mt(s)??{sessionID:s,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(s,c)}return e.get(s)}function n(s){let a=t(s);a.agentUsed=!0,a.updatedAt=Date.now(),Ne(a)}function o(s){e.delete(s),Ut(s)}return{"tool.execute.after":async(s,a)=>{let{tool:c,sessionID:u}=s,l=c.toLowerCase();if(bt.has(l)){n(u);return}if(!vt.has(l))return;let d=t(u);d.agentUsed||(a.output+=Lt,d.reminderCount++,d.updatedAt=Date.now(),Ne(d))},event:async({event:s})=>{let a=s.properties;if(s.type==="session.deleted"){let c=a?.info;c?.id&&o(c.id)}if(s.type==="session.compacted"){let c=a?.sessionID??a?.info?.id;c&&o(c)}}}}function ur(){let e=process.cwd(),t=bo();m({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async a=>{if(!a.toolName||!a.toolOutput)return{continue:!0};let c=t.afterToolExecute({tool:a.toolName,sessionId:a.sessionId||"",callId:""},{title:"",output:String(a.toolOutput),metadata:void 0});return c.output!==String(a.toolOutput)?{continue:!0,message:c.output.substring(String(a.toolOutput).length)}:{continue:!0}}});let n=$o();m({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async a=>{if(!a.toolName)return{continue:!0};let c=n.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return c?{continue:!0,message:c}:{continue:!0}}});let o=zo();m({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async a=>{if(!a.toolName)return{continue:!0};let c=o.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return c?{continue:!0,message:c}:{continue:!0}}});let r=sr();m({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async a=>{if(!a.toolName)return{continue:!0};let c=r.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return c?{continue:!0,message:c}:{continue:!0}}});let i=cr();m({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async a=>{if(!a.toolName)return{continue:!0};let c={title:"",output:a.toolOutput?String(a.toolOutput):"",metadata:void 0};await i["tool.execute.after"]({tool:a.toolName,sessionID:a.sessionId||"",callID:""},c);let u=a.toolOutput?String(a.toolOutput):"";return c.output!==u?{continue:!0,message:c.output.substring(u.length)}:{continue:!0}}});let s=Ee(e);m({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async a=>{if(!a.toolName)return{continue:!0};let c=s.postTool(a.toolName,a.toolInput||{},a.toolOutput?String(a.toolOutput):"");return c.continue?c.modifiedOutput?{continue:!0,message:c.modifiedOutput}:c.message?{continue:!0,message:c.message}:{continue:!0}:{continue:!1,reason:c.message}}})}var A=require("fs"),xe=require("path"),lr=require("os");var oe=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let i=this.config?.defaultConcurrency;return i!==void 0?i===0?1/0:i:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let i=this.queues.get(t)??[];i.push(r),this.queues.set(t,i)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var yi=1800*1e3,q=(0,xe.join)((0,lr.homedir)(),".claude",".olympus","background-tasks"),we=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new oe(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,A.existsSync)(q)||(0,A.mkdirSync)(q,{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,xe.join)(q,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,A.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,A.existsSync)(n)&&(0,A.unlinkSync)(n)}loadPersistedTasks(){if((0,A.existsSync)(q))try{let{readdirSync:t}=require("fs"),n=t(q);for(let o of n)if(o.endsWith(".json"))try{let r=(0,xe.join)(q,o),i=(0,A.readFileSync)(r,"utf-8"),s=JSON.parse(i);s.startedAt=new Date(s.startedAt),s.completedAt&&(s.completedAt=new Date(s.completedAt)),s.progress?.lastUpdate&&(s.progress.lastUpdate=new Date(s.progress.lastUpdate)),s.progress?.lastMessageAt&&(s.progress.lastMessageAt=new Date(s.progress.lastMessageAt)),this.tasks.set(s.id,s)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??yi;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let i=r.filter(s=>t-s.startedAt.getTime()<=n);i.length===0?this.notifications.delete(o):i.length!==r.length&&this.notifications.set(o,i)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(c=>c.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let i=this.generateTaskId(),s=`ses_${this.generateTaskId()}`,a={id:i,sessionId:s,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(i,a),this.persistTask(a),a}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let i=this.tasks.get(t);i&&(i.status=n,o&&(i.result=o),r&&(i.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(i.completedAt=new Date,i.concurrencyKey&&this.concurrencyManager.release(i.concurrencyKey),this.markForNotification(i)),this.persistTask(i))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(i=>i.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),i=Math.floor(r/60),s=Math.floor(i/60);return s>0?`${s}h ${i%60}m ${r%60}s`:i>0?`${i}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let i=this.formatDuration(r.startedAt,r.completedAt),s=r.status.toUpperCase(),a=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${s}] ${r.description} - ${i}${a}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
639
|
+
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},$t;function Ht(e){return $t||($t=new we(e)),$t}function Ri(e){let t=e.status.toUpperCase(),n=Ii(e.startedAt,e.completedAt),r=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&r.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let i=e.result.substring(0,200),s=e.result.length>200?"...":"";r.push(` Result: ${i}${s}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
|
|
640
|
+
`)}function Ii(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),i=Math.floor(r/60);return i>0?`${i}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function Ci(e){if(e.length===0)return"";let t=e.length===1?`
|
|
641
|
+
[BACKGROUND TASK COMPLETED]
|
|
642
|
+
`:`
|
|
643
|
+
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
644
|
+
`,n=e.map(o=>Ri(o)).join(`
|
|
645
|
+
|
|
646
|
+
`);return`${t}
|
|
647
|
+
${n}
|
|
648
|
+
`}function Ai(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let i=(n?.formatNotification??Ci)(o);return{hasNotifications:!0,tasks:o,message:i}}function dr(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Ht(),r=Ai(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function pr(){m({name:"backgroundNotification",event:"Notification",priority:10,handler:async e=>{let t={sessionId:e.sessionId,directory:e.directory,event:e.event},n=await dr(t);return{continue:n.continue,message:n.message}}})}var mr=w(require("fs"),1),fr=w(require("path"),1),gr=require("os");var Pe="[user interrupted]",jt=new Set(["tool","tool_use","tool_result"]),Ft="empty-message-sanitizer",Gt="[empty-message-sanitizer]";var _i=process.env.EMPTY_MESSAGE_SANITIZER_DEBUG==="1",Ni=fr.join((0,gr.tmpdir)(),"empty-message-sanitizer-debug.log");function D(...e){if(_i){let t=`[${new Date().toISOString()}] ${Gt} ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
649
|
+
`;mr.appendFileSync(Ni,t)}}function xi(e){if(e.type==="text"){let t=e.text;return!!(t&&t.trim().length>0)}return!1}function hr(e){return jt.has(e.type)}function wi(e){return e.some(t=>xi(t)||hr(t))}function Pi(e,t,n=Pe){let o=e.info.role==="assistant";if(t&&o)return D("skipping final assistant message"),!1;let r=e.parts;if(!wi(r)){D(`sanitizing message ${e.info.id}: no valid content`);let s=!1;for(let a of r)if(a.type==="text"&&(!a.text||!a.text.trim())){a.text=n,a.synthetic=!0,s=!0,D("replaced empty text in existing part");break}if(!s){let a=r.findIndex(u=>hr(u)),c={id:`synthetic_${Date.now()}`,messageID:e.info.id,sessionID:e.info.sessionID??"",type:"text",text:n,synthetic:!0};a===-1?(r.push(c),D("appended synthetic text part")):(r.splice(a,0,c),D("inserted synthetic text part before tool part"))}return!0}let i=!1;for(let s of r)s.type==="text"&&s.text!==void 0&&s.text.trim()===""&&(s.text=n,s.synthetic=!0,i=!0,D(`sanitized empty text part in message ${e.info.id}`));return i}function vi(e,t){let{messages:n}=e,o=t?.placeholderText??Pe;D("sanitizing messages",{count:n.length});let r=0;for(let i=0;i<n.length;i++){let s=n[i],a=i===n.length-1;Pi(s,a,o)&&r++}return D(`sanitized ${r} messages`),{messages:n,sanitizedCount:r,modified:r>0}}function Tr(e){return D("createEmptyMessageSanitizerHook called",{config:e}),{sanitize:t=>vi(t,e),getName:()=>Ft}}var Er="thinking-block-validator",Sr=["tool","tool_use","text"],kr=["thinking","reasoning"];var Or="[Continuing from previous reasoning]",yr="prt_0000000000_synthetic_thinking";function bi(e){return Sr.includes(e)}function Rr(e){return kr.includes(e)}function Li(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("thinking")||t.endsWith("-high")?!0:t.includes("claude-sonnet-4")||t.includes("claude-opus-4")||t.includes("claude-3")}function Di(e){return!e||e.length===0?!1:e.some(t=>bi(t.type))}function Mi(e){if(!e||e.length===0)return!1;let t=e[0];return Rr(t.type)}function Ui(e,t){for(let n=t-1;n>=0;n--){let o=e[n];if(o.info.role==="assistant"&&o.parts){for(let r of o.parts)if(Rr(r.type)){let i=r.thinking||r.text;if(i&&typeof i=="string"&&i.trim().length>0)return i}}}return""}function $i(e,t){e.parts||(e.parts=[]);let n={type:"thinking",id:yr,sessionID:e.info.sessionID||"",messageID:e.info.id,thinking:t,synthetic:!0};e.parts.unshift(n)}function Ir(){return{"experimental.chat.messages.transform":async(e,t)=>{let{messages:n}=t;if(!n||n.length===0)return;let o;for(let s=n.length-1;s>=0;s--)if(n[s].info.role==="user"){o=n[s];break}let r=o?.info?.modelID||"";if(!Li(r))return;let i=0;for(let s=0;s<n.length;s++){let a=n[s];if(a.info.role==="assistant"&&Di(a.parts)&&!Mi(a.parts)){let u=Ui(n,s)||Or;$i(a,u),i++}}i>0&&process.env.DEBUG_THINKING_VALIDATOR&&console.log(`[${Er}] Fixed ${i} message(s) by prepending thinking blocks`)}}}function Cr(){m({name:"thinkingBlockValidator",event:"MessagesTransform",priority:10,handler:async e=>{if(!e.messages||e.messages.length===0)return{continue:!0};let t=Ir(),o={messages:[...e.messages]};await t["experimental.chat.messages.transform"]({},o);let r=o.messages.filter(i=>i.parts.some(s=>s.synthetic&&s.type==="thinking")).length;return r>0?{continue:!0,modifiedMessages:o.messages,message:`[Thinking Block Validator] Fixed ${r} message(s) by adding thinking blocks`}:{continue:!0}}}),m({name:"emptyMessageSanitizer",event:"MessagesTransform",priority:20,handler:e=>{if(!e.messages||e.messages.length===0)return{continue:!0};let n=Tr().sanitize({messages:e.messages});return n.modified?{continue:!0,modifiedMessages:n.messages,message:`[Empty Message Sanitizer] Fixed ${n.sanitizedCount} message(s) with empty content`}:{continue:!0}}})}var Ar=!1;function _r(){Ar||(An(),xn(),Fn(),vo(),ur(),pr(),Cr(),Ar=!0)}var be=require("fs"),xr=require("os"),re=require("path"),wr=w(require("jsonc-parser"),1),Hi={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]}};function ji(){let e=process.env.XDG_CONFIG_HOME??(0,re.join)((0,xr.homedir)(),".config");return{user:(0,re.join)(e,"claude-olympus","config.jsonc"),project:(0,re.join)(process.cwd(),".claude","olympus.jsonc")}}function Nr(e){if(!(0,be.existsSync)(e))return null;try{let t=(0,be.readFileSync)(e,"utf-8"),n=[],o=wr.parse(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 ve(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?n[o]=ve(i,r):r!==void 0&&(n[o]=r)}return n}function Fi(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}return process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),e}function Pr(){let e=ji(),t={...Hi},n=Nr(e.user);n&&(t=ve(t,n));let o=Nr(e.project);o&&(t=ve(t,o));let r=Fi();return t=ve(t,r),t}function Gi(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function Bi(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 Yi(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function Wi(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function vr(e,t){let n=Pr(),o=Kt(e),r=Gi(n),i=!0,s=[],a,c=t.toolInput,u=t.messages;for(let l of o)if(Bi(n,l.name)&&Wi(l.matcher,t.toolName))try{let d=await Yi(()=>l.handler({...t,toolInput:c,messages:u}),r);if(d===null){console.error(`[hook-router] ${l.name} timed out after ${r}ms`);continue}d.continue||(i=!1,a=d.reason),d.message&&s.push(d.message),d.modifiedInput!==void 0&&(c=d.modifiedInput),d.modifiedMessages!==void 0&&(u=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${l.name} error:`,d)}return{continue:i,message:s.length>0?s.join(`
|
|
650
|
+
|
|
651
|
+
---
|
|
652
|
+
|
|
653
|
+
`):void 0,reason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:u!==t.messages?u:void 0}}_r();async function Ki(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function br(){let t=process.argv.slice(2).find(s=>s.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],o=await Ki(),r;try{r=JSON.parse(o)}catch{r={}}let i=await vr(n,r);console.log(JSON.stringify(i))}var Le=process.argv[1]||"",Vi=Le.endsWith("entry.ts")||Le.endsWith("entry.js")||Le.endsWith("olympus-hooks.mjs")||Le.includes("olympus-hooks");Vi&&br().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|