@muwi/core 0.0.0-stage → 0.7.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.
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/bin/muwi +25 -0
- package/bin/muwi.js +11 -0
- package/connectors/hermes/__init__.py +393 -0
- package/connectors/hermes/plugin.yaml +14 -0
- package/connectors/kilo/muwi.js +409 -0
- package/connectors/omp/muwi.ts +324 -0
- package/connectors/opencode/muwi.js +529 -0
- package/connectors/pi/muwi.ts +235 -0
- package/hooks/hook.sh +50 -0
- package/hooks/instructions.md +17 -0
- package/hooks/tool.sh +45 -0
- package/package.json +23 -4
- package/skills/muwi/SKILL.md +182 -0
- package/skills/muwi/agents/openai.yaml +4 -0
- package/src/cli.js +740 -0
- package/src/connectors/claude.js +91 -0
- package/src/connectors/files.js +75 -0
- package/src/connectors/flat.js +62 -0
- package/src/connectors/hooked.js +256 -0
- package/src/connectors/index.js +28 -0
- package/src/connectors/settings-hooks.js +78 -0
- package/src/connectors/shaped.js +227 -0
- package/src/connectors/tools.js +108 -0
- package/src/connectors/types.js +62 -0
- package/src/events.js +227 -0
- package/src/find-node.sh +92 -0
- package/src/hook.js +23 -0
- package/src/host.js +111 -0
- package/src/kit.js +125 -0
- package/src/node.js +89 -0
- package/src/plan.js +152 -0
- package/src/session.js +170 -0
- package/src/setup.js +337 -0
- package/src/store.js +252 -0
- package/src/update.js +134 -0
- package/src/view.js +596 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SoonMin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,150 @@
|
|
|
1
|
-
#
|
|
1
|
+
# muwi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> 무위(無爲): 인위적인 개입 없이, 자연스러운 흐름을 따른다.
|
|
4
|
+
|
|
5
|
+
AI에게 일을 맡기면 AI가 그 일의 진행 계획을 스스로 짜고, 그 진행을 그래프로 볼 수 있습니다. 순서를 미리 정해 줄 필요가 없습니다. 결과가 이상하면 어느 단계에서 왜 그랬는지 기록에서 찾을 수 있습니다.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
muwi는 AI 도구와 [Herdr 앱](https://herdr.dev)에서 동작합니다. AI 도구(Claude Code, Codex, Gemini CLI, Cursor CLI, Copilot CLI, OpenCode 등)에 커넥터를 넣으면 AI가 자기 계획과 진행을 muwi에 적고, Herdr 앱이 그 기록을 그래프로 보여 줍니다. 어느 도구에서나 같은 방법으로 기록합니다. 리뷰는 Codex가, 구현은 Claude Code가 맡아도 작업 하나의 그래프 하나로 보입니다.
|
|
10
|
+
|
|
11
|
+
## muwi를 쓰면 좋은 점
|
|
12
|
+
|
|
13
|
+
- **AI가 지금 무엇을 하는지 보입니다.** 일을 맡기면 "요구사항 읽기 → 구현 → 리뷰" 같은 계획이 카드로 그려집니다. 진행에 따라 카드가 "작업 중", "끝"으로 바뀝니다.
|
|
14
|
+
- **내 결정이 필요한 순간을 놓치지 않습니다.** AI가 물어볼 게 생기면 그 카드가 "응답 대기"로 바뀌고, 그 작업이 목록 맨 위로 올라옵니다. 끝났는데 아직 보지 않은 작업은 "새 결과"로 따로 모입니다.
|
|
15
|
+
- **순서를 정해 주지 않아도 됩니다.** AI가 작업마다 그 일에 맞는 계획을 짭니다. 브랜치 규칙처럼 팀에서만 통하는 지식만 skill로 적어 두세요.
|
|
16
|
+
- **결과가 이상할 때 원인을 찾을 수 있습니다.** 노드마다 누가 했는지, 어떤 skill을 읽었는지, 몇 번 다시 했는지가 남습니다. "왜 그랬는지 봐줘"라고 하면 AI가 기록에서 원인을 찾습니다.
|
|
17
|
+
- **일이 여러 곳에서 진행돼도 한 그래프로 봅니다.** AI가 일부를 서브에이전트나 새 세션에 맡겨도 같은 그래프에 누가 하는지와 함께 표시됩니다.
|
|
18
|
+
|
|
19
|
+
### 순서를 정해 두지 않는 이유
|
|
20
|
+
|
|
21
|
+
모델이 좋아질수록 미리 정해 둔 순서는 도움이 아니라 한계가 됩니다. 그래서 muwi는 사람과 AI의 몫을 이렇게 나눕니다.
|
|
22
|
+
|
|
23
|
+
| 사람이 정하는 것 | AI가 정하는 것 |
|
|
24
|
+
| --- | --- |
|
|
25
|
+
| 팀에서만 통하는 지식 (skill로 적어 둠) | 어떤 노드로, 어떤 순서로 할지 |
|
|
26
|
+
| 넘으면 안 되는 선 (훅으로 지킴) | 어떤 skill을 읽을지 |
|
|
27
|
+
| | 직접 할지, 서브에이전트나 새 세션에 맡길지 |
|
|
28
|
+
|
|
29
|
+
muwi는 AI가 간 길을 기록하고 보여 줍니다. 순서를 강제하지 않고, 일하는 방식을 정해 주지도 않습니다.
|
|
30
|
+
|
|
31
|
+
### 순서를 강제하고 싶을 경우
|
|
32
|
+
|
|
33
|
+
AI에게 순서를 정해 줄 수 있습니다. 원하는 정도에 맞는 방법을 고르세요.
|
|
34
|
+
|
|
35
|
+
| 원하는 것 | 방법 |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| 이번 한 번만 이 순서로 | 시킬 때 순서를 같이 말하세요 |
|
|
38
|
+
| 이런 작업에는 이 단계가 꼭 들어가야 함 | skill에 "계획에 꼭 넣을 노드"를 적으세요 |
|
|
39
|
+
| 이런 작업은 항상 정확히 이 계획으로 | 계획을 JSON 파일로 만들어 두세요 |
|
|
40
|
+
|
|
41
|
+
muwi에는 AI가 순서에서 벗어나는 것을 막는 기능이 없습니다. 대신 AI가 순서를 바꾸면 누가 왜 바꿨는지 기록에 남습니다. 벗어났는지는 기록에서 확인하세요. 자세한 방법은 [정해 둔 순서로 진행시키기](docs/guides/fixed-workflow.md)에 있습니다.
|
|
42
|
+
|
|
43
|
+
## 설치하기
|
|
44
|
+
|
|
45
|
+
Node 24 이상과 npm이 필요하고, 그래프로 보려면 [Herdr 앱](https://herdr.dev)이 필요합니다. Windows에서는 Git for Windows도 필요합니다 ([Windows에서 쓰기](docs/reference/setup.md#windows에서-쓰기)).
|
|
46
|
+
|
|
47
|
+
muwi는 패키지 두 개로 나뉩니다. 둘 다 `muwi` 명령을 내므로 하나만 까세요.
|
|
48
|
+
|
|
49
|
+
| 패키지 | 들어 있는 것 |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `@muwi/herdr-app` | `@muwi/core`의 모든 것에 더해 Herdr 앱의 작업 목록과 그래프 칸, 새 세션에 맡기기(`muwi run`), 레이아웃 바꾸기 |
|
|
52
|
+
| `@muwi/core` | 기록, 명령(`muwi plan`, `muwi show`…), AI에게 주는 지침, AI 도구 커넥터. 그래프 없이 기록만 쓸 때 |
|
|
53
|
+
|
|
54
|
+
1. 설치하세요.
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
npm i -g @muwi/herdr-app
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
2. AI 도구에 커넥터를 넣으세요. 터미널용 `muwi` 명령과 Herdr 앱의 그래프 칸도 같이 들어갑니다.
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
muwi setup --all # 이 컴퓨터에 깔린 AI 도구 전부. 하나만이면 --tool claude
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
커넥터는 그 도구에 AI에게 주는 지침, 사용법 skill, 진행을 지켜보는 훅을 넣습니다. 넣을 수 있는 도구는 `muwi setup --tools`에 나옵니다. 이미 열려 있던 AI 세션은 새로 여세요.
|
|
67
|
+
|
|
68
|
+
3. Herdr 앱 화면에 muwi를 넣으세요. AI에게 "muwi 화면으로 바꿔줘"라고 해도 됩니다.
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
muwi layout
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
사이드바의 Agents 자리에 작업 목록이, 터미널 아래에 그래프가 생깁니다. 지금 레이아웃을 복제해서 바꾸므로 원래 화면은 그대로 남고, `muwi layout --remove`로 언제든 돌아갈 수 있습니다. 화면을 바꾸지 않고 보려면 `muwi open`으로 터미널 옆에 그래프 칸을 여세요.
|
|
75
|
+
|
|
76
|
+
처음이라면 [시작하기](docs/getting-started.md)를 따라 해 보세요. 설치되는 항목과 제거 방법, 도구마다 되는 것은 [설치와 설정](docs/reference/setup.md)에 있습니다.
|
|
77
|
+
|
|
78
|
+
## 사용하기
|
|
79
|
+
|
|
80
|
+
### 일 맡기기
|
|
81
|
+
|
|
82
|
+
평소처럼 말로 시키세요. 명령을 붙이지 않습니다.
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
PROJ-123 작업해줘
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
AI가 계획을 짜서 기록하고 일을 시작합니다. 계획을 짤지는 일의 크기로 정합니다. PR 리뷰나 조사처럼 파일을 고치지 않는 일도 여러 단계면 계획을 짜고, 질문에 답하거나 오타 하나를 고치는 것처럼 한 번에 끝나는 일에는 만들지 않습니다.
|
|
89
|
+
|
|
90
|
+
### 진행 보기
|
|
91
|
+
|
|
92
|
+
사이드바의 작업 목록에서 어떤 일이 내 응답을 기다리는지, 새로 끝난 일이 있는지 보고, 터미널 아래 그래프에서 그 일이 어디까지 왔는지 보세요.
|
|
93
|
+
|
|
94
|
+
작업 목록은 Herdr의 Agents 칸을 대신합니다. 작업을 급한 순서로 묶고(응답 대기 → 막힘 → 새 결과 → 작업 중 → …), 열려 있는 다른 대화도 같이 보여 줍니다. 작업을 누르면 그 작업의 그래프가 나오고, 그 작업을 한 대화가 아직 열려 있으면 끝난 작업이어도 그 대화로 갑니다. 다른 탭의 터미널로 옮겨 가면 그래프도 그 터미널의 작업으로 바뀝니다.
|
|
95
|
+
|
|
96
|
+
그래프에서는 카드의 색과 표시로 진행을 확인하세요.
|
|
97
|
+
|
|
98
|
+
| 카드 | 뜻 |
|
|
99
|
+
| --- | --- |
|
|
100
|
+
| 작업 중 | AI가 그 노드를 하고 있습니다 |
|
|
101
|
+
| 응답 대기 | AI가 내 답이나 결정을 기다립니다. 무엇을 묻는지 카드에 나옵니다 |
|
|
102
|
+
| 막힘 | AI가 스스로 풀지 못했습니다 |
|
|
103
|
+
| 끝 | 끝났습니다. 결과 한 줄이 나옵니다 |
|
|
104
|
+
| `2회차` 표시 | 끝냈던 노드를 다시 하고 있습니다 |
|
|
105
|
+
| `서브`, `세션` 표시 | 서브에이전트나 새 세션이 하고 있습니다 |
|
|
106
|
+
|
|
107
|
+
카드를 누르면 그 노드의 기록이 나옵니다. 표시의 뜻은 [그래프 화면](docs/reference/graph.md)에 모두 있습니다. Herdr 앱이 없으면 `muwi status`와 `muwi show <작업>`으로 같은 내용을 글로 볼 수 있습니다.
|
|
108
|
+
|
|
109
|
+
### 계획 바꾸기
|
|
110
|
+
|
|
111
|
+
바꾸고 싶은 것을 말하세요.
|
|
112
|
+
|
|
113
|
+
```
|
|
114
|
+
화면 확인 전에 lint부터 돌려
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
AI가 계획을 고치고, 그래프가 다시 그려집니다. 누가 왜 바꿨는지도 남습니다. 자세한 방법은 [진행 중에 계획 바꾸기](docs/guides/change-plan.md)에 있습니다.
|
|
118
|
+
|
|
119
|
+
### 원인 찾기
|
|
120
|
+
|
|
121
|
+
결과가 기대와 다르면 이유를 물어보세요.
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
브랜치 이름이 틀렸네. 왜 그랬는지 봐줘
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
AI가 기록에서 원인을 찾습니다. 예를 들어 브랜치를 만든 노드에 브랜치 규칙 skill을 읽은 기록이 없으면, 그 skill 없이 일한 것입니다. 그러면 그 skill이 제때 읽히도록 skill의 설명을 고칩니다. 자세한 방법은 [결과가 이상할 때 원인 찾기](docs/guides/find-cause.md)에 있습니다.
|
|
128
|
+
|
|
129
|
+
## 알아 둘 점
|
|
130
|
+
|
|
131
|
+
- Claude Code에서 씁니다. 그래프 보기와 새 세션 띄우기는 Herdr 앱 안에서만 됩니다.
|
|
132
|
+
- 새 세션이 처음 보는 폴더에서 뜨면 폴더 신뢰 확인에서 멈춥니다. 그 칸에서 직접 확인을 눌러 주세요.
|
|
133
|
+
- 순서를 정해 둔 skill이 설치돼 있으면 AI가 계획을 스스로 짜지 않고 그 순서를 따릅니다. 함께 쓸 skill에는 판단 기준만 적으세요.
|
|
134
|
+
- 하던 작업을 끝내지 않고 다른 일을 시키면, 그 일의 기록이 하던 노드에 붙을 수 있습니다. "그건 새 작업으로 적어"라고 말해 주세요.
|
|
135
|
+
|
|
136
|
+
전체 목록은 [제한 사항](docs/reference/limits.md)에 있습니다.
|
|
137
|
+
|
|
138
|
+
## 문서
|
|
139
|
+
|
|
140
|
+
| 목적 | 문서 |
|
|
141
|
+
| --- | --- |
|
|
142
|
+
| 처음 써 보기 | [시작하기](docs/getting-started.md) |
|
|
143
|
+
| 할 일 찾기 | [결과가 이상할 때 원인 찾기](docs/guides/find-cause.md) · [진행 중에 계획 바꾸기](docs/guides/change-plan.md) · [하던 작업 이어 가기](docs/guides/continue-work.md) · [서브에이전트와 새 세션 다루기](docs/guides/delegation.md) · [정해 둔 순서로 진행시키기](docs/guides/fixed-workflow.md) · [문제 해결하기](docs/guides/troubleshooting.md) |
|
|
144
|
+
| 정확한 내용 확인하기 | [그래프 화면](docs/reference/graph.md) · [명령어](docs/reference/commands.md) · [설치와 설정](docs/reference/setup.md) · [기록 파일](docs/reference/records.md) · [제한 사항](docs/reference/limits.md) |
|
|
145
|
+
| 원리 이해하기 | [동작 원리](docs/how-it-works.md) |
|
|
146
|
+
| 코드 고치기 | [개발과 기여](CONTRIBUTING.md) |
|
|
147
|
+
|
|
148
|
+
## 라이선스
|
|
149
|
+
|
|
150
|
+
[MIT](LICENSE). `@muwi/herdr-app`이 그래프 배치에 쓰는 [elkjs](https://github.com/kieler/elkjs)는 의존 패키지로 받고, 라이선스는 EPL-2.0입니다.
|
package/bin/muwi
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# muwi 명령. src/cli.ts를 Node로 바로 실행한다 (npm으로 받은 사본은 .js로 바꾼 src/cli.js). Node 24 이상이 필요하다.
|
|
3
|
+
# 셸 설정 없이 실행될 때(Herdr가 띄운 세션, 그래프 칸)도 Node를 찾도록 src/find-node.sh를 쓴다.
|
|
4
|
+
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
|
5
|
+
. "$ROOT/src/find-node.sh"
|
|
6
|
+
NODE=$(muwi_find_node)
|
|
7
|
+
CLI="$ROOT/src/cli.js"
|
|
8
|
+
[ -f "$CLI" ] || CLI="$ROOT/src/cli.ts"
|
|
9
|
+
"$NODE" "$CLI" "$@"
|
|
10
|
+
code=$?
|
|
11
|
+
# TypeScript를 바로 읽지 못하는 Node(22.18 미만)는 알기 어려운 오류를 낸다. 무엇이 필요한지 한 줄 덧붙인다.
|
|
12
|
+
# 그보다 높고 24보다 낮은 Node는 cli.ts가 직접 알린다.
|
|
13
|
+
if [ "$code" -ne 0 ]; then
|
|
14
|
+
v=$("$NODE" -v 2>/dev/null)
|
|
15
|
+
rest=${v#v}
|
|
16
|
+
major=${rest%%.*}
|
|
17
|
+
rest=${rest#*.}
|
|
18
|
+
minor=${rest%%.*}
|
|
19
|
+
case "$major" in '' | *[!0-9]*) major=0 ;; esac
|
|
20
|
+
case "$minor" in '' | *[!0-9]*) minor=0 ;; esac
|
|
21
|
+
if [ "$major" -lt 22 ] || { [ "$major" -eq 22 ] && [ "$minor" -lt 18 ]; }; then
|
|
22
|
+
echo "muwi: Node 24 이상이 필요해요 (지금: ${v:-없음})" >&2
|
|
23
|
+
fi
|
|
24
|
+
fi
|
|
25
|
+
exit "$code"
|
package/bin/muwi.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// npm이 PATH에 거는 muwi 명령. macOS·Linux는 이 파일로 가는 링크를, Windows는 npm이 만든 muwi.cmd·muwi.ps1이 node로 이 파일을 실행한다.
|
|
3
|
+
// Node는 링크를 풀어서 실행하므로 아래의 폴더는 패키지 안이다. npm으로 받은 사본은 .js로 바꾼 src/cli.js, 저장소에서는 src/cli.ts를 실행한다.
|
|
4
|
+
// sh 입구(bin/muwi)는 ~/.local/bin/muwi와 훅이 실제 경로로 부른다 (셸 설정이 없는 곳에서도 Node를 찾는다).
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
8
|
+
|
|
9
|
+
const src = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src');
|
|
10
|
+
const cli = ['cli.js', 'cli.ts'].map(name => path.join(src, name)).find(file => fs.existsSync(file));
|
|
11
|
+
await import(pathToFileURL(cli).href);
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
# muwi integration for Hermes Agent (managed by muwi; do not edit, run muwi setup again)
|
|
2
|
+
# MUWI_INTEGRATION_ID=hermes
|
|
3
|
+
"""Forward Hermes lifecycle events to muwi as Claude-Code-shaped hook JSON.
|
|
4
|
+
|
|
5
|
+
Install path: ~/.hermes/plugins/muwi/__init__.py, next to plugin.yaml. Hermes loads the
|
|
6
|
+
plugin only when `muwi` is listed under `plugins.enabled` in ~/.hermes/config.yaml
|
|
7
|
+
(`hermes plugins enable muwi`).
|
|
8
|
+
|
|
9
|
+
Nothing here may break Hermes: every callback swallows its own errors. This matters most
|
|
10
|
+
for `pre_tool_call`, where a callback that raises or runs past the hook timeout blocks
|
|
11
|
+
the tool.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import subprocess
|
|
20
|
+
import threading
|
|
21
|
+
|
|
22
|
+
_ID = "hermes"
|
|
23
|
+
_MUWI_HOOK = "__MUWI_HOOK__"
|
|
24
|
+
_TIMEOUT_SECONDS = 5
|
|
25
|
+
_SECTION_ID = "muwi.session-context"
|
|
26
|
+
_SECTION_MAX_CHARS = 4000
|
|
27
|
+
# Local, interactive surfaces. Messaging platforms, cron and kanban workers are ignored.
|
|
28
|
+
_INTERACTIVE_PLATFORMS = {"cli", "tui", "desktop", "acp"}
|
|
29
|
+
_FULL_COMPACTIONS = {"summarize", "provider_native"}
|
|
30
|
+
|
|
31
|
+
_lock = threading.RLock()
|
|
32
|
+
# session_id -> {"announced": bool, "cwd": str, "model": str, "pending": [str]}
|
|
33
|
+
_sessions = {}
|
|
34
|
+
# child session_id -> {"root": str, "agent_id": str, "agent_type": str}
|
|
35
|
+
_children = {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# ------------------------------------------------------------------ hook process
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _run_hook(mode, payload):
|
|
42
|
+
"""Run the muwi hook script as `<script> hermes [mode]` with the payload on stdin.
|
|
43
|
+
|
|
44
|
+
Returns the reply dict.
|
|
45
|
+
|
|
46
|
+
Returns {} when the command is missing, fails, prints no JSON, or takes over 5 seconds.
|
|
47
|
+
"""
|
|
48
|
+
try:
|
|
49
|
+
argv = [_MUWI_HOOK, _ID] + ([mode] if mode else [])
|
|
50
|
+
options = {
|
|
51
|
+
"input": json.dumps({k: v for k, v in payload.items() if v is not None}),
|
|
52
|
+
"stdout": subprocess.PIPE,
|
|
53
|
+
"stderr": subprocess.DEVNULL,
|
|
54
|
+
"universal_newlines": True,
|
|
55
|
+
"timeout": _TIMEOUT_SECONDS,
|
|
56
|
+
"check": False,
|
|
57
|
+
}
|
|
58
|
+
if os.name == "nt":
|
|
59
|
+
options["creationflags"] = subprocess.CREATE_NO_WINDOW
|
|
60
|
+
output = (subprocess.run(argv, **options).stdout or "").strip()
|
|
61
|
+
if not output:
|
|
62
|
+
return {}
|
|
63
|
+
reply = json.loads(output)
|
|
64
|
+
return reply if isinstance(reply, dict) else {}
|
|
65
|
+
except Exception:
|
|
66
|
+
return {}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _context_of(reply):
|
|
70
|
+
specific = reply.get("hookSpecificOutput") if isinstance(reply, dict) else None
|
|
71
|
+
text = specific.get("additionalContext") if isinstance(specific, dict) else None
|
|
72
|
+
return text if isinstance(text, str) and text.strip() else None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _decision_of(reply):
|
|
76
|
+
specific = reply.get("hookSpecificOutput") if isinstance(reply, dict) else None
|
|
77
|
+
if not isinstance(specific, dict):
|
|
78
|
+
return None, None
|
|
79
|
+
decision = specific.get("permissionDecision")
|
|
80
|
+
reason = specific.get("permissionDecisionReason")
|
|
81
|
+
return (
|
|
82
|
+
decision if isinstance(decision, str) else None,
|
|
83
|
+
reason if isinstance(reason, str) and reason else None,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ------------------------------------------------------------------ state
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _interactive(platform):
|
|
91
|
+
# Hooks that do not pass a platform are not filtered here.
|
|
92
|
+
return platform is None or platform in _INTERACTIVE_PLATFORMS
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _session(session_id):
|
|
96
|
+
with _lock:
|
|
97
|
+
return _sessions.setdefault(session_id, {"announced": False, "pending": []})
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _known(session_id):
|
|
101
|
+
with _lock:
|
|
102
|
+
return session_id in _sessions or session_id in _children
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _is_child(session_id):
|
|
106
|
+
with _lock:
|
|
107
|
+
return session_id in _children
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _payload(event, session_id, **extra):
|
|
111
|
+
"""Claude-shaped payload. Events inside a subagent go under the root session id."""
|
|
112
|
+
with _lock:
|
|
113
|
+
child = _children.get(session_id)
|
|
114
|
+
root_id = child["root"] if child else session_id
|
|
115
|
+
state = _sessions.get(root_id, {})
|
|
116
|
+
payload = {
|
|
117
|
+
"hook_event_name": event,
|
|
118
|
+
"session_id": root_id,
|
|
119
|
+
"cwd": state.get("cwd") or os.getcwd(),
|
|
120
|
+
"model": state.get("model"),
|
|
121
|
+
}
|
|
122
|
+
if child:
|
|
123
|
+
payload["agent_id"] = child["agent_id"]
|
|
124
|
+
payload["agent_type"] = child["agent_type"]
|
|
125
|
+
payload.update(extra)
|
|
126
|
+
return payload
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _announce(session_id, source):
|
|
130
|
+
"""Send SessionStart once per call and return its additionalContext (or None)."""
|
|
131
|
+
_session(session_id)["announced"] = True
|
|
132
|
+
return _context_of(_run_hook(None, _payload("SessionStart", session_id, source=source)))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _queue_context(session_id, text):
|
|
136
|
+
if text:
|
|
137
|
+
with _lock:
|
|
138
|
+
_session(session_id)["pending"].append(text)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _take_context(session_id):
|
|
142
|
+
with _lock:
|
|
143
|
+
state = _session(session_id)
|
|
144
|
+
pending, state["pending"] = state["pending"], []
|
|
145
|
+
return pending
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ------------------------------------------------------------------ normalizing
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _patch_path(text):
|
|
152
|
+
if not isinstance(text, str):
|
|
153
|
+
return None
|
|
154
|
+
match = re.search(r"^\*\*\* (?:Update|Add|Delete) File: (.+)$", text, re.MULTILINE)
|
|
155
|
+
return match.group(1).strip() if match else None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _first_string(*values):
|
|
159
|
+
for value in values:
|
|
160
|
+
if isinstance(value, str) and value:
|
|
161
|
+
return value
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _normalize_tool(tool_name, args):
|
|
166
|
+
"""Hermes tool names: terminal, write_file, patch, read_file, delegate_task, skill_view."""
|
|
167
|
+
a = args if isinstance(args, dict) else {}
|
|
168
|
+
path = _first_string(a.get("path"), a.get("file_path"))
|
|
169
|
+
if tool_name == "terminal":
|
|
170
|
+
return "Bash", {"command": _first_string(a.get("command")) or ""}, None
|
|
171
|
+
if tool_name == "write_file":
|
|
172
|
+
return "Write", {"file_path": path}, None
|
|
173
|
+
if tool_name == "patch":
|
|
174
|
+
return "Edit", {"file_path": path or _patch_path(_first_string(a.get("patch"), a.get("patch_text")))}, None
|
|
175
|
+
if tool_name == "read_file":
|
|
176
|
+
return "Read", {"file_path": path}, None
|
|
177
|
+
if tool_name == "skill_view":
|
|
178
|
+
return "Skill", {"skill": _first_string(a.get("name"), a.get("skill"))}, None
|
|
179
|
+
if tool_name == "delegate_task":
|
|
180
|
+
tasks = a.get("tasks") if isinstance(a.get("tasks"), list) else []
|
|
181
|
+
first = tasks[0] if tasks and isinstance(tasks[0], dict) else a
|
|
182
|
+
goal = _first_string(first.get("goal"), a.get("goal"))
|
|
183
|
+
agent_type = _first_string(first.get("role"), a.get("role")) or "subagent"
|
|
184
|
+
tool_input = {"subagent_type": agent_type, "description": goal, "prompt": goal}
|
|
185
|
+
if tasks:
|
|
186
|
+
tool_input["count"] = len(tasks)
|
|
187
|
+
return "Agent", tool_input, agent_type
|
|
188
|
+
return None, None, None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _prompt_text(message):
|
|
192
|
+
if isinstance(message, str):
|
|
193
|
+
return message
|
|
194
|
+
if isinstance(message, list):
|
|
195
|
+
parts = [p.get("text") for p in message if isinstance(p, dict) and isinstance(p.get("text"), str)]
|
|
196
|
+
return "\n".join(parts)
|
|
197
|
+
return ""
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ------------------------------------------------------------------ callbacks
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _system_prompt_section(info):
|
|
204
|
+
"""SessionStart for a new session, and the place its context goes.
|
|
205
|
+
|
|
206
|
+
Hermes calls this once while it builds the system prompt of a new session, with a
|
|
207
|
+
mapping that includes the session's cwd (hook keyword arguments do not). The returned
|
|
208
|
+
text becomes a system prompt section that Hermes keeps across compaction and resume.
|
|
209
|
+
An empty return makes Hermes skip the section (it logs a warning).
|
|
210
|
+
"""
|
|
211
|
+
try:
|
|
212
|
+
session_id = info.get("session_id")
|
|
213
|
+
if not session_id or not _interactive(info.get("platform")) or _is_child(session_id):
|
|
214
|
+
return ""
|
|
215
|
+
state = _session(session_id)
|
|
216
|
+
with _lock:
|
|
217
|
+
state["cwd"] = info.get("cwd") or state.get("cwd")
|
|
218
|
+
state["model"] = info.get("model") or state.get("model")
|
|
219
|
+
already = state["announced"]
|
|
220
|
+
if already:
|
|
221
|
+
return ""
|
|
222
|
+
return (_announce(session_id, "startup") or "")[:_SECTION_MAX_CHARS]
|
|
223
|
+
except Exception:
|
|
224
|
+
return ""
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _on_session_start(session_id=None, model=None, platform=None, **kwargs):
|
|
228
|
+
# New session, first turn. Normally the section callback above has already announced
|
|
229
|
+
# it; this covers Hermes versions without system prompt sections.
|
|
230
|
+
try:
|
|
231
|
+
if not session_id or not _interactive(platform) or _is_child(session_id):
|
|
232
|
+
return
|
|
233
|
+
state = _session(session_id)
|
|
234
|
+
if model:
|
|
235
|
+
state["model"] = model
|
|
236
|
+
if not state["announced"]:
|
|
237
|
+
_queue_context(session_id, _announce(session_id, "startup"))
|
|
238
|
+
except Exception:
|
|
239
|
+
pass
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _on_session_open(session_id=None, platform=None, reason=None, **kwargs):
|
|
243
|
+
# A client reopened a stored session (`hermes --resume`, the session picker).
|
|
244
|
+
try:
|
|
245
|
+
if not session_id or reason != "resume" or not _interactive(platform) or _is_child(session_id):
|
|
246
|
+
return
|
|
247
|
+
_queue_context(session_id, _announce(session_id, "resume"))
|
|
248
|
+
except Exception:
|
|
249
|
+
pass
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _post_compaction(session_id=None, old_session_id=None, kind=None, **kwargs):
|
|
253
|
+
try:
|
|
254
|
+
if not session_id or kind not in _FULL_COMPACTIONS:
|
|
255
|
+
return
|
|
256
|
+
with _lock:
|
|
257
|
+
if old_session_id and old_session_id != session_id and old_session_id in _sessions:
|
|
258
|
+
# The compaction rotated the session id: carry cwd/model over.
|
|
259
|
+
previous = _sessions[old_session_id]
|
|
260
|
+
current = _sessions.setdefault(session_id, {"announced": False, "pending": []})
|
|
261
|
+
current.setdefault("cwd", previous.get("cwd"))
|
|
262
|
+
current.setdefault("model", previous.get("model"))
|
|
263
|
+
for child in _children.values():
|
|
264
|
+
if child["root"] == old_session_id:
|
|
265
|
+
child["root"] = session_id
|
|
266
|
+
known = session_id in _sessions
|
|
267
|
+
if known:
|
|
268
|
+
_queue_context(session_id, _announce(session_id, "compact"))
|
|
269
|
+
except Exception:
|
|
270
|
+
pass
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _pre_llm_call(session_id=None, user_message=None, is_first_turn=False, model=None,
|
|
274
|
+
platform=None, parent_session_id=None, **kwargs):
|
|
275
|
+
"""UserPromptSubmit. The returned context is appended to this turn's user message."""
|
|
276
|
+
try:
|
|
277
|
+
if not session_id or not _interactive(platform):
|
|
278
|
+
return None
|
|
279
|
+
if _is_child(session_id) or parent_session_id:
|
|
280
|
+
return None # a subagent's turn: its prompt comes from the parent, not the user
|
|
281
|
+
state = _session(session_id)
|
|
282
|
+
if model:
|
|
283
|
+
state["model"] = model
|
|
284
|
+
if not state["announced"]:
|
|
285
|
+
# Session not seen by this process yet (older Hermes, or a restarted gateway).
|
|
286
|
+
_queue_context(session_id, _announce(session_id, "startup" if is_first_turn else "resume"))
|
|
287
|
+
reply = _run_hook(None, _payload("UserPromptSubmit", session_id, prompt=_prompt_text(user_message)))
|
|
288
|
+
parts = _take_context(session_id)
|
|
289
|
+
text = _context_of(reply)
|
|
290
|
+
if text:
|
|
291
|
+
parts.append(text)
|
|
292
|
+
return {"context": "\n\n".join(parts)} if parts else None
|
|
293
|
+
except Exception:
|
|
294
|
+
return None
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _pre_tool_call(tool_name=None, args=None, session_id=None, tool_call_id=None, **kwargs):
|
|
298
|
+
"""PreToolUse. Deny -> block with the reason."""
|
|
299
|
+
try:
|
|
300
|
+
if not session_id or not _known(session_id):
|
|
301
|
+
return None
|
|
302
|
+
name, tool_input, _agent_type = _normalize_tool(tool_name, args)
|
|
303
|
+
if name == "Bash":
|
|
304
|
+
mode = "command" # links a node a subagent starts; never blocks
|
|
305
|
+
else:
|
|
306
|
+
return None
|
|
307
|
+
reply = _run_hook(mode, _payload("PreToolUse", session_id, tool_name=name,
|
|
308
|
+
tool_input=tool_input, tool_use_id=tool_call_id))
|
|
309
|
+
decision, reason = _decision_of(reply)
|
|
310
|
+
if decision == "deny":
|
|
311
|
+
return {"action": "block", "message": reason or "Blocked by muwi"}
|
|
312
|
+
# Context for the model cannot be returned from pre_tool_call; keep it for the next turn.
|
|
313
|
+
with _lock:
|
|
314
|
+
child = _children.get(session_id)
|
|
315
|
+
_queue_context(child["root"] if child else session_id, _context_of(reply))
|
|
316
|
+
return None
|
|
317
|
+
except Exception:
|
|
318
|
+
return None
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _post_tool_call(tool_name=None, args=None, session_id=None, tool_call_id=None, **kwargs):
|
|
322
|
+
"""PostToolUse, for Read and Skill only."""
|
|
323
|
+
try:
|
|
324
|
+
if not session_id or not _known(session_id):
|
|
325
|
+
return
|
|
326
|
+
name, tool_input, _agent_type = _normalize_tool(tool_name, args)
|
|
327
|
+
if name in ("Read", "Skill"):
|
|
328
|
+
_run_hook(None, _payload("PostToolUse", session_id, tool_name=name,
|
|
329
|
+
tool_input=tool_input, tool_use_id=tool_call_id))
|
|
330
|
+
except Exception:
|
|
331
|
+
pass
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _subagent_start(parent_session_id=None, child_session_id=None, child_subagent_id=None,
|
|
335
|
+
child_role=None, **kwargs):
|
|
336
|
+
try:
|
|
337
|
+
if not parent_session_id or not _known(parent_session_id):
|
|
338
|
+
return
|
|
339
|
+
key = child_session_id or child_subagent_id
|
|
340
|
+
if not key:
|
|
341
|
+
return
|
|
342
|
+
with _lock:
|
|
343
|
+
parent = _children.get(parent_session_id)
|
|
344
|
+
_children[key] = {
|
|
345
|
+
"root": parent["root"] if parent else parent_session_id,
|
|
346
|
+
"agent_id": str(child_subagent_id or child_session_id),
|
|
347
|
+
"agent_type": child_role or "subagent",
|
|
348
|
+
}
|
|
349
|
+
_run_hook(None, _payload("SubagentStart", key))
|
|
350
|
+
except Exception:
|
|
351
|
+
pass
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _subagent_stop(parent_session_id=None, child_session_id=None, child_role=None,
|
|
355
|
+
child_status=None, **kwargs):
|
|
356
|
+
try:
|
|
357
|
+
with _lock:
|
|
358
|
+
known_child = child_session_id in _children if child_session_id else False
|
|
359
|
+
if known_child:
|
|
360
|
+
_run_hook(None, _payload("SubagentStop", child_session_id, status=child_status))
|
|
361
|
+
with _lock:
|
|
362
|
+
_children.pop(child_session_id, None)
|
|
363
|
+
elif parent_session_id and _known(parent_session_id):
|
|
364
|
+
# The start was not seen (or carried no child session id).
|
|
365
|
+
_run_hook(None, _payload("SubagentStop", parent_session_id,
|
|
366
|
+
agent_type=child_role or "subagent", status=child_status))
|
|
367
|
+
except Exception:
|
|
368
|
+
pass
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def register(ctx):
|
|
372
|
+
hooks = (
|
|
373
|
+
("on_session_start", _on_session_start),
|
|
374
|
+
("on_session_open", _on_session_open),
|
|
375
|
+
("post_compaction", _post_compaction),
|
|
376
|
+
("pre_llm_call", _pre_llm_call),
|
|
377
|
+
("pre_tool_call", _pre_tool_call),
|
|
378
|
+
("post_tool_call", _post_tool_call),
|
|
379
|
+
("subagent_start", _subagent_start),
|
|
380
|
+
("subagent_stop", _subagent_stop),
|
|
381
|
+
)
|
|
382
|
+
for name, callback in hooks:
|
|
383
|
+
try:
|
|
384
|
+
ctx.register_hook(name, callback)
|
|
385
|
+
except Exception:
|
|
386
|
+
pass # a Hermes version without this hook
|
|
387
|
+
try:
|
|
388
|
+
register_section = getattr(ctx, "register_system_prompt_section", None)
|
|
389
|
+
if callable(register_section):
|
|
390
|
+
register_section(_SECTION_ID, _system_prompt_section,
|
|
391
|
+
position="after_memory", max_chars=_SECTION_MAX_CHARS)
|
|
392
|
+
except Exception:
|
|
393
|
+
pass
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# muwi integration for Hermes Agent (managed by muwi; do not edit, run muwi setup again)
|
|
2
|
+
# MUWI_INTEGRATION_ID=hermes
|
|
3
|
+
name: muwi
|
|
4
|
+
version: "1.0"
|
|
5
|
+
description: Record Hermes sessions, prompts and tool calls in muwi
|
|
6
|
+
provides_hooks:
|
|
7
|
+
- on_session_start
|
|
8
|
+
- on_session_open
|
|
9
|
+
- post_compaction
|
|
10
|
+
- pre_llm_call
|
|
11
|
+
- pre_tool_call
|
|
12
|
+
- post_tool_call
|
|
13
|
+
- subagent_start
|
|
14
|
+
- subagent_stop
|