@happycastle/oh-my-openclaw 0.13.4 → 0.14.1

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.
@@ -1,6 +1,6 @@
1
1
  import { LOG_PREFIX } from '../constants.js';
2
- import { getActivePersona, setActivePersonaId, resetPersonaState } from '../utils/persona-state.js';
3
- import { resolvePersonaId, listPersonas, DEFAULT_PERSONA_ID } from '../agents/persona-prompts.js';
2
+ import { getActivePersona, setActivePersonaId, resetPersonaState, replaceAgentsMd, restoreAgentsMdToDefault } from '../utils/persona-state.js';
3
+ import { resolvePersonaId, listPersonas, readPersonaPrompt, DEFAULT_PERSONA_ID } from '../agents/persona-prompts.js';
4
4
  function getDisplayName(personaId) {
5
5
  const persona = listPersonas().find((p) => p.id === personaId);
6
6
  return persona ? `${persona.emoji} ${persona.displayName}` : personaId;
@@ -17,22 +17,25 @@ export function registerPersonaCommands(api) {
17
17
  if (!args) {
18
18
  const previousId = await getActivePersona();
19
19
  await setActivePersonaId(DEFAULT_PERSONA_ID);
20
+ const content = await readPersonaPrompt(DEFAULT_PERSONA_ID);
21
+ await replaceAgentsMd(content);
20
22
  const name = getDisplayName(DEFAULT_PERSONA_ID);
21
23
  const switchNote = previousId && previousId !== DEFAULT_PERSONA_ID
22
24
  ? `\n\nSwitched from **${getDisplayName(previousId)}**.`
23
25
  : '';
24
26
  return {
25
- text: `# OmOC Mode: ON\n\nActive persona: **${name}**${switchNote}\n\nApplied immediately your next message will use this persona.\n\nUse \`/omoc list\` to see available personas, or \`/omoc <name>\` to switch.`,
27
+ text: `# OmOC Mode: ON\n\nActive persona: **${name}**${switchNote}\n\nAGENTS.md replaced with persona prompt. Your next message will use this persona.\n\nUse \`/omoc list\` to see available personas, or \`/omoc <name>\` to switch.`,
26
28
  };
27
29
  }
28
30
  if (args === 'off') {
29
31
  const wasActive = await getActivePersona();
30
32
  const wasName = wasActive ? getDisplayName(wasActive) : null;
31
33
  await resetPersonaState();
34
+ await restoreAgentsMdToDefault();
32
35
  return {
33
36
  text: wasName
34
- ? `# OmOC Mode: OFF\n\nPersona **${wasName}** deactivated. Applied immediately your next message will use default behavior.`
35
- : '# OmOC Mode: OFF\n\nNo persona was active.',
37
+ ? `# OmOC Mode: OFF\n\nPersona **${wasName}** deactivated. AGENTS.md restored to default.`
38
+ : '# OmOC Mode: OFF\n\nNo persona was active. AGENTS.md restored to default.',
36
39
  };
37
40
  }
38
41
  if (args === 'list') {
@@ -66,13 +69,15 @@ export function registerPersonaCommands(api) {
66
69
  }
67
70
  const previousId = await getActivePersona();
68
71
  await setActivePersonaId(resolvedId);
72
+ const content = await readPersonaPrompt(resolvedId);
73
+ await replaceAgentsMd(content);
69
74
  const displayName = getDisplayName(resolvedId);
70
75
  const switched = listPersonas().find((p) => p.id === resolvedId);
71
76
  const switchNote = previousId && previousId !== resolvedId
72
77
  ? `\n\nSwitched from **${getDisplayName(previousId)}**.`
73
78
  : '';
74
79
  return {
75
- text: `# Persona Switched\n\nActive persona: **${displayName}**${switchNote}\n\nApplied immediately your next message will use the ${switched?.theme ?? 'persona'} prompt.`,
80
+ text: `# Persona Switched\n\nActive persona: **${displayName}**${switchNote}\n\nAGENTS.md replaced. Your next message will use the ${switched?.theme ?? 'persona'} prompt.`,
76
81
  };
77
82
  },
78
83
  });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Analyze mode — multilingual keyword regex.
3
+ * Necessary: documents 5-language regex for maintainability.
4
+ *
5
+ * EN: analyze, analyse, investigate, examine, research, study, deep-dive, inspect, audit, evaluate, assess, review, diagnose, scrutinize, dissect, debug, comprehend, interpret, breakdown, understand
6
+ * KO: 분석, 조사, 파악, 연구, 검토, 진단, 이해, 설명, 원인, 이유, 뜯어봐, 따져봐, 평가, 해석, 디버깅, 디버그, 어떻게, 왜, 살펴
7
+ * JA: 分析, 調査, 解析, 検討, 研究, 診断, 理解, 説明, 検証, 精査, 究明, デバッグ, なぜ, どう, 仕組み
8
+ * ZH: 调查, 检查, 剖析, 深入, 诊断, 解释, 调试, 为什么, 原理, 搞清楚, 弄明白
9
+ * VI: phân tích, điều tra, nghiên cứu, kiểm tra, xem xét, chẩn đoán, giải thích, tìm hiểu, gỡ lỗi, tại sao
10
+ */
11
+ export declare const ANALYZE_PATTERN: RegExp;
12
+ export declare const ANALYZE_MESSAGE = "[analyze-mode]\nANALYSIS MODE. Gather context from ALL channels before diving deep:\n\nCONTEXT GATHERING (parallel):\n- omoc_delegate(agent_id=\"omoc_explore\") \u2014 codebase patterns, implementations\n- omoc_delegate(agent_id=\"omoc_librarian\") \u2014 external docs, API references\n- web-search-prime / context7 \u2014 official docs, known issues, changelogs\n- grep_app.search \u2014 how others solved similar problems in OSS\n- gemini CLI with @google \u2014 Google Search grounding for real-time info\n\nVISUAL/MULTIMODAL ANALYSIS (if needed):\n- gemini CLI (via tmux) with -f flag \u2014 analyze PDFs, screenshots, architecture diagrams\n- omoc_look_at \u2014 quick multimodal analysis of images/screenshots\n\nIF COMPLEX \u2014 delegate to specialists:\n- omoc_delegate(agent_id=\"omoc_oracle\") \u2014 architecture, debugging, complex logic\n- omoc_delegate(category=\"artistry\") \u2014 unconventional approaches\n\nSYNTHESIZE findings before proceeding.";
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Analyze mode — multilingual keyword regex.
3
+ * Necessary: documents 5-language regex for maintainability.
4
+ *
5
+ * EN: analyze, analyse, investigate, examine, research, study, deep-dive, inspect, audit, evaluate, assess, review, diagnose, scrutinize, dissect, debug, comprehend, interpret, breakdown, understand
6
+ * KO: 분석, 조사, 파악, 연구, 검토, 진단, 이해, 설명, 원인, 이유, 뜯어봐, 따져봐, 평가, 해석, 디버깅, 디버그, 어떻게, 왜, 살펴
7
+ * JA: 分析, 調査, 解析, 検討, 研究, 診断, 理解, 説明, 検証, 精査, 究明, デバッグ, なぜ, どう, 仕組み
8
+ * ZH: 调查, 检查, 剖析, 深入, 诊断, 解释, 调试, 为什么, 原理, 搞清楚, 弄明白
9
+ * VI: phân tích, điều tra, nghiên cứu, kiểm tra, xem xét, chẩn đoán, giải thích, tìm hiểu, gỡ lỗi, tại sao
10
+ */
11
+ export const ANALYZE_PATTERN = /\b(analyze|analyse|investigate|examine|research|study|deep[\s-]?dive|inspect|audit|evaluate|assess|review|diagnose|scrutinize|dissect|debug|comprehend|interpret|breakdown|understand)\b|why\s+is|how\s+does|how\s+to|분석|조사|파악|연구|검토|진단|이해|설명|원인|이유|뜯어봐|따져봐|평가|해석|디버깅|디버그|어떻게|왜|살펴|分析|調査|解析|検討|研究|診断|理解|説明|検証|精査|究明|デバッグ|なぜ|どう|仕組み|调查|检查|剖析|深入|诊断|解释|调试|为什么|原理|搞清楚|弄明白|phân tích|điều tra|nghiên cứu|kiểm tra|xem xét|chẩn đoán|giải thích|tìm hiểu|gỡ lỗi|tại sao/i;
12
+ export const ANALYZE_MESSAGE = `[analyze-mode]
13
+ ANALYSIS MODE. Gather context from ALL channels before diving deep:
14
+
15
+ CONTEXT GATHERING (parallel):
16
+ - omoc_delegate(agent_id="omoc_explore") — codebase patterns, implementations
17
+ - omoc_delegate(agent_id="omoc_librarian") — external docs, API references
18
+ - web-search-prime / context7 — official docs, known issues, changelogs
19
+ - grep_app.search — how others solved similar problems in OSS
20
+ - gemini CLI with @google — Google Search grounding for real-time info
21
+
22
+ VISUAL/MULTIMODAL ANALYSIS (if needed):
23
+ - gemini CLI (via tmux) with -f flag — analyze PDFs, screenshots, architecture diagrams
24
+ - omoc_look_at — quick multimodal analysis of images/screenshots
25
+
26
+ IF COMPLEX — delegate to specialists:
27
+ - omoc_delegate(agent_id="omoc_oracle") — architecture, debugging, complex logic
28
+ - omoc_delegate(category="artistry") — unconventional approaches
29
+
30
+ SYNTHESIZE findings before proceeding.`;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Coding mode — multilingual keyword regex.
3
+ * Necessary: documents 5-language regex for maintainability.
4
+ *
5
+ * EN: implement, code, build, develop, refactor, fix, patch, write code, program, create, scaffold, migrate, port, convert
6
+ * KO: 구현, 코딩, 개발, 리팩토링, 수정, 패치, 코드 작성, 만들어, 짜줘, 고쳐, 빌드, 변환, 마이그레이션
7
+ * JA: 実装, コーディング, 開発, リファクタリング, 修正, パッチ, コード, 作って, ビルド, 変換
8
+ * ZH: 实现, 编码, 开发, 重构, 修复, 补丁, 写代码, 构建, 转换, 迁移
9
+ * VI: triển khai, lập trình, phát triển, tái cấu trúc, sửa lỗi, viết code, xây dựng, chuyển đổi
10
+ */
11
+ export declare const CODING_PATTERN: RegExp;
12
+ export declare const CODING_MESSAGE = "[coding-mode]\nCODING TASK DETECTED. Use the right execution channel:\n\nPRIMARY \u2014 tmux OpenCode/OmO session (opencode-controller skill):\n- Delegate implementation to OpenCode running in tmux for full OmO power\n- Use for: heavy coding, multi-file refactors, test writing, build/lint cycles\n\nALTERNATIVE \u2014 omoc_delegate for lighter tasks:\n- omoc_delegate(category=\"quick\", agent_id=\"omoc_sisyphus\") \u2014 simple fixes, single-file changes\n- omoc_delegate(category=\"deep\", agent_id=\"omoc_hephaestus\") \u2014 complex refactoring, architecture changes\n\nCONTEXT GATHERING (parallel, before coding):\n- omoc_delegate(agent_id=\"omoc_explore\") \u2014 understand existing patterns first\n- context7 / grep_app.search \u2014 check library APIs, find OSS examples\n\nVERIFICATION (after coding):\n- Run tests, linter, type-check, build via tmux opencode session\n- gemini CLI with -f flag \u2014 visual verification of UI changes if applicable";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Coding mode — multilingual keyword regex.
3
+ * Necessary: documents 5-language regex for maintainability.
4
+ *
5
+ * EN: implement, code, build, develop, refactor, fix, patch, write code, program, create, scaffold, migrate, port, convert
6
+ * KO: 구현, 코딩, 개발, 리팩토링, 수정, 패치, 코드 작성, 만들어, 짜줘, 고쳐, 빌드, 변환, 마이그레이션
7
+ * JA: 実装, コーディング, 開発, リファクタリング, 修正, パッチ, コード, 作って, ビルド, 変換
8
+ * ZH: 实现, 编码, 开发, 重构, 修复, 补丁, 写代码, 构建, 转换, 迁移
9
+ * VI: triển khai, lập trình, phát triển, tái cấu trúc, sửa lỗi, viết code, xây dựng, chuyển đổi
10
+ */
11
+ export const CODING_PATTERN = /\b(implement|code|build|develop|refactor|fix|patch|program|scaffold|migrate|port|convert)\b|write\s+code|구현|코딩|개발|리팩토링|수정|패치|코드\s*작성|만들어|짜줘|고쳐|빌드|변환|마이그레이션|実装|コーディング|開発|リファクタリング|修正|パッチ|コード|作って|ビルド|変換|实现|编码|开发|重构|修复|补丁|写代码|构建|转换|迁移|triển khai|lập trình|phát triển|tái cấu trúc|sửa lỗi|viết code|xây dựng|chuyển đổi/i;
12
+ export const CODING_MESSAGE = `[coding-mode]
13
+ CODING TASK DETECTED. Use the right execution channel:
14
+
15
+ PRIMARY — tmux OpenCode/OmO session (opencode-controller skill):
16
+ - Delegate implementation to OpenCode running in tmux for full OmO power
17
+ - Use for: heavy coding, multi-file refactors, test writing, build/lint cycles
18
+
19
+ ALTERNATIVE — omoc_delegate for lighter tasks:
20
+ - omoc_delegate(category="quick", agent_id="omoc_sisyphus") — simple fixes, single-file changes
21
+ - omoc_delegate(category="deep", agent_id="omoc_hephaestus") — complex refactoring, architecture changes
22
+
23
+ CONTEXT GATHERING (parallel, before coding):
24
+ - omoc_delegate(agent_id="omoc_explore") — understand existing patterns first
25
+ - context7 / grep_app.search — check library APIs, find OSS examples
26
+
27
+ VERIFICATION (after coding):
28
+ - Run tests, linter, type-check, build via tmux opencode session
29
+ - gemini CLI with -f flag — visual verification of UI changes if applicable`;
@@ -0,0 +1,6 @@
1
+ export type KeywordType = 'ultrawork' | 'search' | 'analyze' | 'coding';
2
+ export interface DetectedKeyword {
3
+ type: KeywordType;
4
+ message: string;
5
+ }
6
+ export declare function detectKeywords(text: string): DetectedKeyword[];
@@ -0,0 +1,21 @@
1
+ import { SEARCH_PATTERN, SEARCH_MESSAGE } from './search-mode.js';
2
+ import { ANALYZE_PATTERN, ANALYZE_MESSAGE } from './analyze-mode.js';
3
+ import { ULTRAWORK_PATTERN, ULTRAWORK_MESSAGE } from './ultrawork-mode.js';
4
+ import { CODING_PATTERN, CODING_MESSAGE } from './coding-mode.js';
5
+ const CODE_BLOCK_PATTERN = /```[\s\S]*?```/g;
6
+ const INLINE_CODE_PATTERN = /`[^`]+`/g;
7
+ const KEYWORD_DETECTORS = [
8
+ { type: 'ultrawork', pattern: ULTRAWORK_PATTERN, message: ULTRAWORK_MESSAGE },
9
+ { type: 'search', pattern: SEARCH_PATTERN, message: SEARCH_MESSAGE },
10
+ { type: 'analyze', pattern: ANALYZE_PATTERN, message: ANALYZE_MESSAGE },
11
+ { type: 'coding', pattern: CODING_PATTERN, message: CODING_MESSAGE },
12
+ ];
13
+ function removeCodeBlocks(text) {
14
+ return text.replace(CODE_BLOCK_PATTERN, '').replace(INLINE_CODE_PATTERN, '');
15
+ }
16
+ export function detectKeywords(text) {
17
+ const cleaned = removeCodeBlocks(text);
18
+ return KEYWORD_DETECTORS
19
+ .filter(({ pattern }) => pattern.test(cleaned))
20
+ .map(({ type, message }) => ({ type, message }));
21
+ }
@@ -0,0 +1,2 @@
1
+ import { OmocPluginApi } from '../../types.js';
2
+ export declare function registerKeywordDetector(api: OmocPluginApi): void;
@@ -0,0 +1,15 @@
1
+ import { LOG_PREFIX } from '../../constants.js';
2
+ import { detectKeywords } from './detector.js';
3
+ export function registerKeywordDetector(api) {
4
+ api.on('before_prompt_build', (event, _ctx) => {
5
+ const prompt = event.prompt;
6
+ if (!prompt || typeof prompt !== 'string')
7
+ return;
8
+ const detected = detectKeywords(prompt);
9
+ if (detected.length === 0)
10
+ return;
11
+ const merged = detected.map((k) => k.message).join('\n\n');
12
+ api.logger.info(`${LOG_PREFIX} Keyword detector: ${detected.map((k) => k.type).join(', ')} detected`);
13
+ return { prependContext: merged };
14
+ }, { priority: 75 });
15
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Search mode — multilingual keyword regex.
3
+ * Necessary: documents 5-language regex for maintainability.
4
+ *
5
+ * EN: search, find, locate, lookup, explore, discover, scan, grep, query, browse, detect, trace, seek, track, pinpoint, hunt
6
+ * KO: 검색, 찾아, 탐색, 조회, 스캔, 서치, 뒤져, 찾기, 어디, 추적, 탐지, 찾아봐, 찾아내, 보여줘, 목록
7
+ * JA: 検索, 探して, 見つけて, サーチ, 探索, スキャン, どこ, 発見, 捜索, 見つけ出す, 一覧
8
+ * ZH: 搜索, 查找, 寻找, 查询, 检索, 定位, 扫描, 发现, 在哪里, 找出来, 列出
9
+ * VI: tìm kiếm, tra cứu, định vị, quét, phát hiện, truy tìm, tìm ra, ở đâu, liệt kê
10
+ */
11
+ export declare const SEARCH_PATTERN: RegExp;
12
+ export declare const SEARCH_MESSAGE = "[search-mode]\nMAXIMIZE SEARCH EFFORT. Use ALL available channels IN PARALLEL:\n\nAGENT DELEGATION (omoc_delegate):\n- agent_id=\"omoc_explore\" \u2014 codebase patterns, file structures, cross-module references\n- agent_id=\"omoc_librarian\" \u2014 external docs, OSS examples, API references\n\nWEB SEARCH (mcporter MCP + OpenClaw native):\n- web-search-prime.webSearchPrime \u2014 keyword web search (news, blogs, latest info)\n- exa.web_search_exa \u2014 semantic web search (better for question-format queries)\n- context7 \u2014 library/framework official documentation\n- grep_app.search \u2014 open-source code pattern search on GitHub\n- zread \u2014 direct GitHub repo file exploration\n- web_fetch \u2014 direct URL reading\n\nGEMINI CLI (via tmux gemini session):\n- gemini with @google extension \u2014 Google Search grounding for real-time info\n- gemini with -f flag \u2014 analyze PDFs/images/screenshots if visual context needed\n\nLaunch multiple delegates + web searches simultaneously.\nNEVER stop at first result \u2014 be exhaustive.";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Search mode — multilingual keyword regex.
3
+ * Necessary: documents 5-language regex for maintainability.
4
+ *
5
+ * EN: search, find, locate, lookup, explore, discover, scan, grep, query, browse, detect, trace, seek, track, pinpoint, hunt
6
+ * KO: 검색, 찾아, 탐색, 조회, 스캔, 서치, 뒤져, 찾기, 어디, 추적, 탐지, 찾아봐, 찾아내, 보여줘, 목록
7
+ * JA: 検索, 探して, 見つけて, サーチ, 探索, スキャン, どこ, 発見, 捜索, 見つけ出す, 一覧
8
+ * ZH: 搜索, 查找, 寻找, 查询, 检索, 定位, 扫描, 发现, 在哪里, 找出来, 列出
9
+ * VI: tìm kiếm, tra cứu, định vị, quét, phát hiện, truy tìm, tìm ra, ở đâu, liệt kê
10
+ */
11
+ export const SEARCH_PATTERN = /\b(search|find|locate|lookup|look\s*up|explore|discover|scan|grep|query|browse|detect|trace|seek|track|pinpoint|hunt)\b|where\s+is|show\s+me|list\s+all|검색|찾아|탐색|조회|스캔|서치|뒤져|찾기|어디|추적|탐지|찾아봐|찾아내|보여줘|목록|検索|探して|見つけて|サーチ|探索|スキャン|どこ|発見|捜索|見つけ出す|一覧|搜索|查找|寻找|查询|检索|定位|扫描|发现|在哪里|找出来|列出|tìm kiếm|tra cứu|định vị|quét|phát hiện|truy tìm|tìm ra|ở đâu|liệt kê/i;
12
+ export const SEARCH_MESSAGE = `[search-mode]
13
+ MAXIMIZE SEARCH EFFORT. Use ALL available channels IN PARALLEL:
14
+
15
+ AGENT DELEGATION (omoc_delegate):
16
+ - agent_id="omoc_explore" — codebase patterns, file structures, cross-module references
17
+ - agent_id="omoc_librarian" — external docs, OSS examples, API references
18
+
19
+ WEB SEARCH (mcporter MCP + OpenClaw native):
20
+ - web-search-prime.webSearchPrime — keyword web search (news, blogs, latest info)
21
+ - exa.web_search_exa — semantic web search (better for question-format queries)
22
+ - context7 — library/framework official documentation
23
+ - grep_app.search — open-source code pattern search on GitHub
24
+ - zread — direct GitHub repo file exploration
25
+ - web_fetch — direct URL reading
26
+
27
+ GEMINI CLI (via tmux gemini session):
28
+ - gemini with @google extension — Google Search grounding for real-time info
29
+ - gemini with -f flag — analyze PDFs/images/screenshots if visual context needed
30
+
31
+ Launch multiple delegates + web searches simultaneously.
32
+ NEVER stop at first result — be exhaustive.`;
@@ -0,0 +1,2 @@
1
+ export declare const ULTRAWORK_PATTERN: RegExp;
2
+ export declare const ULTRAWORK_MESSAGE = "[ultrawork-mode]\nULTRAWORK MODE ACTIVATED. Maximum precision engaged. ALL channels available.\n\nMANDATORY WORKFLOW:\n1. PLANNING: omoc_delegate(agent_id=\"omoc_prometheus\") \u2014 strategic breakdown\n2. REVIEW: omoc_delegate(agent_id=\"omoc_momus\") \u2014 plan critique before execution\n3. EXECUTION: tmux opencode session for coding, omoc_delegate for non-coding tasks\n4. VERIFICATION: Run diagnostics, tests, build after completion\n\nAGENT DELEGATION (omoc_delegate):\n- Prometheus \u2014 strategic planning\n- Oracle \u2014 architecture decisions, root cause analysis\n- Explore/Librarian \u2014 context gathering (parallel, background=true)\n- Momus \u2014 plan review and gap detection\n- Sisyphus/Hephaestus \u2014 task execution\n\nRESEARCH & ANALYSIS:\n- mcporter MCP (web-search-prime, exa, context7, grep_app, zread) \u2014 web research\n- gemini CLI with @google \u2014 Google Search grounding for real-time info\n- gemini CLI with -f flag \u2014 multimodal analysis (PDFs, images, diagrams)\n- omoc_look_at \u2014 quick visual analysis\n\nDO NOT CUT CORNERS. Every step verified. Every todo completed.";
@@ -0,0 +1,24 @@
1
+ export const ULTRAWORK_PATTERN = /\b(ultrawork|ulw)\b/i;
2
+ export const ULTRAWORK_MESSAGE = `[ultrawork-mode]
3
+ ULTRAWORK MODE ACTIVATED. Maximum precision engaged. ALL channels available.
4
+
5
+ MANDATORY WORKFLOW:
6
+ 1. PLANNING: omoc_delegate(agent_id="omoc_prometheus") — strategic breakdown
7
+ 2. REVIEW: omoc_delegate(agent_id="omoc_momus") — plan critique before execution
8
+ 3. EXECUTION: tmux opencode session for coding, omoc_delegate for non-coding tasks
9
+ 4. VERIFICATION: Run diagnostics, tests, build after completion
10
+
11
+ AGENT DELEGATION (omoc_delegate):
12
+ - Prometheus — strategic planning
13
+ - Oracle — architecture decisions, root cause analysis
14
+ - Explore/Librarian — context gathering (parallel, background=true)
15
+ - Momus — plan review and gap detection
16
+ - Sisyphus/Hephaestus — task execution
17
+
18
+ RESEARCH & ANALYSIS:
19
+ - mcporter MCP (web-search-prime, exa, context7, grep_app, zread) — web research
20
+ - gemini CLI with @google — Google Search grounding for real-time info
21
+ - gemini CLI with -f flag — multimodal analysis (PDFs, images, diagrams)
22
+ - omoc_look_at — quick visual analysis
23
+
24
+ DO NOT CUT CORNERS. Every step verified. Every todo completed.`;
@@ -0,0 +1,3 @@
1
+ import { OmocPluginApi } from '../types.js';
2
+ /** session_start hook: re-sync AGENTS.md from `.omoc-state` (source of truth). */
3
+ export declare function registerSessionSync(api: OmocPluginApi): void;
@@ -0,0 +1,33 @@
1
+ import { LOG_PREFIX } from '../constants.js';
2
+ import { getActivePersona, resolveAgentsMdPath, replaceAgentsMd } from '../utils/persona-state.js';
3
+ import { readPersonaPromptSync } from '../agents/persona-prompts.js';
4
+ import { readFileSync } from 'fs';
5
+ /** session_start hook: re-sync AGENTS.md from `.omoc-state` (source of truth). */
6
+ export function registerSessionSync(api) {
7
+ api.on('session_start', async (_event, _ctx) => {
8
+ try {
9
+ const activePersona = await getActivePersona();
10
+ if (!activePersona)
11
+ return;
12
+ const personaContent = readPersonaPromptSync(activePersona);
13
+ if (personaContent.startsWith('[OmOC]')) {
14
+ api.logger.warn(`${LOG_PREFIX} Session sync: persona file issue for ${activePersona}`);
15
+ return;
16
+ }
17
+ const agentsPath = resolveAgentsMdPath();
18
+ try {
19
+ const current = readFileSync(agentsPath, 'utf-8');
20
+ if (current.includes(personaContent.slice(0, 100)))
21
+ return;
22
+ }
23
+ catch {
24
+ // AGENTS.md missing or unreadable — needs sync
25
+ }
26
+ await replaceAgentsMd(personaContent);
27
+ api.logger.info(`${LOG_PREFIX} Session sync: AGENTS.md re-synced with .omoc-state (persona=${activePersona})`);
28
+ }
29
+ catch (err) {
30
+ api.logger.error(`${LOG_PREFIX} Session sync failed:`, err);
31
+ }
32
+ }, { priority: 200 });
33
+ }
@@ -0,0 +1,3 @@
1
+ import { OmocPluginApi } from '../types.js';
2
+ /** before_tool_call hook: block sessions_spawn without agentId when OmOC persona is active. */
3
+ export declare function registerSpawnGuard(api: OmocPluginApi): void;
@@ -0,0 +1,33 @@
1
+ import { LOG_PREFIX } from '../constants.js';
2
+ import { getActivePersona } from '../utils/persona-state.js';
3
+ import { ALL_AGENT_IDS } from '../agents/agent-ids.js';
4
+ const SPAWN_TOOL_NAME = 'sessions_spawn';
5
+ const AVAILABLE_AGENTS = ALL_AGENT_IDS.map((id) => id.replace('omoc_', '')).join(', ');
6
+ /** before_tool_call hook: block sessions_spawn without agentId when OmOC persona is active. */
7
+ export function registerSpawnGuard(api) {
8
+ api.on('before_tool_call', async (event, _ctx) => {
9
+ if (event.toolName !== SPAWN_TOOL_NAME) {
10
+ return;
11
+ }
12
+ let activePersona;
13
+ try {
14
+ activePersona = await getActivePersona();
15
+ }
16
+ catch {
17
+ return;
18
+ }
19
+ if (!activePersona)
20
+ return;
21
+ const agentId = event.params.agentId;
22
+ if (typeof agentId === 'string' && agentId.trim().length > 0)
23
+ return;
24
+ api.logger.info(`${LOG_PREFIX} Spawn guard: blocked sessions_spawn without agentId (active persona=${activePersona})`);
25
+ return {
26
+ block: true,
27
+ blockReason: `[OmOC] Sub-agent spawn BLOCKED: agentId is required when OmOC persona is active (current: ${activePersona}). ` +
28
+ `You MUST provide the agentId parameter in your sessions_spawn call. ` +
29
+ `Available agents: ${AVAILABLE_AGENTS}. ` +
30
+ `Retry with agentId set to the appropriate agent for this task.`,
31
+ };
32
+ }, { priority: 150 });
33
+ }
package/dist/index.js CHANGED
@@ -14,8 +14,10 @@ import { registerWorkflowCommands } from './commands/workflow-commands.js';
14
14
  import { registerRalphCommands } from './commands/ralph-commands.js';
15
15
  import { registerStatusCommands } from './commands/status-commands.js';
16
16
  import { registerPersonaCommands } from './commands/persona-commands.js';
17
- import { registerPersonaInjector } from './hooks/persona-injector.js';
18
17
  import { registerContextInjector } from './hooks/context-injector.js';
18
+ import { registerSessionSync } from './hooks/session-sync.js';
19
+ import { registerSpawnGuard } from './hooks/spawn-guard.js';
20
+ import { registerKeywordDetector } from './hooks/keyword-detector/hook.js';
19
21
  import { registerSetupCli } from './cli/setup.js';
20
22
  /**
21
23
  * Generation counter for multi-registration handling.
@@ -77,16 +79,26 @@ export default function register(api) {
77
79
  registry.hooks.push('gateway-startup');
78
80
  api.logger.info(`[${PLUGIN_ID}] Gateway startup hook registered`);
79
81
  });
80
- safeRegister(api, 'persona-injector', 'hook', () => {
81
- registerPersonaInjector(guarded);
82
- registry.hooks.push('persona-injector');
83
- api.logger.info(`[${PLUGIN_ID}] Persona injector hook registered`);
82
+ safeRegister(api, 'keyword-detector', 'hook', () => {
83
+ registerKeywordDetector(guarded);
84
+ registry.hooks.push('keyword-detector');
85
+ api.logger.info(`[${PLUGIN_ID}] Keyword detector hook registered (before_prompt_build, priority 75)`);
84
86
  });
85
87
  safeRegister(api, 'context-injector', 'hook', () => {
86
88
  registerContextInjector(guarded);
87
89
  registry.hooks.push('context-injector');
88
90
  api.logger.info(`[${PLUGIN_ID}] Context injector hook registered (before_prompt_build)`);
89
91
  });
92
+ safeRegister(api, 'session-sync', 'hook', () => {
93
+ registerSessionSync(api);
94
+ registry.hooks.push('session-sync');
95
+ api.logger.info(`[${PLUGIN_ID}] Session sync hook registered (session_start)`);
96
+ });
97
+ safeRegister(api, 'spawn-guard', 'hook', () => {
98
+ registerSpawnGuard(api);
99
+ registry.hooks.push('spawn-guard');
100
+ api.logger.info(`[${PLUGIN_ID}] Spawn guard hook registered (before_tool_call)`);
101
+ });
90
102
  safeRegister(api, 'ralph-loop', 'service', () => {
91
103
  registerRalphLoop(api);
92
104
  registry.services.push('ralph-loop');
package/dist/types.d.ts CHANGED
@@ -118,4 +118,5 @@ export interface BeforePromptBuildResult {
118
118
  export interface BeforePromptBuildEvent {
119
119
  prompt?: string;
120
120
  messages?: unknown[];
121
+ systemPrompt?: string;
121
122
  }
@@ -4,3 +4,7 @@ export declare function setActivePersonaId(id: string | null): Promise<void>;
4
4
  export declare function setActivePersona(id: string | null): Promise<void>;
5
5
  export declare function getActivePersona(): Promise<string | null>;
6
6
  export declare function resetPersonaState(): Promise<void>;
7
+ export declare const OFF_MARKER = "__OFF__";
8
+ export declare function resolveAgentsMdPath(): string;
9
+ export declare function replaceAgentsMd(personaContent: string): Promise<void>;
10
+ export declare function restoreAgentsMdToDefault(): Promise<void>;
@@ -1,8 +1,10 @@
1
1
  import { readFile, writeFile, mkdir } from 'fs/promises';
2
2
  import { dirname, join } from 'path';
3
+ import { homedir } from 'os';
3
4
  let activePersonaId = null;
4
5
  let loaded = false;
5
- let stateFilePath = join('workspace', '.omoc-state', 'active-persona');
6
+ const stateDir = join('workspace', '.omoc-state');
7
+ let stateFilePath = join(stateDir, 'active-persona');
6
8
  export async function initPersonaState(_api) {
7
9
  try {
8
10
  await mkdir(dirname(stateFilePath), { recursive: true });
@@ -28,12 +30,12 @@ export async function getActivePersona() {
28
30
  export async function resetPersonaState() {
29
31
  activePersonaId = null;
30
32
  loaded = true;
31
- await saveToDisk();
33
+ await saveOffState();
32
34
  }
33
35
  async function loadFromDisk() {
34
36
  try {
35
37
  const content = (await readFile(stateFilePath, 'utf-8')).trim();
36
- activePersonaId = content || null;
38
+ activePersonaId = (content && content !== OFF_MARKER) ? content : null;
37
39
  }
38
40
  catch (error) {
39
41
  // ENOENT is expected on first boot — no state file yet
@@ -44,13 +46,83 @@ async function loadFromDisk() {
44
46
  }
45
47
  loaded = true;
46
48
  }
49
+ export const OFF_MARKER = '__OFF__';
47
50
  async function saveToDisk() {
48
51
  try {
49
52
  await mkdir(dirname(stateFilePath), { recursive: true });
50
53
  await writeFile(stateFilePath, activePersonaId ?? '', 'utf-8');
51
54
  }
52
55
  catch (error) {
53
- // silent fail — in-memory state still works, but log for debugging
54
56
  console.warn('[omoc] Failed to persist persona state to disk:', error);
55
57
  }
56
58
  }
59
+ async function saveOffState() {
60
+ try {
61
+ await mkdir(dirname(stateFilePath), { recursive: true });
62
+ await writeFile(stateFilePath, OFF_MARKER, 'utf-8');
63
+ }
64
+ catch (error) {
65
+ console.warn('[omoc] Failed to persist persona off-state to disk:', error);
66
+ }
67
+ }
68
+ export function resolveAgentsMdPath() {
69
+ const profile = process.env.OPENCLAW_PROFILE?.trim();
70
+ const wsDir = (profile && profile.toLowerCase() !== 'default')
71
+ ? join(homedir(), '.openclaw', `workspace-${profile}`)
72
+ : join(homedir(), '.openclaw', 'workspace');
73
+ return join(wsDir, 'AGENTS.md');
74
+ }
75
+ export async function replaceAgentsMd(personaContent) {
76
+ const agentsPath = resolveAgentsMdPath();
77
+ await mkdir(dirname(agentsPath), { recursive: true });
78
+ const merged = `${DEFAULT_AGENTS_MD}\n---\n\n${personaContent}`;
79
+ await writeFile(agentsPath, merged, 'utf-8');
80
+ }
81
+ export async function restoreAgentsMdToDefault() {
82
+ const agentsPath = resolveAgentsMdPath();
83
+ await mkdir(dirname(agentsPath), { recursive: true });
84
+ await writeFile(agentsPath, DEFAULT_AGENTS_MD, 'utf-8');
85
+ }
86
+ const DEFAULT_AGENTS_MD = `# AGENTS.md - Your Workspace
87
+
88
+ This folder is home. Treat it that way.
89
+
90
+ ## First Run
91
+
92
+ If \`BOOTSTRAP.md\` exists, that's your birth certificate. Follow it, figure out who you are, then delete it. You won't need it again.
93
+
94
+ ## Every Session
95
+
96
+ Before doing anything else:
97
+
98
+ 1. Read \`SOUL.md\` — this is who you are
99
+ 2. Read \`USER.md\` — this is who you're helping
100
+ 3. Read \`memory/YYYY-MM-DD.md\` (today + yesterday) for recent context
101
+ 4. **If in MAIN SESSION** (direct chat with your human): Also read \`MEMORY.md\`
102
+
103
+ Don't ask permission. Just do it.
104
+
105
+ ## Memory
106
+
107
+ You wake up fresh each session. These files are your continuity:
108
+
109
+ - **Daily notes:** \`memory/YYYY-MM-DD.md\` (create \`memory/\` if needed) — raw logs of what happened
110
+ - **Long-term:** \`MEMORY.md\` — your curated memories, like a human's long-term memory
111
+
112
+ Capture what matters. Decisions, context, things to remember. Skip the secrets unless asked to keep them.
113
+
114
+ ## Safety
115
+
116
+ - Don't exfiltrate private data. Ever.
117
+ - Don't run destructive commands without asking.
118
+ - \`trash\` > \`rm\` (recoverable beats gone forever)
119
+ - When in doubt, ask.
120
+
121
+ ## Tools
122
+
123
+ Skills provide your tools. When you need one, check its \`SKILL.md\`. Keep local notes in \`TOOLS.md\`.
124
+
125
+ ## Make It Yours
126
+
127
+ This is a starting point. Add your own conventions, style, and rules as you figure out what works.
128
+ `;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happycastle/oh-my-openclaw",
3
- "version": "0.13.4",
3
+ "version": "0.14.1",
4
4
  "description": "Oh-My-OpenClaw plugin — multi-agent orchestration, todo enforcer, ralph loop, and custom tools for OpenClaw",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,10 +0,0 @@
1
- import { OmocPluginApi } from '../types.js';
2
- /**
3
- * Check whether persona content is already present in session history.
4
- *
5
- * OpenClaw's `prependContext` is merged into the user prompt and persisted
6
- * in session history. Without this check the persona text accumulates —
7
- * appearing once per historical user message sent to the model.
8
- */
9
- export declare function isPersonaAlreadyInHistory(messages: unknown[] | undefined, personaContent: string): boolean;
10
- export declare function registerPersonaInjector(api: OmocPluginApi): void;
@@ -1,87 +0,0 @@
1
- import { LOG_PREFIX } from '../constants.js';
2
- import { getActivePersona } from '../utils/persona-state.js';
3
- import { readPersonaPromptSync, resolvePersonaId } from '../agents/persona-prompts.js';
4
- /**
5
- * Resolve the effective persona ID.
6
- *
7
- * Priority:
8
- * 1. Manually set persona via /omoc command (getActivePersona())
9
- * 2. agentId from the hook context (set by OpenClaw core)
10
- * 3. null — no persona to inject
11
- */
12
- async function resolveEffectivePersona(ctx) {
13
- const manual = await getActivePersona();
14
- if (manual) {
15
- const resolved = resolvePersonaId(manual);
16
- if (resolved)
17
- return { personaId: resolved, source: 'manual' };
18
- }
19
- const agentId = ctx.agentId;
20
- if (!agentId)
21
- return null;
22
- const resolved = resolvePersonaId(agentId);
23
- if (!resolved)
24
- return null;
25
- return { personaId: resolved, source: 'auto' };
26
- }
27
- const FINGERPRINT_LENGTH = 200;
28
- /**
29
- * Check whether persona content is already present in session history.
30
- *
31
- * OpenClaw's `prependContext` is merged into the user prompt and persisted
32
- * in session history. Without this check the persona text accumulates —
33
- * appearing once per historical user message sent to the model.
34
- */
35
- export function isPersonaAlreadyInHistory(messages, personaContent) {
36
- if (!messages || messages.length === 0)
37
- return false;
38
- const fingerprint = personaContent.slice(0, FINGERPRINT_LENGTH).trim();
39
- if (!fingerprint)
40
- return false;
41
- for (const msg of messages) {
42
- if (!msg || typeof msg !== 'object')
43
- continue;
44
- const record = msg;
45
- if (record['role'] !== 'user')
46
- continue;
47
- const content = record['content'];
48
- if (typeof content === 'string' && content.includes(fingerprint)) {
49
- return true;
50
- }
51
- }
52
- return false;
53
- }
54
- export function registerPersonaInjector(api) {
55
- // Use the typed hook system (api.on) for before_prompt_build.
56
- // This directly injects into the system prompt via prependContext,
57
- // which is more reliable than bootstrapFiles via agent:bootstrap.
58
- //
59
- // api.registerHook('before_prompt_build', ...) registers into the internal
60
- // hook system which does NOT trigger before_prompt_build — only hookRunner
61
- // (typed hooks via api.on) does.
62
- api.on('before_prompt_build', async (event, ctx) => {
63
- const result = await resolveEffectivePersona(ctx);
64
- if (!result) {
65
- const manual = await getActivePersona();
66
- api.logger.info(`${LOG_PREFIX} Persona injector: no persona resolved (agentId=${ctx.agentId ?? 'none'}, manual=${manual ?? 'none'})`);
67
- return;
68
- }
69
- const { personaId, source } = result;
70
- try {
71
- const content = readPersonaPromptSync(personaId);
72
- if (isPersonaAlreadyInHistory(event.messages, content)) {
73
- api.logger.info(`${LOG_PREFIX} Persona already in history, skipping injection: ${personaId} (${source})`);
74
- return;
75
- }
76
- api.logger.info(`${LOG_PREFIX} Persona injected via before_prompt_build: ${personaId} (${source}, agentId=${ctx.agentId ?? 'none'})`);
77
- return {
78
- prependContext: content,
79
- };
80
- }
81
- catch (err) {
82
- api.logger.error(`${LOG_PREFIX} Failed to inject persona ${personaId}:`, err);
83
- return;
84
- }
85
- }, { priority: 100 } // High priority — persona prompt should be prepended first
86
- );
87
- }