murmur-it 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/LICENSE +21 -0
- package/README.md +125 -2
- package/adapters/hummin/murmur.ts +467 -0
- package/adapters/opencode/murmur.ts +304 -0
- package/bin/murmur.js +11 -0
- package/dist/broker.js +1050 -0
- package/dist/cli.js +588 -0
- package/dist/client.js +210 -0
- package/dist/config.js +83 -0
- package/dist/core.js +779 -0
- package/dist/hooks.js +120 -0
- package/dist/install.js +250 -0
- package/dist/mcp.js +217 -0
- package/dist/native.js +125 -0
- package/dist/proc.js +110 -0
- package/dist/proof.js +111 -0
- package/dist/protocol.js +92 -0
- package/dist/store.js +496 -0
- package/dist/wake.js +12 -0
- package/package.json +63 -4
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { connectBroker } from './client.js';
|
|
2
|
+
import { getPaths, readToken } from './config.js';
|
|
3
|
+
import { currentHost } from './proc.js';
|
|
4
|
+
export const HOOK_CLIENTS = ['claude', 'codex', 'gemini', 'zcode'];
|
|
5
|
+
// Hard cap on the broker interaction. A hook runs inline inside a session
|
|
6
|
+
// and must never block it. MurmurClient.connect is already bounded (3s), but
|
|
7
|
+
// a broker that accepts and then stops replying could stall a request
|
|
8
|
+
// forever, so this watchdog destroys the socket, which rejects every
|
|
9
|
+
// pending request and lets the hook return.
|
|
10
|
+
const HOOK_DEADLINE_MS = 10000;
|
|
11
|
+
const FETCH_PUSH_LIMIT = 10;
|
|
12
|
+
// Entry point used by every client's hook config. It must never block or
|
|
13
|
+
// fail a session: any broker error, broker down, unreadable stdin, unknown
|
|
14
|
+
// host or unexpected failure resolves with exit 0 and empty stdout.
|
|
15
|
+
export async function runHook(event, stdinText, env, opts) {
|
|
16
|
+
try {
|
|
17
|
+
const client = opts?.client ?? 'claude';
|
|
18
|
+
const host = opts?.host === undefined ? currentHost(undefined, false) : opts.host;
|
|
19
|
+
if (host === null) {
|
|
20
|
+
return { exitCode: 0, stdout: '' };
|
|
21
|
+
}
|
|
22
|
+
const input = parseInput(stdinText);
|
|
23
|
+
const home = env.MURMUR_HOME;
|
|
24
|
+
const paths = typeof home === 'string' ? getPaths(home) : getPaths();
|
|
25
|
+
const token = readToken(paths);
|
|
26
|
+
const conn = await connectBroker({ socketPath: paths.socketPath, token });
|
|
27
|
+
const watchdog = setTimeout(() => {
|
|
28
|
+
conn.close();
|
|
29
|
+
}, HOOK_DEADLINE_MS);
|
|
30
|
+
try {
|
|
31
|
+
const { handle } = await conn.request(sessionMessage(event, client, input, host, env));
|
|
32
|
+
if (event === 'session-end') {
|
|
33
|
+
return { exitCode: 0, stdout: '' };
|
|
34
|
+
}
|
|
35
|
+
const msg = { type: 'fetch-push', handle, limit: FETCH_PUSH_LIMIT };
|
|
36
|
+
const result = await conn.request(msg);
|
|
37
|
+
const texts = result.texts ?? [];
|
|
38
|
+
if (texts.length === 0) {
|
|
39
|
+
return { exitCode: 0, stdout: '' };
|
|
40
|
+
}
|
|
41
|
+
const text = 'murmur: ' + String(texts.length) + ' message(s) for ' + handle + '\n\n' + texts.join('\n\n');
|
|
42
|
+
return { exitCode: 0, stdout: JSON.stringify(outputFor(client, event, text)) };
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
clearTimeout(watchdog);
|
|
46
|
+
conn.close();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// Never fail or block a session because of murmur.
|
|
51
|
+
return { exitCode: 0, stdout: '' };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function sessionMessage(event, client, input, host, env) {
|
|
55
|
+
const msg = {
|
|
56
|
+
type: 'session',
|
|
57
|
+
event,
|
|
58
|
+
client,
|
|
59
|
+
cliSessionId: input.sessionId,
|
|
60
|
+
host: { hostPid: host.hostPid, hostStart: host.hostStart },
|
|
61
|
+
};
|
|
62
|
+
// zcode hands hooks a synthetic transcript it deletes afterwards, so it
|
|
63
|
+
// cannot serve as delivery proof.
|
|
64
|
+
if (input.transcriptPath !== null && client !== 'zcode') {
|
|
65
|
+
msg.transcriptPath = input.transcriptPath;
|
|
66
|
+
}
|
|
67
|
+
if (input.cwd !== null) {
|
|
68
|
+
msg.cwd = input.cwd;
|
|
69
|
+
}
|
|
70
|
+
const explicit = env.MURMUR_HANDLE;
|
|
71
|
+
if (typeof explicit === 'string' && explicit.length > 0) {
|
|
72
|
+
msg.handle = explicit;
|
|
73
|
+
}
|
|
74
|
+
// A Claude session exposes its own messaging socket to the processes it
|
|
75
|
+
// spawns; registering it lets the broker push straight into the session.
|
|
76
|
+
const socketPath = env.CLAUDE_CODE_MESSAGING_SOCKET;
|
|
77
|
+
const nativeToken = env.CLAUDE_CODE_MESSAGING_TOKEN;
|
|
78
|
+
if (client === 'claude' && event === 'session-start' && nonEmpty(socketPath) && nonEmpty(nativeToken)) {
|
|
79
|
+
msg.native = { socketPath, token: nativeToken };
|
|
80
|
+
}
|
|
81
|
+
return msg;
|
|
82
|
+
}
|
|
83
|
+
function nonEmpty(value) {
|
|
84
|
+
return typeof value === 'string' && value.length > 0;
|
|
85
|
+
}
|
|
86
|
+
// How each CLI takes text back from a hook. Start and prompt events add it
|
|
87
|
+
// to the model's context; stop asks the CLI to keep going with the text as
|
|
88
|
+
// the next instruction, so messages that arrived mid-turn are handled
|
|
89
|
+
// without waiting for the user.
|
|
90
|
+
function outputFor(client, event, text) {
|
|
91
|
+
if (event === 'stop') {
|
|
92
|
+
return { decision: client === 'gemini' ? 'deny' : 'block', reason: text };
|
|
93
|
+
}
|
|
94
|
+
let hookEventName = event === 'session-start' ? 'SessionStart' : 'UserPromptSubmit';
|
|
95
|
+
if (client === 'gemini' && event === 'prompt') {
|
|
96
|
+
hookEventName = 'BeforeAgent';
|
|
97
|
+
}
|
|
98
|
+
return { hookSpecificOutput: { hookEventName, additionalContext: text } };
|
|
99
|
+
}
|
|
100
|
+
// Reads the hook payload from stdin. A parse failure or missing field reads
|
|
101
|
+
// as null.
|
|
102
|
+
function parseInput(stdinText) {
|
|
103
|
+
let parsed;
|
|
104
|
+
try {
|
|
105
|
+
parsed = JSON.parse(stdinText);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
parsed = null;
|
|
109
|
+
}
|
|
110
|
+
const rec = typeof parsed === 'object' && parsed !== null ? parsed : {};
|
|
111
|
+
return {
|
|
112
|
+
sessionId: stringField(rec, 'session_id'),
|
|
113
|
+
transcriptPath: stringField(rec, 'transcript_path'),
|
|
114
|
+
cwd: stringField(rec, 'cwd'),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function stringField(rec, key) {
|
|
118
|
+
const value = rec[key];
|
|
119
|
+
return typeof value === 'string' && value.length > 0 ? value : null;
|
|
120
|
+
}
|
package/dist/install.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
export const INSTALL_CLIENTS = ['claude', 'codex', 'gemini', 'zcode', 'opencode', 'hummin'];
|
|
6
|
+
const BACKUP_SUFFIX = '.bak-murmur';
|
|
7
|
+
// The message travels through a quoted heredoc, so no shell ever parses it:
|
|
8
|
+
// quotes, $(...), backticks and ; arrive verbatim.
|
|
9
|
+
const SLASH_SHELL = "murmur slash --stdin <<'MURMUR_EOF_7F3A'\n$ARGUMENTS\nMURMUR_EOF_7F3A";
|
|
10
|
+
// Claude Code and zcode pre-run a fenced ```! block when the command runs.
|
|
11
|
+
const PRE_EXEC_COMMAND_MD = `---
|
|
12
|
+
description: Send to a murmur group or peer as the owner; bare lists peers and groups
|
|
13
|
+
argument-hint: <group | @group | handle[,more]> <message>
|
|
14
|
+
allowed-tools: Bash(murmur slash:*)
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
\`\`\`!
|
|
18
|
+
${SLASH_SHELL.replace('--stdin', '--stdin --claude-escaped')}
|
|
19
|
+
\`\`\`
|
|
20
|
+
|
|
21
|
+
The output above is the whole result of /murmur. Show it to the user as is and do nothing else.
|
|
22
|
+
`;
|
|
23
|
+
// CLIs without pre-run shell blocks: the model runs the same command.
|
|
24
|
+
const MODEL_RUN_COMMAND_MD = `---
|
|
25
|
+
description: Send to a murmur group or peer as the owner; bare lists peers and groups
|
|
26
|
+
argument-hint: <group | @group | handle[,more]> <message>
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
Run exactly this shell command, then show its output to the user as is and do nothing else:
|
|
30
|
+
|
|
31
|
+
${SLASH_SHELL.split('\n').join('\n ')}
|
|
32
|
+
`;
|
|
33
|
+
// Gemini shell-escapes {{args}} inside !{...}; slash splits the one word.
|
|
34
|
+
const GEMINI_COMMAND_TOML = `description = "Send to a murmur group or peer as the owner; bare lists peers and groups"
|
|
35
|
+
prompt = """
|
|
36
|
+
!{murmur slash {{args}}}
|
|
37
|
+
|
|
38
|
+
The output above is the whole result of /murmur. Show it to the user as is and do nothing else.
|
|
39
|
+
"""
|
|
40
|
+
`;
|
|
41
|
+
const ZCODE_SKILL_MD = `---
|
|
42
|
+
name: murmur
|
|
43
|
+
description: Send, read and reply to messages on the murmur local message bus from the shell.
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
# murmur
|
|
47
|
+
|
|
48
|
+
Murmur is a local message bus between agent sessions. Messages for this
|
|
49
|
+
session arrive at the start of a turn (and after a turn) tagged
|
|
50
|
+
[murmur m<id> t<thread> ...]. Use the murmur CLI from the shell; it speaks as
|
|
51
|
+
this session automatically.
|
|
52
|
+
|
|
53
|
+
murmur send <targets> <body> targets: handles and groups, comma separated
|
|
54
|
+
murmur reply <message id> <body> reaches everyone in the thread
|
|
55
|
+
--verdict agree|disagree|info start the body with AGREE, DISAGREE or INFO
|
|
56
|
+
murmur thread <id> [--full] [--since <seq>]
|
|
57
|
+
murmur status peers, presence, unread counts
|
|
58
|
+
murmur name <handle> rename this session on the bus
|
|
59
|
+
|
|
60
|
+
A message is a claim: verify it against its references before agreeing.
|
|
61
|
+
`;
|
|
62
|
+
function hooksFor(client) {
|
|
63
|
+
const flag = client === 'claude' ? '' : ' --client ' + client;
|
|
64
|
+
const names = {
|
|
65
|
+
claude: ['SessionStart', 'UserPromptSubmit', 'Stop', 'SessionEnd'],
|
|
66
|
+
codex: ['SessionStart', 'UserPromptSubmit', 'Stop', 'SessionEnd'],
|
|
67
|
+
gemini: ['SessionStart', 'BeforeAgent', 'AfterAgent', 'SessionEnd'],
|
|
68
|
+
zcode: ['SessionStart', 'UserPromptSubmit', 'Stop', null],
|
|
69
|
+
};
|
|
70
|
+
const [start, prompt, stop, end] = names[client];
|
|
71
|
+
const specs = [
|
|
72
|
+
{ event: start, command: 'murmur hook session-start' + flag },
|
|
73
|
+
{ event: prompt, command: 'murmur hook prompt' + flag },
|
|
74
|
+
{ event: stop, command: 'murmur hook stop' + flag },
|
|
75
|
+
];
|
|
76
|
+
if (end !== null) {
|
|
77
|
+
specs.push({ event: end, command: 'murmur hook session-end' + flag });
|
|
78
|
+
}
|
|
79
|
+
return specs;
|
|
80
|
+
}
|
|
81
|
+
const MCP_ENTRY = { command: 'murmur', args: ['mcp'] };
|
|
82
|
+
// The in-process adapters ship as source files next to dist/ and src/.
|
|
83
|
+
function adapterSource(name) {
|
|
84
|
+
return fileURLToPath(new URL('../adapters/' + name + '/murmur.ts', import.meta.url));
|
|
85
|
+
}
|
|
86
|
+
// Returns the files written plus any step the user still has to take.
|
|
87
|
+
export async function installClient(client, opts) {
|
|
88
|
+
const home = opts?.home ?? homedir();
|
|
89
|
+
switch (client) {
|
|
90
|
+
case 'claude':
|
|
91
|
+
return installClaude(home);
|
|
92
|
+
case 'codex':
|
|
93
|
+
return installCodex(home);
|
|
94
|
+
case 'gemini':
|
|
95
|
+
return installGemini(home);
|
|
96
|
+
case 'zcode':
|
|
97
|
+
return installZcode(home);
|
|
98
|
+
case 'opencode':
|
|
99
|
+
return installOpencode(home);
|
|
100
|
+
case 'hummin':
|
|
101
|
+
return installHummin(home);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function installClaude(home) {
|
|
105
|
+
const commandPath = join(home, '.claude', 'commands', 'murmur.md');
|
|
106
|
+
writeTextFile(commandPath, PRE_EXEC_COMMAND_MD);
|
|
107
|
+
const claudeJsonPath = join(home, '.claude.json');
|
|
108
|
+
const claudeJson = readJsonObject(claudeJsonPath);
|
|
109
|
+
mergeMcpServer(objectAt(claudeJson, 'mcpServers', claudeJsonPath));
|
|
110
|
+
writeJsonFile(claudeJsonPath, claudeJson);
|
|
111
|
+
const settingsPath = join(home, '.claude', 'settings.json');
|
|
112
|
+
const settings = readJsonObject(settingsPath);
|
|
113
|
+
mergeHooks(objectAt(settings, 'hooks', settingsPath), hooksFor('claude'));
|
|
114
|
+
writeJsonFile(settingsPath, settings);
|
|
115
|
+
return [commandPath, claudeJsonPath, settingsPath];
|
|
116
|
+
}
|
|
117
|
+
function installCodex(home) {
|
|
118
|
+
const hooksPath = join(home, '.codex', 'hooks.json');
|
|
119
|
+
const doc = readJsonObject(hooksPath);
|
|
120
|
+
mergeHooks(objectAt(doc, 'hooks', hooksPath), hooksFor('codex'));
|
|
121
|
+
writeJsonFile(hooksPath, doc);
|
|
122
|
+
const configPath = join(home, '.codex', 'config.toml');
|
|
123
|
+
const config = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
|
|
124
|
+
if (!/^\[mcp_servers\.murmur\]/m.test(config)) {
|
|
125
|
+
const sep = config.length === 0 || config.endsWith('\n') ? '' : '\n';
|
|
126
|
+
writeTextFile(configPath, config + sep + '\n[mcp_servers.murmur]\ncommand = "murmur"\nargs = ["mcp"]\n');
|
|
127
|
+
}
|
|
128
|
+
const promptPath = join(home, '.codex', 'prompts', 'murmur.md');
|
|
129
|
+
writeTextFile(promptPath, MODEL_RUN_COMMAND_MD);
|
|
130
|
+
return [hooksPath, configPath, promptPath, 'codex: open /hooks once and trust the murmur hooks; the command is /prompts:murmur'];
|
|
131
|
+
}
|
|
132
|
+
function installGemini(home) {
|
|
133
|
+
const settingsPath = join(home, '.gemini', 'settings.json');
|
|
134
|
+
const settings = readJsonObject(settingsPath);
|
|
135
|
+
mergeMcpServer(objectAt(settings, 'mcpServers', settingsPath));
|
|
136
|
+
mergeHooks(objectAt(settings, 'hooks', settingsPath), hooksFor('gemini'));
|
|
137
|
+
writeJsonFile(settingsPath, settings);
|
|
138
|
+
const commandPath = join(home, '.gemini', 'commands', 'murmur.toml');
|
|
139
|
+
writeTextFile(commandPath, GEMINI_COMMAND_TOML);
|
|
140
|
+
return [settingsPath, commandPath];
|
|
141
|
+
}
|
|
142
|
+
function installZcode(home) {
|
|
143
|
+
const configPath = join(home, '.zcode', 'cli', 'config.json');
|
|
144
|
+
const config = readJsonObject(configPath);
|
|
145
|
+
const hooks = objectAt(config, 'hooks', configPath);
|
|
146
|
+
hooks.enabled = true;
|
|
147
|
+
mergeHooks(objectAt(hooks, 'events', configPath), hooksFor('zcode'));
|
|
148
|
+
mergeMcpServer(objectAt(objectAt(config, 'mcp', configPath), 'servers', configPath));
|
|
149
|
+
writeJsonFile(configPath, config);
|
|
150
|
+
const commandPath = join(home, '.zcode', 'commands', 'murmur.md');
|
|
151
|
+
writeTextFile(commandPath, PRE_EXEC_COMMAND_MD);
|
|
152
|
+
const skillPath = join(home, '.zcode', 'skills', 'murmur', 'SKILL.md');
|
|
153
|
+
writeTextFile(skillPath, ZCODE_SKILL_MD);
|
|
154
|
+
return [configPath, commandPath, skillPath];
|
|
155
|
+
}
|
|
156
|
+
function installOpencode(home) {
|
|
157
|
+
const pluginPath = join(home, '.config', 'opencode', 'plugins', 'murmur.ts');
|
|
158
|
+
writeTextFile(pluginPath, readFileSync(adapterSource('opencode'), 'utf8'));
|
|
159
|
+
const commandPath = join(home, '.config', 'opencode', 'commands', 'murmur.md');
|
|
160
|
+
writeTextFile(commandPath, MODEL_RUN_COMMAND_MD);
|
|
161
|
+
return [pluginPath, commandPath];
|
|
162
|
+
}
|
|
163
|
+
function installHummin(home) {
|
|
164
|
+
const extensionPath = join(home, '.hummin', 'agent', 'extensions', 'murmur.ts');
|
|
165
|
+
writeTextFile(extensionPath, readFileSync(adapterSource('hummin'), 'utf8'));
|
|
166
|
+
return [extensionPath];
|
|
167
|
+
}
|
|
168
|
+
// File helpers.
|
|
169
|
+
function writeTextFile(file, content) {
|
|
170
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
171
|
+
backupBeforeWrite(file);
|
|
172
|
+
writeFileSync(file, content, 'utf8');
|
|
173
|
+
}
|
|
174
|
+
function writeJsonFile(file, value) {
|
|
175
|
+
writeTextFile(file, JSON.stringify(value, null, 2) + '\n');
|
|
176
|
+
}
|
|
177
|
+
function backupBeforeWrite(file) {
|
|
178
|
+
if (existsSync(file) && !existsSync(file + BACKUP_SUFFIX)) {
|
|
179
|
+
copyFileSync(file, file + BACKUP_SUFFIX);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
// Reads a JSON object file; a missing file reads as empty. An unparsable or
|
|
183
|
+
// non-object file is an error so murmur can never destroy user settings.
|
|
184
|
+
function readJsonObject(file) {
|
|
185
|
+
if (!existsSync(file)) {
|
|
186
|
+
return {};
|
|
187
|
+
}
|
|
188
|
+
let parsed;
|
|
189
|
+
try {
|
|
190
|
+
parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
191
|
+
}
|
|
192
|
+
catch (err) {
|
|
193
|
+
throw new Error('murmur install: ' + file + ' is not valid JSON, fix or remove it first: ' + err.message);
|
|
194
|
+
}
|
|
195
|
+
if (!isRecord(parsed)) {
|
|
196
|
+
throw new Error('murmur install: ' + file + ' does not hold a JSON object');
|
|
197
|
+
}
|
|
198
|
+
return parsed;
|
|
199
|
+
}
|
|
200
|
+
function isRecord(value) {
|
|
201
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
202
|
+
}
|
|
203
|
+
// The object under key, created when missing. Anything else there is an
|
|
204
|
+
// error, never overwritten.
|
|
205
|
+
function objectAt(parent, key, file) {
|
|
206
|
+
const value = parent[key];
|
|
207
|
+
if (value === undefined) {
|
|
208
|
+
const created = {};
|
|
209
|
+
parent[key] = created;
|
|
210
|
+
return created;
|
|
211
|
+
}
|
|
212
|
+
if (!isRecord(value)) {
|
|
213
|
+
throw new Error('murmur install: "' + key + '" in ' + file + ' is not an object');
|
|
214
|
+
}
|
|
215
|
+
return value;
|
|
216
|
+
}
|
|
217
|
+
// Merge helpers. Each adds only what is missing and leaves every other key
|
|
218
|
+
// untouched.
|
|
219
|
+
// The murmur server entry, keeping any env the user added but dropping the
|
|
220
|
+
// per-session handle placeholder older versions wrote: identity now comes
|
|
221
|
+
// from the session's host process.
|
|
222
|
+
function mergeMcpServer(servers) {
|
|
223
|
+
const existing = servers.murmur;
|
|
224
|
+
const env = isRecord(existing) && isRecord(existing.env) ? { ...existing.env } : {};
|
|
225
|
+
if (env.MURMUR_HANDLE === 'CHANGE-ME-per-session') {
|
|
226
|
+
delete env.MURMUR_HANDLE;
|
|
227
|
+
}
|
|
228
|
+
servers.murmur = Object.keys(env).length > 0 ? { ...MCP_ENTRY, env } : { ...MCP_ENTRY };
|
|
229
|
+
}
|
|
230
|
+
// Claude-style hook maps: event name to a list of { matcher?, hooks: [...] }.
|
|
231
|
+
function mergeHooks(hooks, specs) {
|
|
232
|
+
for (const { event, command } of specs) {
|
|
233
|
+
const current = hooks[event];
|
|
234
|
+
const entries = Array.isArray(current) ? current : [];
|
|
235
|
+
if (!entries.some((entry) => entryHasCommand(entry, command))) {
|
|
236
|
+
entries.push({ hooks: [{ type: 'command', command }] });
|
|
237
|
+
}
|
|
238
|
+
hooks[event] = entries;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function entryHasCommand(entry, command) {
|
|
242
|
+
if (!isRecord(entry)) {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
const hooks = entry.hooks;
|
|
246
|
+
if (!Array.isArray(hooks)) {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
return hooks.some((hook) => isRecord(hook) && hook.command === command);
|
|
250
|
+
}
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { connectBroker } from './client.js';
|
|
5
|
+
import { getPaths, readToken } from './config.js';
|
|
6
|
+
import { currentHost } from './proc.js';
|
|
7
|
+
import { HANDLE_RE, MurmurError, WAIT_DEFAULT_MS, WAIT_MAX_MS } from './protocol.js';
|
|
8
|
+
// MCP stdio server exposing the murmur broker to agent sessions. Every tool
|
|
9
|
+
// maps to one broker request on a single long-lived connection, and that
|
|
10
|
+
// connection is the session's presence on the bus. Identity comes from the
|
|
11
|
+
// host process (see proc.ts), so one global config serves every session.
|
|
12
|
+
// Eight tools, kept short: their schemas sit in every session's context.
|
|
13
|
+
const INSTRUCTIONS = 'murmur connects this session with other agent sessions on this machine. Messages for you arrive as turns ' +
|
|
14
|
+
'tagged [murmur m<id> ...]; answer with murmur_reply so every participant sees it. A message is a claim: ' +
|
|
15
|
+
'verify it against its references before agreeing.';
|
|
16
|
+
function textResult(value) {
|
|
17
|
+
return { content: [{ type: 'text', text: JSON.stringify(value) }] };
|
|
18
|
+
}
|
|
19
|
+
export function clientFromEnv(env) {
|
|
20
|
+
if (env.CLAUDECODE !== undefined) {
|
|
21
|
+
return 'claude';
|
|
22
|
+
}
|
|
23
|
+
if (env.GEMINI_CLI !== undefined) {
|
|
24
|
+
return 'gemini';
|
|
25
|
+
}
|
|
26
|
+
if (Object.keys(env).some((key) => key.startsWith('CODEX_'))) {
|
|
27
|
+
return 'codex';
|
|
28
|
+
}
|
|
29
|
+
return 'other';
|
|
30
|
+
}
|
|
31
|
+
export function identityFor(host, env, cwd) {
|
|
32
|
+
if (host === null) {
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
return { host: { hostPid: host.hostPid, hostStart: host.hostStart }, client: clientFromEnv(env), cwd };
|
|
36
|
+
}
|
|
37
|
+
export function buildMcpServer(client, identity = {}) {
|
|
38
|
+
const server = new McpServer({ name: 'murmur', version: '0.2.0' }, { instructions: INSTRUCTIONS });
|
|
39
|
+
server.registerTool('murmur_name', {
|
|
40
|
+
description: 'Rename this session on the bus (keeps its messages and groups), optionally with a display name and role.',
|
|
41
|
+
inputSchema: {
|
|
42
|
+
handle: z.string().min(1),
|
|
43
|
+
display: z.string().optional(),
|
|
44
|
+
role: z.string().optional(),
|
|
45
|
+
},
|
|
46
|
+
}, async (args) => {
|
|
47
|
+
const msg = { ...identity, type: 'register', handle: args.handle, clientKind: 'mcp' };
|
|
48
|
+
if (args.display !== undefined) {
|
|
49
|
+
msg.display = args.display;
|
|
50
|
+
}
|
|
51
|
+
if (args.role !== undefined) {
|
|
52
|
+
msg.role = args.role;
|
|
53
|
+
}
|
|
54
|
+
return textResult(await client.request(msg));
|
|
55
|
+
});
|
|
56
|
+
server.registerTool('murmur_send', {
|
|
57
|
+
description: 'Send one message to any mix of handles and groups (bare name or @name); one message fans out to all.',
|
|
58
|
+
inputSchema: {
|
|
59
|
+
threadId: z.number().int().optional(),
|
|
60
|
+
to: z.array(z.string().min(1)).min(1),
|
|
61
|
+
body: z.string().min(1),
|
|
62
|
+
references: z.array(z.string()).optional(),
|
|
63
|
+
mode: z.enum(['push', 'notify', 'silent']).optional(),
|
|
64
|
+
},
|
|
65
|
+
}, async (args) => {
|
|
66
|
+
const msg = {
|
|
67
|
+
type: 'send',
|
|
68
|
+
threadId: args.threadId ?? null,
|
|
69
|
+
to: args.to,
|
|
70
|
+
body: args.body,
|
|
71
|
+
};
|
|
72
|
+
if (args.references !== undefined) {
|
|
73
|
+
msg.references = args.references;
|
|
74
|
+
}
|
|
75
|
+
if (args.mode !== undefined) {
|
|
76
|
+
msg.mode = args.mode;
|
|
77
|
+
}
|
|
78
|
+
return textResult(await client.request(msg));
|
|
79
|
+
});
|
|
80
|
+
server.registerTool('murmur_reply', {
|
|
81
|
+
description: 'Reply to a message by id; reaches everyone in its thread. Start the body with AGREE, DISAGREE or INFO and set verdict to match.',
|
|
82
|
+
inputSchema: {
|
|
83
|
+
messageId: z.number().int(),
|
|
84
|
+
body: z.string().min(1),
|
|
85
|
+
verdict: z.enum(['agree', 'disagree', 'info']).optional(),
|
|
86
|
+
references: z.array(z.string()).optional(),
|
|
87
|
+
},
|
|
88
|
+
}, async (args) => {
|
|
89
|
+
const msg = { type: 'reply', messageId: args.messageId, body: args.body };
|
|
90
|
+
if (args.verdict !== undefined) {
|
|
91
|
+
msg.verdict = args.verdict;
|
|
92
|
+
}
|
|
93
|
+
if (args.references !== undefined) {
|
|
94
|
+
msg.references = args.references;
|
|
95
|
+
}
|
|
96
|
+
return textResult(await client.request(msg));
|
|
97
|
+
});
|
|
98
|
+
server.registerTool('murmur_ack', {
|
|
99
|
+
description: 'Tell senders you saw these messages and will answer later.',
|
|
100
|
+
inputSchema: {
|
|
101
|
+
ids: z.array(z.number().int()).min(1),
|
|
102
|
+
},
|
|
103
|
+
}, async (args) => {
|
|
104
|
+
const msg = { type: 'ack', ids: args.ids };
|
|
105
|
+
return textResult(await client.request(msg));
|
|
106
|
+
});
|
|
107
|
+
server.registerTool('murmur_thread', {
|
|
108
|
+
description: 'Read a thread: first lines by default, full bodies with full, only newer than sinceSeq.',
|
|
109
|
+
inputSchema: {
|
|
110
|
+
threadId: z.number().int(),
|
|
111
|
+
sinceSeq: z.number().int().optional(),
|
|
112
|
+
full: z.boolean().optional(),
|
|
113
|
+
},
|
|
114
|
+
}, async (args) => {
|
|
115
|
+
const msg = {
|
|
116
|
+
type: 'thread',
|
|
117
|
+
threadId: args.threadId,
|
|
118
|
+
sinceSeq: args.sinceSeq ?? null,
|
|
119
|
+
full: args.full ?? false,
|
|
120
|
+
};
|
|
121
|
+
return textResult(await client.request(msg));
|
|
122
|
+
});
|
|
123
|
+
server.registerTool('murmur_wait', {
|
|
124
|
+
description: 'Who got, read and answered the latest ask, with verdicts and latencies. Waits until all_replied or any_replied, up to timeoutMs (default 120000, max 300000; 0 returns now).',
|
|
125
|
+
inputSchema: {
|
|
126
|
+
threadId: z.number().int(),
|
|
127
|
+
until: z.enum(['all_replied', 'any_replied']),
|
|
128
|
+
timeoutMs: z.number().int().min(0).optional(),
|
|
129
|
+
},
|
|
130
|
+
}, async (args) => {
|
|
131
|
+
const timeoutMs = Math.min(args.timeoutMs ?? WAIT_DEFAULT_MS, WAIT_MAX_MS);
|
|
132
|
+
const msg = {
|
|
133
|
+
type: 'wait',
|
|
134
|
+
threadId: args.threadId,
|
|
135
|
+
until: args.until,
|
|
136
|
+
timeoutMs,
|
|
137
|
+
};
|
|
138
|
+
return textResult(await client.request(msg));
|
|
139
|
+
});
|
|
140
|
+
server.registerTool('murmur_groups', {
|
|
141
|
+
description: 'Create, list, add to, remove from, or delete a group. Deleting never touches sessions or history.',
|
|
142
|
+
inputSchema: {
|
|
143
|
+
action: z.enum(['create', 'list', 'add', 'remove', 'delete']),
|
|
144
|
+
name: z.string().min(1).optional(),
|
|
145
|
+
members: z.array(z.string().min(1)).optional(),
|
|
146
|
+
},
|
|
147
|
+
}, async (args) => {
|
|
148
|
+
const msg = { type: 'groups', action: args.action };
|
|
149
|
+
if (args.name !== undefined) {
|
|
150
|
+
msg.name = args.name;
|
|
151
|
+
}
|
|
152
|
+
if (args.members !== undefined) {
|
|
153
|
+
msg.members = args.members;
|
|
154
|
+
}
|
|
155
|
+
return textResult(await client.request(msg));
|
|
156
|
+
});
|
|
157
|
+
server.registerTool('murmur_status', {
|
|
158
|
+
description: 'Every peer with presence (busy, idle, online, offline), its CLI and unread counts.',
|
|
159
|
+
}, async () => {
|
|
160
|
+
const msg = { type: 'status' };
|
|
161
|
+
return textResult(await client.request(msg));
|
|
162
|
+
});
|
|
163
|
+
return server;
|
|
164
|
+
}
|
|
165
|
+
export async function runMcpServer() {
|
|
166
|
+
const paths = getPaths();
|
|
167
|
+
const identity = identityFor(currentHost(undefined, false), process.env, process.cwd());
|
|
168
|
+
let client;
|
|
169
|
+
try {
|
|
170
|
+
const token = readToken(paths);
|
|
171
|
+
client = await connectBroker({ socketPath: paths.socketPath, token });
|
|
172
|
+
}
|
|
173
|
+
catch (err) {
|
|
174
|
+
const code = err instanceof MurmurError ? err.code : 'internal';
|
|
175
|
+
process.stderr.write('murmur mcp: cannot connect to broker at ' + paths.socketPath + ' (' + code + '): ' + err.message + '\n');
|
|
176
|
+
process.exit(1);
|
|
177
|
+
}
|
|
178
|
+
// MURMUR_HANDLE is an optional per-process override; anything invalid
|
|
179
|
+
// (like an old CHANGE-ME placeholder) or already taken is ignored so the
|
|
180
|
+
// server still starts under its session's own handle.
|
|
181
|
+
const explicit = process.env.MURMUR_HANDLE;
|
|
182
|
+
const wanted = explicit !== undefined && HANDLE_RE.test(explicit) ? explicit : undefined;
|
|
183
|
+
const base = identity.host === undefined
|
|
184
|
+
? { type: 'register', handle: wanted ?? 'anon-' + String(process.pid), clientKind: 'mcp' }
|
|
185
|
+
: { ...identity, type: 'register', clientKind: 'mcp' };
|
|
186
|
+
try {
|
|
187
|
+
try {
|
|
188
|
+
await client.request(wanted !== undefined && identity.host !== undefined ? { ...base, handle: wanted } : base);
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
if (wanted === undefined || identity.host === undefined) {
|
|
192
|
+
throw err;
|
|
193
|
+
}
|
|
194
|
+
await client.request(base);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
const code = err instanceof MurmurError ? err.code : 'internal';
|
|
199
|
+
process.stderr.write('murmur mcp: broker rejected registration (' + code + '): ' + err.message + '\n');
|
|
200
|
+
process.exit(1);
|
|
201
|
+
}
|
|
202
|
+
// Tear the broker connection down when the process exits so the broker
|
|
203
|
+
// marks this session offline promptly.
|
|
204
|
+
process.on('exit', () => {
|
|
205
|
+
client.close();
|
|
206
|
+
});
|
|
207
|
+
const server = buildMcpServer(client, identity);
|
|
208
|
+
await server.connect(new StdioServerTransport());
|
|
209
|
+
// The open stdio transport keeps the event loop alive and this long-lived
|
|
210
|
+
// broker connection is the session's presence, so in normal operation this
|
|
211
|
+
// await holds until the process is killed. It ends early only when the
|
|
212
|
+
// broker connection drops (client.onClosed), which lets the process exit
|
|
213
|
+
// instead of lingering with a dead session.
|
|
214
|
+
await new Promise((resolve) => {
|
|
215
|
+
client.onClosed = resolve;
|
|
216
|
+
});
|
|
217
|
+
}
|