@agentmesh-md/mcp-server 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/dist/tools.js ADDED
@@ -0,0 +1,528 @@
1
+ /**
2
+ * The 9 AgentMesh MCP tools: argument mapping to `/api/v1` + response
3
+ * shaping into MCP `CallToolResult`s.
4
+ *
5
+ * PLAN §2 "Tool -> /api/v1 contract map" (method/path/scope per tool) and
6
+ * §3 "Typed MCP contracts": on success, the upstream object is returned in
7
+ * BOTH `structuredContent` (validated against the tool's outputSchema via
8
+ * schemas.ts) and as serialized JSON in a text content block. On failure,
9
+ * `isError:true` with a single text block `"<CODE>: <message>"` (§6). This
10
+ * module never fabricates a passing validation for data that doesn't
11
+ * conform, and returns a success for a non-2xx upstream response in exactly
12
+ * ONE carved-out case (Phase-1 Seam A, accepted plan 1b562f4 §1 Seam A +
13
+ * control V5): a `claim_card` 409 ALREADY_CLAIMED whose echoed claimant IS
14
+ * this request's own verified identity (`GET /me`) is converted to a no-op
15
+ * success — and only after a live `GET /board` readback re-proves the row is
16
+ * still `claimed` by this identity and supplies the ACTUAL row for the
17
+ * result (typed echo of real state, never a fabricated body). Every other
18
+ * non-2xx, including ALREADY_CLAIMED for a different identity and every
19
+ * CARD_STATE_CONFLICT, stays a typed tool error.
20
+ *
21
+ * B1 (build-QA): every surfaced tool-error text is passed through redact() as
22
+ * a final scrub, so an upstream/undici message that echoes the credential can
23
+ * never reach the tool result. B2 (build-QA): each run() receives the MCP
24
+ * request's AbortSignal (server.ts threads extra.signal) and forwards it to
25
+ * callApi, so an MCP client cancellation aborts the in-flight upstream request
26
+ * immediately -- no lingering socket, no retry attempt 2.
27
+ *
28
+ * Input handling: fields are read from `args` with simple runtime `typeof`
29
+ * narrowing (server.ts already validated `args` against the tool's inputSchema
30
+ * before dispatch), then forwarded upstream. `create_card` trims `title` per
31
+ * PLAN Appendix A.
32
+ */
33
+ import { callApi } from "./client.js";
34
+ import { HOSTED_TOOL_NAMES, validateOutput } from "./schemas.js";
35
+ import { formatToolErrorText } from "./errors.js";
36
+ import { redact, redactDeep } from "./redact.js";
37
+ // ---- small, defensive arg readers ----
38
+ function stringArg(args, key) {
39
+ const value = args[key];
40
+ return typeof value === "string" ? value : undefined;
41
+ }
42
+ function numberArg(args, key) {
43
+ const value = args[key];
44
+ return typeof value === "number" ? value : undefined;
45
+ }
46
+ // ---- shared result shaping ----
47
+ function errorResult(result) {
48
+ // B1: redact any credential that an upstream/undici/cancel message may carry.
49
+ return {
50
+ isError: true,
51
+ content: [{ type: "text", text: redact(formatToolErrorText(result)) }],
52
+ };
53
+ }
54
+ function formatAjvErrors(errors) {
55
+ if (errors === null || errors === undefined || errors.length === 0) {
56
+ return "no further detail available";
57
+ }
58
+ return errors.map((e) => `${e.instancePath.length > 0 ? e.instancePath : "<root>"} ${e.message ?? "is invalid"}`).join("; ");
59
+ }
60
+ function successResult(name, data) {
61
+ // RULE-10 applies to successful data too: an upstream can echo the presented
62
+ // credential in an otherwise schema-valid 2xx body. Scrub every nested string
63
+ // before validation and before either MCP result representation is created.
64
+ const redactedData = redactDeep(data);
65
+ const validate = validateOutput(name);
66
+ const valid = validate(redactedData);
67
+ if (!valid) {
68
+ // The upstream call succeeded (2xx), but the response body does not conform
69
+ // to the outputSchema we publish. Report plainly (redacted for safety).
70
+ return {
71
+ isError: true,
72
+ content: [
73
+ {
74
+ type: "text",
75
+ text: redact(`INTERNAL: AgentMesh returned data for tool "${name}" that does not match its documented output schema (${formatAjvErrors(validate.errors)}).`),
76
+ },
77
+ ],
78
+ };
79
+ }
80
+ const structuredContent = redactedData;
81
+ return {
82
+ structuredContent,
83
+ content: [{ type: "text", text: JSON.stringify(structuredContent) }],
84
+ };
85
+ }
86
+ function finish(name, result) {
87
+ if (!result.ok) {
88
+ return errorResult(result);
89
+ }
90
+ return successResult(name, result.data);
91
+ }
92
+ // ---- API tools — each forwards the MCP AbortSignal to callApi (B2) ----
93
+ async function readBoard(_args, signal) {
94
+ const result = await callApi({ method: "GET", path: "/board", signal });
95
+ return finish("read_board", result);
96
+ }
97
+ async function readChannels(_args, signal) {
98
+ const result = await callApi({ method: "GET", path: "/channels", signal });
99
+ return finish("read_channels", result);
100
+ }
101
+ async function readMessages(args, signal) {
102
+ const result = await callApi({
103
+ method: "GET",
104
+ path: "/messages",
105
+ query: {
106
+ channel: stringArg(args, "channel"),
107
+ limit: numberArg(args, "limit"),
108
+ before_id: stringArg(args, "before_id"),
109
+ },
110
+ signal,
111
+ });
112
+ return finish("read_messages", result);
113
+ }
114
+ async function listAsks(args, signal) {
115
+ const result = await callApi({
116
+ method: "GET",
117
+ path: "/asks",
118
+ query: { state: stringArg(args, "state") },
119
+ signal,
120
+ });
121
+ return finish("list_asks", result);
122
+ }
123
+ async function getMyInstructions(_args, signal) {
124
+ return finish("get_my_instructions", await callApi({ method: "GET", path: "/me/instructions", signal }));
125
+ }
126
+ async function whoami(_args, signal) {
127
+ const result = await callApi({ method: "GET", path: "/me", signal });
128
+ return finish("whoami", result);
129
+ }
130
+ async function postMessage(args, signal) {
131
+ const result = await callApi({
132
+ method: "POST",
133
+ path: "/messages",
134
+ body: { body_md: stringArg(args, "body_md"), channel: stringArg(args, "channel") },
135
+ idempotencyKey: crypto.randomUUID(),
136
+ signal,
137
+ });
138
+ return finish("post_message", result);
139
+ }
140
+ async function readRoster(_args, signal) {
141
+ const result = await callApi({ method: "GET", path: "/roster", signal });
142
+ return finish("read_roster", result);
143
+ }
144
+ async function listConversations(args, signal) {
145
+ const result = await callApi({
146
+ method: "GET",
147
+ path: "/conversations",
148
+ query: { limit: numberArg(args, "limit"), before_id: stringArg(args, "before_id") },
149
+ signal,
150
+ });
151
+ return finish("list_conversations", result);
152
+ }
153
+ async function createConversation(args, signal) {
154
+ const result = await callApi({
155
+ method: "POST",
156
+ path: "/conversations",
157
+ body: { participants: args["participants"] },
158
+ idempotencyKey: crypto.randomUUID(),
159
+ signal,
160
+ });
161
+ return finish("create_conversation", result);
162
+ }
163
+ async function readConversationMessages(args, signal) {
164
+ const conversationId = stringArg(args, "conversation_id");
165
+ const result = await callApi({
166
+ method: "GET",
167
+ path: `/conversations/${encodeURIComponent(conversationId ?? "")}/messages`,
168
+ query: { limit: numberArg(args, "limit"), before_id: stringArg(args, "before_id") },
169
+ signal,
170
+ });
171
+ return finish("read_conversation_messages", result);
172
+ }
173
+ async function postConversationMessage(args, signal) {
174
+ const conversationId = stringArg(args, "conversation_id");
175
+ const result = await callApi({
176
+ method: "POST",
177
+ path: `/conversations/${encodeURIComponent(conversationId ?? "")}/messages`,
178
+ body: { body_md: stringArg(args, "body_md") },
179
+ idempotencyKey: crypto.randomUUID(),
180
+ signal,
181
+ });
182
+ return finish("post_conversation_message", result);
183
+ }
184
+ /**
185
+ * Resolve THIS invocation's own identity via `GET /me` (the same credential
186
+ * the failed claim used — in http mode the per-request key, in stdio the
187
+ * process key). Returns null on ANY failure or non-conforming body: the
188
+ * caller treats an unprovable identity as "not me" (fail closed — the typed
189
+ * conflict passes through rather than guessing a no-op). Deliberately NOT
190
+ * cached: in http mode the credential varies per request, and this path only
191
+ * runs on an ALREADY_CLAIMED conflict, never on the happy path.
192
+ */
193
+ async function fetchSelfIdentity(signal) {
194
+ const result = await callApi({ method: "GET", path: "/me", signal });
195
+ if (!result.ok || typeof result.data !== "object" || result.data === null) {
196
+ return null;
197
+ }
198
+ const principal = result.data["principal"];
199
+ if (typeof principal !== "object" || principal === null) {
200
+ return null;
201
+ }
202
+ const record = principal;
203
+ const id = record["id"];
204
+ const kind = record["kind"];
205
+ return typeof id === "string" && typeof kind === "string" ? { id, kind } : null;
206
+ }
207
+ /** Parse `{claimed_by, claimed_by_kind}` from ALREADY_CLAIMED's details; null if absent/malformed. */
208
+ function claimantFromDetails(details) {
209
+ if (typeof details !== "object" || details === null) {
210
+ return null;
211
+ }
212
+ const record = details;
213
+ const claimedBy = record["claimed_by"];
214
+ const claimedByKind = record["claimed_by_kind"];
215
+ return typeof claimedBy === "string" && typeof claimedByKind === "string"
216
+ ? { claimedBy, claimedByKind }
217
+ : null;
218
+ }
219
+ /**
220
+ * Read-after-write echo for the no-op branch: fetch the ACTUAL card row via
221
+ * `GET /board` (the only card-reading endpoint) and return it only if it
222
+ * still shows `status='claimed'` by exactly this identity — a defensive
223
+ * re-verification against state drift between the 409 and this read. Returns
224
+ * null when the readback fails (e.g. a cards:claim-only key lacks board:read
225
+ * — 403), the card is absent, or the state drifted; the caller then falls
226
+ * back to the honest typed conflict. The row is echoed as the upstream
227
+ * serialized it — never synthesized — so the normal successResult path
228
+ * validates it against claim_card's outputSchema like any real claim.
229
+ */
230
+ async function fetchClaimedCardEcho(cardId, self, signal) {
231
+ const result = await callApi({ method: "GET", path: "/board", signal });
232
+ if (!result.ok || typeof result.data !== "object" || result.data === null) {
233
+ return null;
234
+ }
235
+ const columns = result.data["columns"];
236
+ if (!Array.isArray(columns)) {
237
+ return null;
238
+ }
239
+ for (const column of columns) {
240
+ if (typeof column !== "object" || column === null) {
241
+ continue;
242
+ }
243
+ const cards = column["cards"];
244
+ if (!Array.isArray(cards)) {
245
+ continue;
246
+ }
247
+ for (const card of cards) {
248
+ if (typeof card !== "object" || card === null) {
249
+ continue;
250
+ }
251
+ const record = card;
252
+ if (record["id"] !== cardId) {
253
+ continue;
254
+ }
255
+ if (record["status"] === "claimed" && record["claimed_by"] === self.id && record["claimed_by_kind"] === self.kind) {
256
+ return record;
257
+ }
258
+ return null; // found, but no longer claimed by this identity — do not echo
259
+ }
260
+ }
261
+ return null;
262
+ }
263
+ /** Typed ALREADY_CLAIMED tool error with the claimant echoed into the surfaced text. */
264
+ function claimConflictResult(result, claimant) {
265
+ if (claimant === null) {
266
+ return errorResult(result);
267
+ }
268
+ // Claimant ids are workspace principal ids (uuid/uid), not credentials; the
269
+ // composed text still passes redact() inside errorResult as a final scrub.
270
+ return errorResult({
271
+ ...result,
272
+ message: `${result.message} (claimed_by=${claimant.claimedBy}, claimed_by_kind=${claimant.claimedByKind})`,
273
+ });
274
+ }
275
+ async function claimCard(args, signal) {
276
+ const cardId = stringArg(args, "card_id");
277
+ if (cardId === undefined) {
278
+ return errorResult({ ok: false, code: "VALIDATION", message: 'missing or invalid required argument "card_id".', status: 0 });
279
+ }
280
+ // CAS claim via the parent API, exactly as before: fresh Idempotency-Key
281
+ // per MCP invocation (c7), same key reused only by client.ts's own
282
+ // transport retry. On success the parent's RETURNING* row comes back and
283
+ // is the typed read-after-write echo.
284
+ const result = await callApi({
285
+ method: "POST",
286
+ path: `/cards/${encodeURIComponent(cardId)}/claim`,
287
+ idempotencyKey: crypto.randomUUID(),
288
+ signal,
289
+ });
290
+ if (result.ok) {
291
+ return successResult("claim_card", result.data);
292
+ }
293
+ if (result.code !== "ALREADY_CLAIMED") {
294
+ // NOT_FOUND, CARD_STATE_CONFLICT (terminal 'done' is unclaimable — the
295
+ // no-op carve-out is claim-state only), scope/auth failures, network:
296
+ // all pass through typed, unchanged.
297
+ return errorResult(result);
298
+ }
299
+ const claimant = claimantFromDetails(result.details);
300
+ if (claimant !== null) {
301
+ const self = await fetchSelfIdentity(signal);
302
+ // V5 RED anchor (do not reformat): the same-identity check below is the
303
+ // mutation target proving the no-op is load-bearing.
304
+ if (self !== null && claimant.claimedBy === self.id && claimant.claimedByKind === self.kind) {
305
+ // Re-claim by the SAME identity => no-op success (NEW Seam-A
306
+ // semantics). The result body is the ACTUAL row from a live readback,
307
+ // never a body assembled from assumptions; if the readback cannot
308
+ // prove the row (no board:read, drift, failure), fall through to the
309
+ // honest typed conflict below.
310
+ const echoed = await fetchClaimedCardEcho(cardId, self, signal);
311
+ if (echoed !== null) {
312
+ return successResult("claim_card", { card: echoed });
313
+ }
314
+ }
315
+ }
316
+ return claimConflictResult(result, claimant);
317
+ }
318
+ async function completeCard(args, signal) {
319
+ const cardId = stringArg(args, "card_id");
320
+ if (cardId === undefined) {
321
+ return errorResult({ ok: false, code: "VALIDATION", message: 'missing or invalid required argument "card_id".', status: 0 });
322
+ }
323
+ // Claimant-only CAS via the parent API, unchanged; `409
324
+ // CARD_STATE_CONFLICT` passes through TYPED for every wrong state.
325
+ //
326
+ // Phase-1 Seam A, deliberate asymmetry with claim_card (FLAGGED, build-plan
327
+ // resolution (c)): a same-identity re-complete no-op is INFEASIBLE without
328
+ // a parent change. Ground truth (src/routes/board.js, complete CAS-miss
329
+ // branch): the conflict payload is `{ status: cur.status }` ONLY — it does
330
+ // NOT echo the claimant, so "this card is done AND this identity completed
331
+ // it" cannot be proven from the payload; a card completed by X and
332
+ // re-completed by Y yields byte-identical conflicts. Honesty over reach:
333
+ // the strict typed passthrough stays until the parent ever echoes the
334
+ // claimant here. (Effect-idempotence still holds: a re-complete mutates
335
+ // nothing — the CAS-miss branch is read-only.)
336
+ const result = await callApi({
337
+ method: "POST",
338
+ path: `/cards/${encodeURIComponent(cardId)}/complete`,
339
+ idempotencyKey: crypto.randomUUID(),
340
+ signal,
341
+ });
342
+ return finish("complete_card", result);
343
+ }
344
+ async function createCard(args, signal) {
345
+ // Phase-1 Seam A (build-plan resolution (c), unchanged behavior, pinned by
346
+ // control V5): ONE fresh Idempotency-Key per MCP invocation (c7 discipline);
347
+ // a transport-level retry inside client.ts replays the SAME key, so the
348
+ // parent byte-replays the SAME card — no duplicate. No cross-invocation
349
+ // dedup is claimed: a second MCP call is a second card by design.
350
+ const rawTitle = stringArg(args, "title");
351
+ const result = await callApi({
352
+ method: "POST",
353
+ path: "/cards",
354
+ body: {
355
+ title: rawTitle === undefined ? undefined : rawTitle.trim(),
356
+ body_md: stringArg(args, "body_md"),
357
+ column_id: stringArg(args, "column_id"),
358
+ },
359
+ idempotencyKey: crypto.randomUUID(),
360
+ signal,
361
+ });
362
+ return finish("create_card", result);
363
+ }
364
+ // Member tools reuse the existing API guards, audit, CAS/version rules and retry keys.
365
+ async function edit_card(args, signal) {
366
+ return finish("edit_card", await callApi({
367
+ method: "POST", path: `/cards/${encodeURIComponent(String(args["card_id"]))}/edit`, signal,
368
+ body: { title: args["title"], body_md: args["body_md"] },
369
+ idempotencyKey: crypto.randomUUID(),
370
+ }));
371
+ }
372
+ async function assign_card(args, signal) {
373
+ return finish("assign_card", await callApi({
374
+ method: "POST", path: `/cards/${encodeURIComponent(String(args["card_id"]))}/assign`, signal,
375
+ body: { assignee_kind: args["assignee_kind"], assignee_id: args["assignee_id"] },
376
+ idempotencyKey: crypto.randomUUID(),
377
+ }));
378
+ }
379
+ async function create_ask(args, signal) {
380
+ return finish("create_ask", await callApi({
381
+ method: "POST", path: "/asks", signal,
382
+ body: { text: args["text"], ttl_minutes: args["ttl_minutes"] },
383
+ idempotencyKey: crypto.randomUUID(),
384
+ }));
385
+ }
386
+ async function claim_ask(args, signal) {
387
+ return finish("claim_ask", await callApi({
388
+ method: "POST", path: `/asks/${encodeURIComponent(String(args["ask_id"]))}/claim`, signal,
389
+ body: {},
390
+ idempotencyKey: crypto.randomUUID(),
391
+ }));
392
+ }
393
+ async function resolve_ask(args, signal) {
394
+ return finish("resolve_ask", await callApi({
395
+ method: "POST", path: `/asks/${encodeURIComponent(String(args["ask_id"]))}/resolve`, signal,
396
+ body: { note: args["note"] },
397
+ idempotencyKey: crypto.randomUUID(),
398
+ }));
399
+ }
400
+ async function list_documents(args, signal) {
401
+ return finish("list_documents", await callApi({
402
+ method: "GET", path: "/docs", signal,
403
+ query: { lifecycle: stringArg(args, "lifecycle") },
404
+ }));
405
+ }
406
+ async function read_document(args, signal) {
407
+ return finish("read_document", await callApi({
408
+ method: "GET", path: `/docs/${encodeURIComponent(String(args["document_id"]))}`, signal,
409
+ }));
410
+ }
411
+ async function create_document(args, signal) {
412
+ return finish("create_document", await callApi({
413
+ method: "POST", path: "/docs", signal,
414
+ body: { title: args["title"], body_md: args["body_md"], collection: args["collection"], tags: args["tags"], summary: args["summary"] },
415
+ idempotencyKey: crypto.randomUUID(),
416
+ }));
417
+ }
418
+ async function edit_document(args, signal) {
419
+ return finish("edit_document", await callApi({
420
+ method: "POST", path: `/docs/${encodeURIComponent(String(args["document_id"]))}/edit`, signal,
421
+ body: { body_md: args["body_md"], expected_version: args["expected_version"], summary: args["summary"], allow_clear: args["allow_clear"] },
422
+ idempotencyKey: crypto.randomUUID(),
423
+ }));
424
+ }
425
+ async function terminal_wake_start(args, signal) {
426
+ return finish("terminal_wake_start", await callApi({ method: "POST", path: "/terminal-wakes/start", body: args, signal }));
427
+ }
428
+ async function terminal_wake_poll(args, signal) {
429
+ return finish("terminal_wake_poll", await callApi({ method: "POST", path: "/terminal-wakes/poll", body: args, signal }));
430
+ }
431
+ async function terminal_wake_receipt(args, signal) {
432
+ return finish("terminal_wake_receipt", await callApi({ method: "POST", path: "/terminal-wakes/receipt", body: args, signal }));
433
+ }
434
+ async function terminal_wake_checkin(args, signal) {
435
+ return finish("terminal_wake_checkin", await callApi({ method: "POST", path: "/terminal-wakes/checkin", body: args, signal }));
436
+ }
437
+ // ---- registry ----
438
+ export const TOOLS = {
439
+ terminal_wake_start: { name: "terminal_wake_start", run: terminal_wake_start },
440
+ terminal_wake_poll: { name: "terminal_wake_poll", run: terminal_wake_poll },
441
+ terminal_wake_receipt: { name: "terminal_wake_receipt", run: terminal_wake_receipt },
442
+ terminal_wake_checkin: { name: "terminal_wake_checkin", run: terminal_wake_checkin },
443
+ read_board: { name: "read_board", run: readBoard },
444
+ read_channels: { name: "read_channels", run: readChannels },
445
+ read_messages: { name: "read_messages", run: readMessages },
446
+ list_asks: { name: "list_asks", run: listAsks },
447
+ get_my_instructions: { name: "get_my_instructions", run: getMyInstructions },
448
+ whoami: { name: "whoami", run: whoami },
449
+ post_message: { name: "post_message", run: postMessage },
450
+ claim_card: { name: "claim_card", run: claimCard },
451
+ complete_card: { name: "complete_card", run: completeCard },
452
+ create_card: { name: "create_card", run: createCard },
453
+ read_roster: { name: "read_roster", run: readRoster },
454
+ list_conversations: { name: "list_conversations", run: listConversations },
455
+ create_conversation: { name: "create_conversation", run: createConversation },
456
+ read_conversation_messages: { name: "read_conversation_messages", run: readConversationMessages },
457
+ post_conversation_message: { name: "post_conversation_message", run: postConversationMessage },
458
+ edit_card: { name: "edit_card", run: edit_card },
459
+ assign_card: { name: "assign_card", run: assign_card },
460
+ create_ask: { name: "create_ask", run: create_ask },
461
+ claim_ask: { name: "claim_ask", run: claim_ask },
462
+ resolve_ask: { name: "resolve_ask", run: resolve_ask },
463
+ list_documents: { name: "list_documents", run: list_documents },
464
+ read_document: { name: "read_document", run: read_document },
465
+ create_document: { name: "create_document", run: create_document },
466
+ edit_document: { name: "edit_document", run: edit_document },
467
+ };
468
+ /**
469
+ * Accurate per-tool annotations for all tools.
470
+ *
471
+ * Semantics (MCP spec): `readOnlyHint` — the tool does not modify its
472
+ * environment; `destructiveHint` — the tool may perform DESTRUCTIVE (not
473
+ * merely additive) updates; `idempotentHint` — repeated calls with the same
474
+ * arguments have no ADDITIONAL effect on the environment; `openWorldHint` —
475
+ * the tool touches an open external world (all 9 tools operate on the closed
476
+ * AgentMesh workspace upstream, hence false everywhere).
477
+ *
478
+ * Write-tool rationale:
479
+ * - claim_card: CAS — a repeat claim either no-ops (same identity) or is a
480
+ * typed conflict that mutates nothing ⇒ idempotent, additive-only.
481
+ * - complete_card: claimant-only CAS — a repeat complete is a typed conflict
482
+ * whose CAS-miss branch is read-only ⇒ effect-idempotent, additive-only
483
+ * (the response is a conflict, but the ENVIRONMENT is unchanged — the
484
+ * hint speaks to environmental effect, per spec wording).
485
+ * - post_message / create_card: every invocation appends a NEW row by design
486
+ * (fresh Idempotency-Key per invocation) ⇒ NOT idempotent; additive-only.
487
+ *
488
+ * Serving these from ListTools is a one-line integration in server.ts
489
+ * (`annotations: TOOL_ANNOTATIONS[name]`) — server.ts is Seam B's file, so
490
+ * that wiring is FLAGGED to the integrator rather than edited here.
491
+ */
492
+ export const TOOL_ANNOTATIONS = {
493
+ terminal_wake_start: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
494
+ terminal_wake_poll: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
495
+ terminal_wake_receipt: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
496
+ terminal_wake_checkin: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
497
+ read_board: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
498
+ read_channels: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
499
+ read_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
500
+ list_asks: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
501
+ get_my_instructions: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
502
+ whoami: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
503
+ post_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
504
+ claim_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
505
+ complete_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
506
+ create_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
507
+ read_roster: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
508
+ list_conversations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
509
+ create_conversation: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
510
+ read_conversation_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
511
+ post_conversation_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
512
+ edit_document: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
513
+ create_document: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
514
+ read_document: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
515
+ list_documents: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
516
+ resolve_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
517
+ claim_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
518
+ create_ask: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
519
+ assign_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
520
+ edit_card: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
521
+ };
522
+ function isToolName(name) {
523
+ return HOSTED_TOOL_NAMES.some((n) => n === name);
524
+ }
525
+ /** Look up a registered tool by its wire-level name (which may be any string a client sends). */
526
+ export function getTool(name) {
527
+ return isToolName(name) ? TOOLS[name] : undefined;
528
+ }
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Poll-mode delivery for the agentmesh plugin (td-ef46e2): a Claude Code
4
+ * plugin monitor runs this, and every line it prints wakes the session.
5
+ *
6
+ * It never talks to agentmesh.md and never sees the API key (monitors do not
7
+ * receive plugin userConfig). It only drains queues that the MCP server of
8
+ * the SAME Claude Code session wrote in poll mode: mode.json must name this
9
+ * session (nearest `claude` ancestor) and a live server pid. Queues of other
10
+ * sessions, other agents, or sessions in channel/off mode are never printed
11
+ * or removed.
12
+ *
13
+ * Each item is renamed to .sending before its line is written and removed
14
+ * after. An item found already .sending (interrupted earlier) is printed
15
+ * again with "replay=possible". A printed line means the session received
16
+ * the text, not that it acted on it.
17
+ *
18
+ * Usage: wake-monitor.js <state root> (the plugin passes ${CLAUDE_PLUGIN_DATA}/wake)
19
+ */
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import { writeAtomic } from "./wake-storage.js";
23
+ import { findSessionPid } from "./session.js";
24
+ export { findSessionPid };
25
+ const INTERVAL_MS = 2_000;
26
+ function readJson(file) {
27
+ try {
28
+ return JSON.parse(fs.readFileSync(file, "utf8"));
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ function alive(pid) {
35
+ if (typeof pid !== "number")
36
+ return false;
37
+ try {
38
+ process.kill(pid, 0);
39
+ return true;
40
+ }
41
+ catch (err) {
42
+ return err.code === "EPERM";
43
+ }
44
+ }
45
+ const flat = (value) => String(value ?? "").replace(/[\r\n\u2028\u2029]+/g, " ");
46
+ /** One line per event, with its identities; message text cannot forge extra lines. */
47
+ export function formatLine(item, replay) {
48
+ const meta = (item["meta"] ?? {});
49
+ const kind = typeof item["kind"] === "string" ? item["kind"] : "notice";
50
+ const ids = ["message_id", "conversation_id", "channel", "event_key"]
51
+ .filter((k) => typeof meta[k] === "string")
52
+ .map((k) => `${k}=${flat(meta[k])}`);
53
+ if (replay)
54
+ ids.push("replay=possible");
55
+ return `agentmesh.md ${kind}: ${flat(item["content"])} (${ids.join(", ")})`;
56
+ }
57
+ /** Prints and removes this session's poll-mode items. Returns how many lines were written. */
58
+ export function drain(root, write, sessionPid) {
59
+ if (sessionPid === null)
60
+ return 0; // cannot tell which session we are in: deliver nothing
61
+ let delivered = 0;
62
+ let agents;
63
+ try {
64
+ agents = fs.readdirSync(root);
65
+ }
66
+ catch {
67
+ return 0; // nothing written yet
68
+ }
69
+ for (const agent of agents) {
70
+ const dir = path.join(root, agent);
71
+ const mode = readJson(path.join(dir, "mode.json"));
72
+ if (mode?.["mode"] !== "poll" || mode["session_pid"] !== sessionPid || !alive(mode["pid"]))
73
+ continue;
74
+ const queue = path.join(dir, "queue");
75
+ let files;
76
+ try {
77
+ files = fs.readdirSync(queue).filter((f) => f.endsWith(".json") || f.endsWith(".sending"));
78
+ }
79
+ catch {
80
+ continue;
81
+ }
82
+ const items = files
83
+ .map((f) => ({ file: path.join(queue, f), replay: f.endsWith(".sending"), item: readJson(path.join(queue, f)) }))
84
+ .filter((x) => x.item !== undefined)
85
+ .sort((a, b) => String(a.item["queued_at"]).localeCompare(String(b.item["queued_at"])));
86
+ for (const { file, replay, item } of items) {
87
+ const sending = replay ? file : file.replace(/\.json$/, ".sending");
88
+ if (!replay)
89
+ fs.renameSync(file, sending);
90
+ write(formatLine(item, replay));
91
+ if (mode["terminal"] === true && /^[a-f0-9-]{36}$/.test(String(item["key"]))) {
92
+ const receipts = path.join(dir, "receipts");
93
+ fs.mkdirSync(receipts, { recursive: true, mode: 0o700 });
94
+ writeAtomic(path.join(receipts, `${String(item["key"])}.json`), { transport: true });
95
+ }
96
+ fs.rmSync(sending, { force: true });
97
+ delivered += 1;
98
+ }
99
+ }
100
+ return delivered;
101
+ }
102
+ const isMain = process.argv[1] !== undefined && path.resolve(process.argv[1]).endsWith("wake-monitor.js");
103
+ if (isMain) {
104
+ const root = process.argv[2];
105
+ if (root === undefined || !path.isAbsolute(root)) {
106
+ console.error("wake-monitor: usage: wake-monitor.js <absolute state root>");
107
+ process.exit(2);
108
+ }
109
+ const session = findSessionPid();
110
+ if (session === null)
111
+ console.error("wake-monitor: no Claude Code session found above this process; poll delivery is off.");
112
+ const tick = () => {
113
+ drain(root, (line) => process.stdout.write(`${line}\n`), session);
114
+ };
115
+ tick();
116
+ setInterval(tick, INTERVAL_MS);
117
+ }