@murmurv2/mcp-server 0.1.0 → 0.2.3

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.
@@ -0,0 +1,44 @@
1
+ export interface AgentConfig {
2
+ agentId: string;
3
+ memberId?: string;
4
+ natsUrl: string;
5
+ natsToken?: string;
6
+ subject: string;
7
+ subjectScoping?: {
8
+ enabled?: boolean;
9
+ channelIds?: string[];
10
+ };
11
+ dataDir: string;
12
+ keys: {
13
+ encryption: {
14
+ publicKey: string;
15
+ privateKey: string;
16
+ };
17
+ signing: {
18
+ publicKey: string;
19
+ privateKey: string;
20
+ };
21
+ };
22
+ peers: Record<string, {
23
+ encryption: {
24
+ publicKey: string;
25
+ };
26
+ signing: {
27
+ publicKey: string;
28
+ };
29
+ subject: string;
30
+ subjectScoping?: boolean;
31
+ channelId?: string;
32
+ memberId?: string;
33
+ }>;
34
+ }
35
+ /** Peer-only refresh; a process remains bound to its first valid identity/runtime. */
36
+ export declare class AgentConfigCache {
37
+ private readonly filePath;
38
+ private cached;
39
+ private pinnedIdentity;
40
+ private pinnedBinding;
41
+ private directory;
42
+ constructor(filePath: string);
43
+ read(force?: boolean): AgentConfig;
44
+ }
@@ -0,0 +1,89 @@
1
+ import { chmodSync, closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ const sameFile = (a, b) => a.ino === b.ino && (process.platform === "win32"
4
+ ? a.dev === 0n || b.dev === 0n || BigInt.asUintN(32, a.dev) === BigInt.asUintN(32, b.dev)
5
+ : a.dev === b.dev);
6
+ const stamp = (s) => [s.dev, s.ino, s.mtimeNs, s.ctimeNs, s.size, s.mode, s.uid].join(":");
7
+ const validateFile = (s) => {
8
+ if (s.isSymbolicLink() || !s.isFile())
9
+ throw new Error("agent-config-file-invalid");
10
+ if (typeof process.getuid === "function" && s.uid !== BigInt(process.getuid()))
11
+ throw new Error("agent-config-file-owner-mismatch");
12
+ };
13
+ const identity = (c) => JSON.stringify([c.agentId,
14
+ c.keys?.encryption?.publicKey, c.keys?.encryption?.privateKey,
15
+ c.keys?.signing?.publicKey, c.keys?.signing?.privateKey]);
16
+ const binding = (c) => JSON.stringify([c.memberId, c.subject, c.natsUrl, c.natsToken, c.dataDir,
17
+ c.subjectScoping?.enabled, [...(c.subjectScoping?.channelIds ?? [])].sort()]);
18
+ /** Peer-only refresh; a process remains bound to its first valid identity/runtime. */
19
+ export class AgentConfigCache {
20
+ filePath;
21
+ cached = null;
22
+ pinnedIdentity;
23
+ pinnedBinding;
24
+ directory;
25
+ constructor(filePath) {
26
+ this.filePath = filePath;
27
+ }
28
+ read(force = false) {
29
+ try {
30
+ process.umask(0o077);
31
+ const dir = path.dirname(this.filePath);
32
+ const directory = lstatSync(dir, { bigint: true });
33
+ if (directory.isSymbolicLink() || !directory.isDirectory())
34
+ throw new Error("agent-config-directory-invalid");
35
+ if (typeof process.getuid === "function" && directory.uid !== BigInt(process.getuid()))
36
+ throw new Error("agent-config-directory-owner-mismatch");
37
+ if (this.directory && !sameFile(this.directory, directory))
38
+ throw new Error("agent-config-profile-changed-restart-required");
39
+ chmodSync(dir, 0o700);
40
+ const before = lstatSync(this.filePath, { bigint: true });
41
+ validateFile(before);
42
+ if (!force && this.cached?.stamp === stamp(before))
43
+ return this.cached.config;
44
+ const fd = openSync(this.filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
45
+ let config, finalStats;
46
+ try {
47
+ const opened = fstatSync(fd, { bigint: true });
48
+ validateFile(opened);
49
+ if (!sameFile(before, opened) || before.size !== opened.size || before.mtimeNs !== opened.mtimeNs)
50
+ throw new Error("agent-config-file-changed");
51
+ fchmodSync(fd, 0o600);
52
+ const reading = fstatSync(fd, { bigint: true });
53
+ const contents = readFileSync(fd, "utf8");
54
+ finalStats = fstatSync(fd, { bigint: true });
55
+ const after = lstatSync(this.filePath, { bigint: true });
56
+ validateFile(after);
57
+ if (!sameFile(opened, after) || stamp(reading) !== stamp(finalStats)
58
+ || after.size !== finalStats.size || after.mtimeNs !== finalStats.mtimeNs || after.ctimeNs !== finalStats.ctimeNs
59
+ || !sameFile(directory, lstatSync(dir, { bigint: true })))
60
+ throw new Error("agent-config-file-changed");
61
+ // Path and handle dev differ on Node 22.13/Windows; cache the path stamp.
62
+ finalStats = after;
63
+ config = JSON.parse(contents);
64
+ }
65
+ finally {
66
+ closeSync(fd);
67
+ }
68
+ if (!config || typeof config.agentId !== "string" || !config.agentId.trim()
69
+ || !config.peers || typeof config.peers !== "object" || Array.isArray(config.peers))
70
+ throw new Error("agent-config-invalid");
71
+ const nextIdentity = identity(config), nextBinding = binding(config);
72
+ if (this.pinnedIdentity !== undefined && nextIdentity !== this.pinnedIdentity)
73
+ throw new Error("agent-config-identity-changed-restart-required");
74
+ if (this.pinnedBinding !== undefined && nextBinding !== this.pinnedBinding)
75
+ throw new Error("agent-config-runtime-changed-restart-required");
76
+ this.pinnedIdentity = nextIdentity;
77
+ this.pinnedBinding = nextBinding;
78
+ this.directory = directory;
79
+ this.cached = { config, stamp: stamp(finalStats) };
80
+ return config;
81
+ }
82
+ catch (error) {
83
+ this.cached = null; // Never send with old peer keys after any read/parse/policy failure.
84
+ if (error instanceof Error && /^agent-config-[a-z-]+$/.test(error.message))
85
+ throw error;
86
+ throw new Error("agent-config-unavailable-retry-or-restart");
87
+ }
88
+ }
89
+ }
@@ -0,0 +1,6 @@
1
+ export declare const codexTaskConversationId: (threadId: string | undefined) => string | null;
2
+ export declare const defaultPeerConversationId: ({ to, agentId, codexThreadId, }: {
3
+ to: string;
4
+ agentId: string;
5
+ codexThreadId?: string;
6
+ }) => string;
@@ -0,0 +1,6 @@
1
+ const THREAD_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2
+ export const codexTaskConversationId = (threadId) => {
3
+ const value = String(threadId ?? "").trim();
4
+ return THREAD_ID_PATTERN.test(value) ? `codex:task:${value}` : null;
5
+ };
6
+ export const defaultPeerConversationId = ({ to, agentId, codexThreadId, }) => codexTaskConversationId(codexThreadId) ?? `dm:${agentId}:${to}`;
package/dist/src/index.js CHANGED
@@ -1,39 +1,187 @@
1
- import { randomUUID } from "node:crypto";
2
- import { readFileSync } from "node:fs";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { chmodSync, closeSync, constants, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { createInterface } from "node:readline";
5
- import { SQLiteDedupeOutboxStore, SQLiteMessageStore, } from "@murmurv2/core";
5
+ import { ChannelRosterStore, SQLiteDedupeOutboxStore, SQLiteMessageStore, stableEnvelopePayload, resolveMessageSubject, channelScopedSubject, } from "@murmurv2/core";
6
6
  import { encryptPayload, signEnvelope } from "@murmurv2/security";
7
+ import { NatsBroker } from "@murmurv2/broker-nats";
8
+ import { codexTaskConversationId, defaultPeerConversationId } from "./codex-routing.js";
9
+ import { buildReplyMatcher, createReplySignalTap, requestDelivery, requestTiming, waitForReply } from "./request-reply.js";
10
+ import { AgentConfigCache } from "./agent-config.js";
7
11
  // --- Load agent config (optional — gracefully degrade if missing) ---
8
12
  const dataDir = process.env.DATA_DIR || ".data";
9
13
  const configPath = path.join(dataDir, "agent-config.json");
10
14
  const dbPath = process.env.MURMUR_STORE_PATH ?? path.join(dataDir, "murmur.db");
11
- let agentConfig = null;
15
+ const channelRosterPath = process.env.MURMUR_CHANNEL_ROSTER_PATH ?? path.join(dataDir, "channel-roster.db");
16
+ // One stdio connection is one chat session. Callers cannot impersonate another
17
+ // session/agent through tool arguments; hosts may supply their stable session ID.
18
+ const presenceSessionId = (process.env.MURMUR_SESSION_ID || process.env.CODEX_THREAD_ID || process.env.CLAUDE_CODE_SESSION_ID || `mcp:${randomUUID()}`).trim();
19
+ const requestWaitDir = path.resolve(dataDir, ".codex-request-waits");
20
+ const taskBindingDir = path.resolve(dataDir, ".codex-task-bindings");
21
+ const privateDigestPath = (directory, conversationId, peerId) => {
22
+ const key = createHash("sha256").update(`${conversationId}\0${peerId}`).digest("hex");
23
+ return path.join(directory, `${key}.json`);
24
+ };
25
+ const requestWaitPath = (conversationId, peerId) => {
26
+ return privateDigestPath(requestWaitDir, conversationId, peerId);
27
+ };
28
+ const armSynchronousReplySuppression = (conversationId, peerId, timeoutMs) => {
29
+ try {
30
+ mkdirSync(requestWaitDir, { recursive: true, mode: 0o700 });
31
+ chmodSync(requestWaitDir, 0o700);
32
+ const markerPath = requestWaitPath(conversationId, peerId);
33
+ const marker = {
34
+ conversationId,
35
+ peerId,
36
+ pid: process.pid,
37
+ expiresAt: Date.now() + Math.max(1_000, timeoutMs) + 60_000,
38
+ };
39
+ const create = () => {
40
+ const fd = openSync(markerPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
41
+ try {
42
+ writeFileSync(fd, JSON.stringify(marker));
43
+ }
44
+ finally {
45
+ closeSync(fd);
46
+ }
47
+ return markerPath;
48
+ };
49
+ try {
50
+ return create();
51
+ }
52
+ catch (error) {
53
+ if (error.code !== "EEXIST")
54
+ throw error;
55
+ let existingLive = true;
56
+ try {
57
+ const existing = JSON.parse(readFileSync(markerPath, "utf8"));
58
+ existingLive = Number(existing.expiresAt) >= Date.now();
59
+ if (existingLive && Number.isSafeInteger(existing.pid) && Number(existing.pid) > 0) {
60
+ try {
61
+ process.kill(Number(existing.pid), 0);
62
+ }
63
+ catch {
64
+ existingLive = false;
65
+ }
66
+ }
67
+ }
68
+ catch {
69
+ existingLive = false;
70
+ }
71
+ if (existingLive)
72
+ throw new Error("murmur-request-already-pending-for-peer-and-conversation");
73
+ rmSync(markerPath, { force: true });
74
+ return create();
75
+ }
76
+ }
77
+ catch (error) {
78
+ if (error.message === "murmur-request-already-pending-for-peer-and-conversation")
79
+ throw error;
80
+ // Suppression is only a convenience. Request/reply must still work if the
81
+ // marker cannot be written.
82
+ return null;
83
+ }
84
+ };
85
+ const shortenSynchronousReplySuppression = (markerPath, graceMs = 5_000) => {
86
+ if (!markerPath)
87
+ return;
88
+ try {
89
+ const marker = JSON.parse(readFileSync(markerPath, "utf8"));
90
+ writeFileSync(markerPath, JSON.stringify({ ...marker, expiresAt: Date.now() + graceMs }), { mode: 0o600 });
91
+ const timer = setTimeout(() => clearSynchronousReplySuppression(markerPath), graceMs);
92
+ timer.unref();
93
+ }
94
+ catch {
95
+ // The receive hook may already have atomically claimed the marker.
96
+ }
97
+ };
98
+ const recordCodexTaskPeerBinding = (conversationId, peerId) => {
99
+ const ownTaskConversationId = codexTaskConversationId(process.env.CODEX_THREAD_ID);
100
+ if (!ownTaskConversationId || conversationId !== ownTaskConversationId)
101
+ return;
102
+ try {
103
+ mkdirSync(taskBindingDir, { recursive: true, mode: 0o700 });
104
+ chmodSync(taskBindingDir, 0o700);
105
+ const bindingPath = privateDigestPath(taskBindingDir, conversationId, peerId);
106
+ writeFileSync(bindingPath, JSON.stringify({ conversationId, peerId, createdAt: new Date().toISOString() }), { mode: 0o600 });
107
+ chmodSync(bindingPath, 0o600);
108
+ }
109
+ catch {
110
+ // Binding is a local auto-delivery authorization. A write failure safely
111
+ // degrades replies to inbox-only delivery on the receiving hook.
112
+ }
113
+ };
114
+ const clearSynchronousReplySuppression = (markerPath) => {
115
+ if (!markerPath)
116
+ return;
117
+ try {
118
+ rmSync(markerPath, { force: true });
119
+ }
120
+ catch {
121
+ // Best-effort cleanup; stale markers have an expiry and are ignored by the hook.
122
+ }
123
+ };
124
+ const configCache = new AgentConfigCache(configPath);
125
+ let initialConfig = null;
12
126
  try {
13
- agentConfig = JSON.parse(readFileSync(configPath, "utf8"));
14
- }
15
- catch {
16
- // Agent config not found — send/inbox/peers tools will be unavailable
127
+ initialConfig = configCache.read();
17
128
  }
129
+ catch { /* Optional until a config-bound tool is used. */ }
18
130
  const store = new SQLiteMessageStore(dbPath);
131
+ const channelRoster = new ChannelRosterStore(channelRosterPath);
19
132
  // Outbox store — shared with daemon, only created if agent config exists
20
133
  let outbox = null;
21
- if (agentConfig) {
134
+ if (initialConfig) {
22
135
  outbox = new SQLiteDedupeOutboxStore(dbPath);
23
136
  }
24
- // --- Stable envelope payload for signing ---
25
- const stableEnvelopePayload = (envelope) => {
26
- return JSON.stringify({
27
- schemaVersion: envelope.schemaVersion,
28
- msgId: envelope.msgId,
29
- conversationId: envelope.conversationId,
30
- senderAgentId: envelope.senderAgentId,
31
- recipients: [...envelope.recipients],
32
- createdAt: envelope.createdAt,
33
- payloadCiphertext: envelope.payloadCiphertext,
34
- payloadNonce: envelope.payloadNonce,
137
+ // Lazy read-only NATS tap for wake-accelerated murmur_request. Optional — if NATS is
138
+ // unreachable we degrade gracefully to pure store polling. A failed connect does NOT
139
+ // disable acceleration forever: it's retried after a cooldown so a transient outage at
140
+ // startup doesn't permanently fall back to slow polling (per CODEX-VOLT review).
141
+ const WAKE_BROKER_RETRY_COOLDOWN_MS = 30_000;
142
+ let wakeBroker = null;
143
+ let wakeBrokerConnecting = null;
144
+ let wakeBrokerNextRetry = 0;
145
+ const getWakeBroker = async (agentConfig, now = Date.now) => {
146
+ if (wakeBroker)
147
+ return wakeBroker;
148
+ if (wakeBrokerConnecting)
149
+ return wakeBrokerConnecting;
150
+ if (now() < wakeBrokerNextRetry)
151
+ return null; // in cooldown after a recent failure
152
+ const broker = new NatsBroker({
153
+ url: agentConfig.natsUrl,
154
+ token: agentConfig.natsToken,
155
+ jetstream: false,
156
+ // The tap is optional. Daemon reconnect policy must not make this tool wait
157
+ // forever before it can poll the durable local store.
158
+ waitOnFirstConnect: false,
159
+ maxReconnectAttempts: 0,
160
+ connectMaxAttempts: 1,
161
+ connectTimeoutMs: 2_000,
35
162
  });
163
+ wakeBrokerConnecting = (async () => {
164
+ try {
165
+ await broker.connect();
166
+ wakeBroker = broker;
167
+ }
168
+ catch {
169
+ // graceful degrade — store polling still resolves the reply; retry after cooldown
170
+ wakeBroker = null;
171
+ wakeBrokerNextRetry = now() + WAKE_BROKER_RETRY_COOLDOWN_MS;
172
+ void broker.close().catch(() => { });
173
+ }
174
+ return wakeBroker;
175
+ })();
176
+ try {
177
+ return await wakeBrokerConnecting;
178
+ }
179
+ finally {
180
+ wakeBrokerConnecting = null;
181
+ }
36
182
  };
183
+ // stableEnvelopePayload is the canonical signing form from @murmurv2/core
184
+ // (single source of truth shared by daemon / bridges / runner / demos).
37
185
  // --- JSON-RPC helpers ---
38
186
  const send = (payload) => {
39
187
  process.stdout.write(`${JSON.stringify(payload)}\n`);
@@ -57,9 +205,40 @@ const asMessage = (r) => ({
57
205
  text: r.text,
58
206
  createdAt: r.createdAt,
59
207
  transport: r.transport,
208
+ channelId: r.channelId,
209
+ senderMemberId: r.senderMemberId,
210
+ addresseeMemberId: r.addresseeMemberId,
60
211
  });
212
+ const optionalString = (value) => {
213
+ if (value === undefined || value === null)
214
+ return undefined;
215
+ const result = String(value).trim();
216
+ return result || undefined;
217
+ };
218
+ const resolveRoutingMetadata = (args, config, peer) => {
219
+ const channelId = optionalString(args.channelId) ?? optionalString(peer.channelId);
220
+ const senderMemberId = optionalString(args.senderMemberId) ?? optionalString(config.memberId);
221
+ const addresseeMemberId = optionalString(args.addresseeMemberId) ?? optionalString(peer.memberId);
222
+ if (!channelId && !senderMemberId && !addresseeMemberId)
223
+ return {};
224
+ if (!channelId || !senderMemberId) {
225
+ throw new Error("channelId and senderMemberId are required together for structured routing");
226
+ }
227
+ return { channelId, senderMemberId, addresseeMemberId };
228
+ };
61
229
  // --- Tool handlers ---
230
+ const CONFIG_TOOLS = new Set(["murmur_send", "murmur_request", "murmur_inbox", "murmur_peers",
231
+ "channel_presence_heartbeat", "channel_presence_leave"]);
62
232
  const handleTool = async (name, args) => {
233
+ const startedAt = Date.now();
234
+ // Capture one immutable snapshot for this call. Another concurrent request may
235
+ // refresh the peer list without changing the keys/routing of this in-flight call.
236
+ let agentConfig = CONFIG_TOOLS.has(name) ? configCache.read() : null;
237
+ if (agentConfig && (name === "murmur_send" || name === "murmur_request")
238
+ && !Object.hasOwn(agentConfig.peers, String(args.to ?? "").trim()))
239
+ agentConfig = configCache.read(true);
240
+ if (agentConfig && !outbox)
241
+ outbox = new SQLiteDedupeOutboxStore(dbPath);
63
242
  // === Original tools ===
64
243
  if (name === "send_message") {
65
244
  const text = String(args.text ?? "").trim();
@@ -92,6 +271,88 @@ const handleTool = async (name, args) => {
92
271
  const messages = await store.searchMessages(query, Number.isFinite(limit) ? limit : 50);
93
272
  return { messages: messages.map(asMessage) };
94
273
  }
274
+ if (name === "channel_create") {
275
+ const channelId = String(args.channelId ?? "").trim();
276
+ if (!channelId)
277
+ throw new Error("channelId is required");
278
+ const conversationId = String(args.conversationId ?? "").trim();
279
+ if (!conversationId)
280
+ throw new Error("conversationId is required");
281
+ const type = String(args.type ?? "").trim();
282
+ if (!["dm", "group", "consult"].includes(type))
283
+ throw new Error("type must be one of: dm, group, consult");
284
+ const members = Array.isArray(args.members) ? args.members : [];
285
+ const channel = channelRoster.createChannel({
286
+ channelId,
287
+ conversationId,
288
+ type: type,
289
+ metadata: typeof args.metadata === "object" && args.metadata && !Array.isArray(args.metadata) ? args.metadata : undefined,
290
+ members: members.map((member) => ({
291
+ memberId: String(member.memberId ?? "").trim(),
292
+ memberSlot: member.memberSlot === undefined ? undefined : String(member.memberSlot),
293
+ agentId: String(member.agentId ?? "").trim(),
294
+ role: member.role === undefined ? undefined : String(member.role),
295
+ personaId: member.personaId === undefined ? undefined : String(member.personaId),
296
+ model: member.model === undefined ? undefined : String(member.model),
297
+ baseInstructionsHash: member.baseInstructionsHash === undefined ? undefined : String(member.baseInstructionsHash),
298
+ eligibility: typeof member.eligibility === "object" && member.eligibility && !Array.isArray(member.eligibility) ? member.eligibility : undefined,
299
+ metadata: typeof member.metadata === "object" && member.metadata && !Array.isArray(member.metadata) ? member.metadata : undefined,
300
+ })),
301
+ });
302
+ return { channel, members: channelRoster.listChannelMembers(channelId) };
303
+ }
304
+ if (name === "channel_list") {
305
+ const conversationId = String(args.conversationId ?? "").trim();
306
+ if (!conversationId)
307
+ throw new Error("conversationId is required");
308
+ return { channels: channelRoster.listChannelsForConversation(conversationId) };
309
+ }
310
+ if (name === "channel_members") {
311
+ const channelId = String(args.channelId ?? "").trim();
312
+ if (!channelId)
313
+ throw new Error("channelId is required");
314
+ return { members: channelRoster.listChannelMembers(channelId) };
315
+ }
316
+ if (name === "channel_presence") {
317
+ const channelId = String(args.channelId ?? "").trim();
318
+ if (!channelId)
319
+ throw new Error("channelId is required");
320
+ return { scope: "local", sessions: channelRoster.listChannelPresence(channelId) };
321
+ }
322
+ if (name === "channel_presence_heartbeat" || name === "channel_presence_leave") {
323
+ if (!agentConfig)
324
+ throw new Error("agent config not loaded — presence requires a local agent identity");
325
+ if (args.agentId !== undefined || args.sessionId !== undefined)
326
+ throw new Error("presence identity is bound to this MCP server");
327
+ const identity = {
328
+ channelId: String(args.channelId ?? "").trim(),
329
+ memberId: String(args.memberId ?? agentConfig.memberId ?? "").trim(),
330
+ agentId: agentConfig.agentId,
331
+ sessionId: presenceSessionId,
332
+ };
333
+ if (name === "channel_presence_leave")
334
+ return { left: channelRoster.leaveChannelSession(identity) };
335
+ return { scope: "local", presence: channelRoster.heartbeatChannelSession({
336
+ ...identity,
337
+ status: args.status,
338
+ ttlMs: args.ttlMs,
339
+ }) };
340
+ }
341
+ if (name === "channel_evaluate_addressing") {
342
+ const selfAgentId = String(args.selfAgentId ?? "").trim();
343
+ if (!selfAgentId)
344
+ throw new Error("selfAgentId is required");
345
+ return {
346
+ decision: channelRoster.evaluateAddressing({
347
+ channelId: args.channelId === undefined ? undefined : String(args.channelId),
348
+ selfAgentId,
349
+ senderAgentId: args.senderAgentId === undefined ? undefined : String(args.senderAgentId),
350
+ senderMemberId: args.senderMemberId === undefined ? undefined : String(args.senderMemberId),
351
+ addresseeMemberId: args.addresseeMemberId === undefined ? undefined : String(args.addresseeMemberId),
352
+ addresseeAgentId: args.addresseeAgentId === undefined ? undefined : String(args.addresseeAgentId),
353
+ }),
354
+ };
355
+ }
95
356
  // === New agent-to-agent tools (require agent config) ===
96
357
  if (name === "murmur_send") {
97
358
  if (!agentConfig || !outbox)
@@ -102,11 +363,16 @@ const handleTool = async (name, args) => {
102
363
  const text = String(args.text ?? "").trim();
103
364
  if (!text)
104
365
  throw new Error("'text' is required");
105
- const peer = agentConfig.peers[to];
366
+ const peer = Object.hasOwn(agentConfig.peers, to) ? agentConfig.peers[to] : undefined;
106
367
  if (!peer)
107
368
  throw new Error(`unknown peer: ${to} — add to peers in agent-config.json`);
108
- const conversationId = String(args.conversationId ?? `dm:${agentConfig.agentId}:${to}`);
369
+ const conversationId = String(args.conversationId ?? defaultPeerConversationId({
370
+ to,
371
+ agentId: agentConfig.agentId,
372
+ codexThreadId: process.env.CODEX_THREAD_ID,
373
+ }));
109
374
  const msgId = randomUUID();
375
+ const routing = resolveRoutingMetadata(args, agentConfig, peer);
110
376
  // Encrypt
111
377
  const encrypted = await encryptPayload(text, peer.encryption.publicKey, agentConfig.keys.encryption.privateKey);
112
378
  // Build envelope
@@ -120,11 +386,13 @@ const handleTool = async (name, args) => {
120
386
  payloadCiphertext: encrypted.ciphertext,
121
387
  payloadNonce: encrypted.nonce,
122
388
  signature: "",
389
+ ...routing,
123
390
  };
124
391
  // Sign
125
392
  envelope.signature = await signEnvelope(stableEnvelopePayload(envelope), agentConfig.keys.signing.privateKey);
126
393
  // Enqueue to outbox — daemon will flush to NATS
127
- await outbox.enqueue(peer.subject, envelope);
394
+ await outbox.enqueue(resolveMessageSubject(peer, routing.channelId), envelope);
395
+ recordCodexTaskPeerBinding(conversationId, to);
128
396
  // Store outbound copy in message store
129
397
  await store.append({
130
398
  conversationId,
@@ -134,20 +402,21 @@ const handleTool = async (name, args) => {
134
402
  text,
135
403
  createdAt: envelope.createdAt,
136
404
  transport: "nats",
405
+ ...routing,
137
406
  });
138
- return { msgId, to, conversationId, status: "queued" };
407
+ return { msgId, to, conversationId, status: "queued", ...routing };
139
408
  }
140
409
  if (name === "murmur_inbox") {
141
410
  if (!agentConfig)
142
411
  throw new Error("agent config not loaded — run agent-config-init.mjs first");
143
412
  const limit = Number(args.limit ?? 20);
144
413
  const effectiveLimit = Number.isFinite(limit) ? limit : 20;
145
- // Search inbound messages for this agent
146
- const messages = await store.searchMessages(agentConfig.agentId, effectiveLimit * 5);
147
- // Filter to only inbound messages
148
- const inbound = messages
149
- .filter((m) => m.direction === "inbound")
150
- .slice(0, effectiveLimit);
414
+ // Select by direction, not by a text search for the agent's own name: this store
415
+ // belongs to one agent, so every inbound row in it is addressed to that agent.
416
+ // The old searchMessages(agentId) form was a LIKE over text/sender/conversationId
417
+ // and silently returned count:0 for any message that did not spell out the agent's
418
+ // name — delivered, acked, present in local_messages, invisible to the inbox (#114).
419
+ const inbound = await store.listInbound(effectiveLimit);
151
420
  return { messages: inbound.map(asMessage), count: inbound.length };
152
421
  }
153
422
  if (name === "murmur_request") {
@@ -159,14 +428,18 @@ const handleTool = async (name, args) => {
159
428
  const text = String(args.text ?? "").trim();
160
429
  if (!text)
161
430
  throw new Error("'text' is required");
162
- const peer = agentConfig.peers[to];
431
+ const peer = Object.hasOwn(agentConfig.peers, to) ? agentConfig.peers[to] : undefined;
163
432
  if (!peer)
164
433
  throw new Error(`unknown peer: ${to} — add to peers in agent-config.json`);
165
- const timeoutMs = Number(args.timeout_ms ?? 300_000);
166
- const pollMs = Number(args.poll_interval_ms ?? 10_000);
167
- const conversationId = String(args.conversationId ?? `dm:${agentConfig.agentId}:${to}`);
434
+ const { requestedTimeoutMs, timeoutMs, pollMs, graceMs } = requestTiming(args);
435
+ const conversationId = String(args.conversationId ?? defaultPeerConversationId({
436
+ to,
437
+ agentId: agentConfig.agentId,
438
+ codexThreadId: process.env.CODEX_THREAD_ID,
439
+ }));
168
440
  const msgId = randomUUID();
169
441
  const sentAt = new Date().toISOString();
442
+ const routing = resolveRoutingMetadata(args, agentConfig, peer);
170
443
  // Encrypt
171
444
  const encrypted = await encryptPayload(text, peer.encryption.publicKey, agentConfig.keys.encryption.privateKey);
172
445
  // Build envelope
@@ -180,48 +453,105 @@ const handleTool = async (name, args) => {
180
453
  payloadCiphertext: encrypted.ciphertext,
181
454
  payloadNonce: encrypted.nonce,
182
455
  signature: "",
456
+ ...routing,
183
457
  };
184
458
  // Sign
185
459
  envelope.signature = await signEnvelope(stableEnvelopePayload(envelope), agentConfig.keys.signing.privateKey);
186
460
  // Enqueue to outbox
187
- await outbox.enqueue(peer.subject, envelope);
461
+ const suppressionMarker = armSynchronousReplySuppression(conversationId, to, timeoutMs);
462
+ try {
463
+ await outbox.enqueue(resolveMessageSubject(peer, routing.channelId), envelope);
464
+ recordCodexTaskPeerBinding(conversationId, to);
465
+ }
466
+ catch (error) {
467
+ clearSynchronousReplySuppression(suppressionMarker);
468
+ throw error;
469
+ }
188
470
  // Store outbound copy
189
- await store.append({
190
- conversationId,
191
- msgId,
192
- direction: "outbound",
193
- sender: agentConfig.agentId,
194
- text,
195
- createdAt: sentAt,
196
- transport: "nats",
197
- });
198
- // Poll for response
199
- const deadline = Date.now() + timeoutMs;
471
+ try {
472
+ await store.append({
473
+ conversationId,
474
+ msgId,
475
+ direction: "outbound",
476
+ sender: agentConfig.agentId,
477
+ text,
478
+ createdAt: sentAt,
479
+ transport: "nats",
480
+ ...routing,
481
+ });
482
+ }
483
+ catch (error) {
484
+ clearSynchronousReplySuppression(suppressionMarker);
485
+ throw error;
486
+ }
487
+ // Wait for the reply. Store polling is the durable fallback and always runs;
488
+ // an optional read-only NATS tap on our own subject accelerates the wait by
489
+ // re-checking the store as soon as a matching envelope is observed. The tap is
490
+ // signal-only — the daemon stays the source of truth for decrypt + persistence.
491
+ const deadline = startedAt + timeoutMs;
492
+ const matchReply = buildReplyMatcher(conversationId, to, routing.addresseeMemberId);
493
+ const snapshot = agentConfig;
494
+ const subjects = [snapshot.subject];
495
+ if (snapshot.subjectScoping?.enabled === true && routing.channelId)
496
+ subjects.push(channelScopedSubject(snapshot.subject, routing.channelId));
497
+ const tap = {};
498
+ let wokenBySignal = false;
499
+ const onSignal = (wake) => {
500
+ tap.current = createReplySignalTap(() => getWakeBroker(snapshot), subjects, env => {
501
+ if (matchReply(env)) {
502
+ wokenBySignal = true;
503
+ wake();
504
+ }
505
+ });
506
+ };
200
507
  let reply = null;
201
- while (Date.now() < deadline) {
202
- const inbound = await store.getInboundAfter(conversationId, sentAt, 1);
203
- if (inbound.length > 0) {
204
- reply = inbound[0];
205
- break;
206
- }
207
- await new Promise((r) => setTimeout(r, pollMs));
508
+ try {
509
+ reply = await waitForReply({
510
+ checkStore: async () => {
511
+ const inbound = await store.getInboundAfter(conversationId, sentAt, 100);
512
+ return inbound.find((row) => row.sender === to &&
513
+ (!routing.addresseeMemberId || row.senderMemberId === routing.addresseeMemberId)) ?? null;
514
+ },
515
+ pollMs,
516
+ graceMs,
517
+ deadline,
518
+ onSignal,
519
+ });
520
+ }
521
+ catch (error) {
522
+ clearSynchronousReplySuppression(suppressionMarker);
523
+ throw error;
524
+ }
525
+ finally {
526
+ tap.current?.close();
208
527
  }
209
528
  if (reply) {
529
+ shortenSynchronousReplySuppression(suppressionMarker);
210
530
  return {
211
531
  status: "received",
212
532
  msgId,
213
533
  conversationId,
214
534
  sentAt,
535
+ ...routing,
215
536
  reply: asMessage(reply),
537
+ // Precise telemetry (per CODEX-VOLT review): tapAttached = the read-only NATS
538
+ // tap was live for this wait; wokenBySignal = a matching envelope actually
539
+ // short-circuited the poll (true acceleration, not merely "broker available").
540
+ tapAttached: tap.current?.hasAttached() ?? false,
541
+ wokenBySignal,
216
542
  };
217
543
  }
544
+ clearSynchronousReplySuppression(suppressionMarker);
218
545
  return {
219
- status: "timeout",
546
+ status: "awaiting_reply",
220
547
  msgId,
221
548
  conversationId,
222
549
  sentAt,
550
+ ...routing,
223
551
  timeout_ms: timeoutMs,
224
- hint: "Use murmur_inbox to check for late responses",
552
+ requested_timeout_ms: requestedTimeoutMs,
553
+ delivery: requestDelivery((await outbox.getOutboxRecord(msgId))?.status),
554
+ hint: "No reply yet. Use murmur_inbox and match conversationId to read a later reply; do not resend this request.",
225
555
  };
226
556
  }
227
557
  if (name === "murmur_peers") {
@@ -230,6 +560,8 @@ const handleTool = async (name, args) => {
230
560
  const peerList = Object.entries(agentConfig.peers).map(([id, p]) => ({
231
561
  agentId: id,
232
562
  subject: p.subject,
563
+ channelId: p.channelId,
564
+ memberId: p.memberId,
233
565
  hasEncryptionKey: !!p.encryption?.publicKey,
234
566
  hasSigningKey: !!p.signing?.publicKey,
235
567
  }));
@@ -275,6 +607,104 @@ const tools = [
275
607
  required: ["query"],
276
608
  },
277
609
  },
610
+ {
611
+ name: "channel_create",
612
+ description: "Create a typed Murmur channel roster entry with optional members.",
613
+ inputSchema: {
614
+ type: "object",
615
+ properties: {
616
+ channelId: { type: "string", description: "Stable channel/routing ID, distinct from conversationId" },
617
+ conversationId: { type: "string", description: "Legacy history label associated with the channel" },
618
+ type: { type: "string", enum: ["dm", "group", "consult"] },
619
+ metadata: { type: "object" },
620
+ members: {
621
+ type: "array",
622
+ items: {
623
+ type: "object",
624
+ properties: {
625
+ memberId: { type: "string" },
626
+ memberSlot: { type: "string" },
627
+ agentId: { type: "string" },
628
+ role: { type: "string" },
629
+ personaId: { type: "string" },
630
+ model: { type: "string" },
631
+ baseInstructionsHash: { type: "string" },
632
+ eligibility: { type: "object" },
633
+ metadata: { type: "object" },
634
+ },
635
+ required: ["memberId", "agentId"],
636
+ },
637
+ },
638
+ },
639
+ required: ["channelId", "conversationId", "type"],
640
+ },
641
+ },
642
+ {
643
+ name: "channel_list",
644
+ description: "List typed channels associated with a legacy conversationId.",
645
+ inputSchema: {
646
+ type: "object",
647
+ properties: {
648
+ conversationId: { type: "string" },
649
+ },
650
+ required: ["conversationId"],
651
+ },
652
+ },
653
+ {
654
+ name: "channel_members",
655
+ description: "List active and historical members for a typed channel.",
656
+ inputSchema: {
657
+ type: "object",
658
+ properties: {
659
+ channelId: { type: "string" },
660
+ },
661
+ required: ["channelId"],
662
+ },
663
+ },
664
+ {
665
+ name: "channel_evaluate_addressing",
666
+ description: "Evaluate channel membership/addressing into reject/append/wake decisions.",
667
+ inputSchema: {
668
+ type: "object",
669
+ properties: {
670
+ channelId: { type: "string" },
671
+ selfAgentId: { type: "string" },
672
+ senderAgentId: { type: "string" },
673
+ senderMemberId: { type: "string" },
674
+ addresseeMemberId: { type: "string" },
675
+ addresseeAgentId: { type: "string" },
676
+ },
677
+ required: ["selfAgentId"],
678
+ },
679
+ },
680
+ {
681
+ name: "channel_presence",
682
+ description: "List unexpired local chat-session presence for a channel. Advisory only; not peer liveness or lease ownership.",
683
+ inputSchema: {
684
+ type: "object", properties: { channelId: { type: "string" } }, required: ["channelId"],
685
+ },
686
+ },
687
+ {
688
+ name: "channel_presence_heartbeat",
689
+ description: "Report this local chat session in an existing channel. Repeat before TTL expires; does not claim a lease or grant membership.",
690
+ inputSchema: {
691
+ type: "object", additionalProperties: false,
692
+ properties: {
693
+ channelId: { type: "string" },
694
+ memberId: { type: "string", description: "Existing local agent member; defaults to configured memberId" },
695
+ status: { type: "string", enum: ["active", "idle", "busy"] },
696
+ ttlMs: { type: "integer", minimum: 5000, maximum: 300000, default: 30000 },
697
+ }, required: ["channelId"],
698
+ },
699
+ },
700
+ {
701
+ name: "channel_presence_leave",
702
+ description: "Remove this local chat session from the channel presence list without changing roster membership or leases.",
703
+ inputSchema: {
704
+ type: "object", additionalProperties: false,
705
+ properties: { channelId: { type: "string" }, memberId: { type: "string" } }, required: ["channelId"],
706
+ },
707
+ },
278
708
  {
279
709
  name: "murmur_send",
280
710
  description: "Send an encrypted, signed message to another agent via NATS. Message is queued in outbox and delivered by murmur-daemon.",
@@ -283,22 +713,29 @@ const tools = [
283
713
  properties: {
284
714
  to: { type: "string", description: "Recipient agent ID (must be in peers config)" },
285
715
  text: { type: "string", description: "Message text (will be encrypted)" },
286
- conversationId: { type: "string", description: "Optional conversation ID" },
716
+ conversationId: { type: "string", description: "Optional conversation ID. In Codex Desktop, omission automatically binds replies to the current task." },
717
+ channelId: { type: "string", description: "Optional typed-channel ID; may default from peer config" },
718
+ senderMemberId: { type: "string", description: "Optional sender member identity; may default from local config" },
719
+ addresseeMemberId: { type: "string", description: "Optional target member identity; may default from peer config" },
287
720
  },
288
721
  required: ["to", "text"],
289
722
  },
290
723
  },
291
724
  {
292
725
  name: "murmur_request",
293
- description: "Send a message and wait for the reply. Combines murmur_send + automatic polling — the tool blocks until the peer responds or timeout is reached. Ideal for autonomous agent-to-agent conversations.",
726
+ description: "Send a message and wait up to 45 seconds for the reply, using the durable local store and an optional NATS tap. A slower reply returns a normal awaiting_reply result with delivery status and conversationId. Read later replies with murmur_inbox; do not resend. Delivery is confirmed only by an ACK, and does not prove automatic agent wake.",
294
727
  inputSchema: {
295
728
  type: "object",
296
729
  properties: {
297
730
  to: { type: "string", description: "Recipient agent ID (must be in peers config)" },
298
731
  text: { type: "string", description: "Message text (will be encrypted)" },
299
- conversationId: { type: "string", description: "Optional conversation ID" },
300
- timeout_ms: { type: "number", description: "Max wait time in ms (default: 300000 = 5 min)" },
301
- poll_interval_ms: { type: "number", description: "Poll interval in ms (default: 10000 = 10s)" },
732
+ conversationId: { type: "string", description: "Optional conversation ID. In Codex Desktop, omission automatically binds replies to the current task." },
733
+ channelId: { type: "string", description: "Optional typed-channel ID; may default from peer config" },
734
+ senderMemberId: { type: "string", description: "Optional sender member identity; may default from local config" },
735
+ addresseeMemberId: { type: "string", description: "Optional target member identity; may default from peer config" },
736
+ timeout_ms: { type: "number", description: "Max wait time in ms (default and cap: 45000); larger values are capped to fit desktop host tool limits" },
737
+ poll_interval_ms: { type: "number", description: "Store-poll fallback interval in ms (default: 10000 = 10s)" },
738
+ grace_ms: { type: "number", description: "Delay after a wake signal before re-checking the store, to let the daemon persist (default: 250)" },
302
739
  },
303
740
  required: ["to", "text"],
304
741
  },
@@ -0,0 +1,72 @@
1
+ import type { EnvelopeV1, LocalMessageRecord, OutboxStatus } from "@murmurv2/core";
2
+ export declare const MAX_REQUEST_WAIT_MS = 45000;
3
+ export declare function requestTiming(args: Record<string, unknown>): {
4
+ requestedTimeoutMs: number;
5
+ timeoutMs: number;
6
+ pollMs: number;
7
+ graceMs: number;
8
+ };
9
+ export declare function requestDelivery(status: OutboxStatus | undefined): {
10
+ status: string;
11
+ acknowledged: boolean;
12
+ outboxStatus: string;
13
+ };
14
+ interface SignalSubscription {
15
+ unsubscribe(): void | Promise<void>;
16
+ }
17
+ interface SignalBroker {
18
+ subscribeRaw(subject: string, onEnvelope: (envelope: EnvelopeV1) => void): Promise<SignalSubscription>;
19
+ }
20
+ /** Optional acceleration never blocks store polling or completion, even while
21
+ * connecting. A subscription that attaches after close is immediately released. */
22
+ export declare function createReplySignalTap(connect: () => Promise<SignalBroker | null>, subjects: string[], onEnvelope: (envelope: EnvelopeV1) => void): {
23
+ hasAttached: () => boolean;
24
+ close: () => void;
25
+ };
26
+ /**
27
+ * Pure wait-loop for the request/reply ("native-request-reply") flow.
28
+ *
29
+ * Design B (locked with CODEX-VOLT):
30
+ * - The outbox stays the source of truth: sending happens elsewhere, this only WAITS.
31
+ * - Store polling is the durable fallback and ALWAYS runs, so a reply is found even
32
+ * when no live wake signal is available (NATS down / `onSignal` omitted).
33
+ * - An optional `onSignal` source (a read-only NATS tap on the agent's own subject)
34
+ * accelerates the wait: when a matching envelope arrives we re-check the store
35
+ * immediately instead of waiting out the poll interval. The signal NEVER carries
36
+ * the reply itself — decryption + persistence stay the daemon's job — it only nudges
37
+ * us to re-poll the store the daemon writes into.
38
+ *
39
+ * Lost-wakeup safety: the wake promise is armed BEFORE each store check, so a signal
40
+ * that fires between the check and the race still short-circuits the wait.
41
+ */
42
+ export interface ReplyWaiterDeps {
43
+ /** Return the reply record if one has arrived, else null. */
44
+ checkStore: () => Promise<LocalMessageRecord | null>;
45
+ /** Poll interval in ms (fallback cadence when no signal fires). */
46
+ pollMs: number;
47
+ /** Grace delay in ms after a signal, to let the daemon persist before re-checking. */
48
+ graceMs: number;
49
+ /** Absolute deadline as epoch ms (Date.now()-style). */
50
+ deadline: number;
51
+ /**
52
+ * Optional wake-signal registration. Called once with a callback; invoke the
53
+ * callback whenever a relevant inbound envelope is observed. Omit for pure-poll.
54
+ */
55
+ onSignal?: (wake: () => void) => void;
56
+ /** Injectable clock (tests). Defaults to Date.now. */
57
+ now?: () => number;
58
+ /** Injectable sleep (tests). Defaults to setTimeout. */
59
+ sleep?: (ms: number) => Promise<void>;
60
+ }
61
+ export declare function waitForReply(deps: ReplyWaiterDeps): Promise<LocalMessageRecord | null>;
62
+ /**
63
+ * Build a predicate that matches an inbound envelope as the awaited reply:
64
+ * same conversation AND sent by the peer we are waiting on. Envelope metadata is
65
+ * plaintext (conversationId / senderAgentId), so this needs no decryption.
66
+ */
67
+ export declare const buildReplyMatcher: (conversationId: string, fromAgentId: string, fromMemberId?: string) => (envelope: {
68
+ conversationId: string;
69
+ senderAgentId: string;
70
+ senderMemberId?: string;
71
+ }) => boolean;
72
+ export {};
@@ -0,0 +1,93 @@
1
+ // Leave room below desktop hosts' common 60-second tool limit. A larger caller
2
+ // timeout must not turn a healthy but slower peer into a host-level tool error.
3
+ export const MAX_REQUEST_WAIT_MS = 45_000;
4
+ export function requestTiming(args) {
5
+ const number = (key, fallback, minimum) => {
6
+ const value = args[key] ?? fallback;
7
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
8
+ throw new Error(`${key} must be an integer >= ${minimum}`);
9
+ }
10
+ return value;
11
+ };
12
+ const requestedTimeoutMs = number("timeout_ms", MAX_REQUEST_WAIT_MS, 1);
13
+ const timeoutMs = Math.min(requestedTimeoutMs, MAX_REQUEST_WAIT_MS);
14
+ return { requestedTimeoutMs, timeoutMs,
15
+ pollMs: Math.min(number("poll_interval_ms", 10_000, 1), timeoutMs),
16
+ graceMs: Math.min(number("grace_ms", 250, 0), timeoutMs) };
17
+ }
18
+ export function requestDelivery(status) {
19
+ return { status: status === "acked" ? "delivered" : status === "dlq" ? "failed" : status ? "pending" : "unknown",
20
+ acknowledged: status === "acked", outboxStatus: status ?? "unknown" };
21
+ }
22
+ /** Optional acceleration never blocks store polling or completion, even while
23
+ * connecting. A subscription that attaches after close is immediately released. */
24
+ export function createReplySignalTap(connect, subjects, onEnvelope) {
25
+ let closed = false, attached = false;
26
+ const subscriptions = [];
27
+ const release = (sub) => {
28
+ try {
29
+ void Promise.resolve(sub.unsubscribe()).catch(() => { });
30
+ }
31
+ catch { /* optional tap */ }
32
+ };
33
+ void Promise.resolve().then(connect).then(async (broker) => {
34
+ if (!broker || closed)
35
+ return;
36
+ await Promise.all(subjects.map(async (subject) => {
37
+ try {
38
+ const sub = await broker.subscribeRaw(subject, envelope => { if (!closed)
39
+ onEnvelope(envelope); });
40
+ if (closed)
41
+ release(sub);
42
+ else {
43
+ attached = true;
44
+ subscriptions.push(sub);
45
+ }
46
+ }
47
+ catch { /* Store polling remains the durable fallback. */ }
48
+ }));
49
+ }).catch(() => { });
50
+ return { hasAttached: () => attached, close: () => { closed = true; subscriptions.splice(0).forEach(release); } };
51
+ }
52
+ export async function waitForReply(deps) {
53
+ const now = deps.now ?? (() => Date.now());
54
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
55
+ let signaled = false;
56
+ let wakeResolve = null;
57
+ if (deps.onSignal) {
58
+ deps.onSignal(() => {
59
+ signaled = true;
60
+ wakeResolve?.();
61
+ });
62
+ }
63
+ while (now() < deps.deadline) {
64
+ // Arm the wake BEFORE checking the store to avoid a lost wakeup: a signal that
65
+ // fires while checkStore() is in flight still resolves this promise.
66
+ signaled = false;
67
+ const wake = new Promise((resolve) => {
68
+ wakeResolve = resolve;
69
+ });
70
+ const found = await deps.checkStore();
71
+ if (found)
72
+ return found;
73
+ const remaining = deps.deadline - now();
74
+ if (remaining <= 0)
75
+ break;
76
+ const waitMs = Math.min(deps.pollMs, remaining);
77
+ await Promise.race([wake, sleep(waitMs)]);
78
+ if (signaled) {
79
+ const graceRemaining = deps.deadline - now();
80
+ if (graceRemaining > 0)
81
+ await sleep(Math.min(deps.graceMs, graceRemaining));
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+ /**
87
+ * Build a predicate that matches an inbound envelope as the awaited reply:
88
+ * same conversation AND sent by the peer we are waiting on. Envelope metadata is
89
+ * plaintext (conversationId / senderAgentId), so this needs no decryption.
90
+ */
91
+ export const buildReplyMatcher = (conversationId, fromAgentId, fromMemberId) => (envelope) => envelope.conversationId === conversationId &&
92
+ envelope.senderAgentId === fromAgentId &&
93
+ (!fromMemberId || envelope.senderMemberId === fromMemberId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murmurv2/mcp-server",
3
- "version": "0.1.0",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "main": "dist/src/index.js",
6
6
  "types": "dist/src/index.d.ts",
@@ -9,13 +9,14 @@
9
9
  "prepack": "npm run build"
10
10
  },
11
11
  "dependencies": {
12
- "@murmurv2/core": "^0.1.0",
13
- "@murmurv2/security": "^0.1.0"
12
+ "@murmurv2/broker-nats": "^0.3.4",
13
+ "@murmurv2/core": "^0.6.3",
14
+ "@murmurv2/security": "^0.1.1"
14
15
  },
15
16
  "license": "MIT",
16
17
  "repository": {
17
18
  "type": "git",
18
- "url": "git+https://github.com/alexfrmn/mur-mur-v2.git",
19
+ "url": "git+https://github.com/alexfrmn/murmur.git",
19
20
  "directory": "packages/mcp-server"
20
21
  },
21
22
  "publishConfig": {
@@ -25,5 +26,25 @@
25
26
  "dist/src",
26
27
  "LICENSE"
27
28
  ],
28
- "description": "Murmur V2 MCP server — 7 tools for agent-to-agent messaging over the Model Context Protocol."
29
+ "description": "Murmur V2 MCP server — agent-to-agent messaging and scoped-channel roster tools over the Model Context Protocol.",
30
+ "homepage": "https://murmurconnect.com",
31
+ "bugs": {
32
+ "url": "https://github.com/alexfrmn/murmur/issues"
33
+ },
34
+ "keywords": [
35
+ "murmur",
36
+ "agent-communication",
37
+ "agent-to-agent",
38
+ "a2a",
39
+ "agent-bus",
40
+ "message-bus",
41
+ "ai-agents",
42
+ "multi-agent",
43
+ "mcp",
44
+ "model-context-protocol",
45
+ "claude-code",
46
+ "codex",
47
+ "mcp-server",
48
+ "tools"
49
+ ]
29
50
  }