@agentmesh-md/mcp-server 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tools.js ADDED
@@ -0,0 +1,424 @@
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 { 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 whoami(_args, signal) {
124
+ const result = await callApi({ method: "GET", path: "/me", signal });
125
+ return finish("whoami", result);
126
+ }
127
+ async function postMessage(args, signal) {
128
+ const result = await callApi({
129
+ method: "POST",
130
+ path: "/messages",
131
+ body: { body_md: stringArg(args, "body_md"), channel: stringArg(args, "channel") },
132
+ idempotencyKey: crypto.randomUUID(),
133
+ signal,
134
+ });
135
+ return finish("post_message", result);
136
+ }
137
+ async function readRoster(_args, signal) {
138
+ const result = await callApi({ method: "GET", path: "/roster", signal });
139
+ return finish("read_roster", result);
140
+ }
141
+ async function listConversations(args, signal) {
142
+ const result = await callApi({
143
+ method: "GET",
144
+ path: "/conversations",
145
+ query: { limit: numberArg(args, "limit"), before_id: stringArg(args, "before_id") },
146
+ signal,
147
+ });
148
+ return finish("list_conversations", result);
149
+ }
150
+ async function createConversation(args, signal) {
151
+ const result = await callApi({
152
+ method: "POST",
153
+ path: "/conversations",
154
+ body: { participants: args["participants"] },
155
+ idempotencyKey: crypto.randomUUID(),
156
+ signal,
157
+ });
158
+ return finish("create_conversation", result);
159
+ }
160
+ async function readConversationMessages(args, signal) {
161
+ const conversationId = stringArg(args, "conversation_id");
162
+ const result = await callApi({
163
+ method: "GET",
164
+ path: `/conversations/${encodeURIComponent(conversationId ?? "")}/messages`,
165
+ query: { limit: numberArg(args, "limit"), before_id: stringArg(args, "before_id") },
166
+ signal,
167
+ });
168
+ return finish("read_conversation_messages", result);
169
+ }
170
+ async function postConversationMessage(args, signal) {
171
+ const conversationId = stringArg(args, "conversation_id");
172
+ const result = await callApi({
173
+ method: "POST",
174
+ path: `/conversations/${encodeURIComponent(conversationId ?? "")}/messages`,
175
+ body: { body_md: stringArg(args, "body_md") },
176
+ idempotencyKey: crypto.randomUUID(),
177
+ signal,
178
+ });
179
+ return finish("post_conversation_message", result);
180
+ }
181
+ /**
182
+ * Resolve THIS invocation's own identity via `GET /me` (the same credential
183
+ * the failed claim used — in http mode the per-request key, in stdio the
184
+ * process key). Returns null on ANY failure or non-conforming body: the
185
+ * caller treats an unprovable identity as "not me" (fail closed — the typed
186
+ * conflict passes through rather than guessing a no-op). Deliberately NOT
187
+ * cached: in http mode the credential varies per request, and this path only
188
+ * runs on an ALREADY_CLAIMED conflict, never on the happy path.
189
+ */
190
+ async function fetchSelfIdentity(signal) {
191
+ const result = await callApi({ method: "GET", path: "/me", signal });
192
+ if (!result.ok || typeof result.data !== "object" || result.data === null) {
193
+ return null;
194
+ }
195
+ const principal = result.data["principal"];
196
+ if (typeof principal !== "object" || principal === null) {
197
+ return null;
198
+ }
199
+ const record = principal;
200
+ const id = record["id"];
201
+ const kind = record["kind"];
202
+ return typeof id === "string" && typeof kind === "string" ? { id, kind } : null;
203
+ }
204
+ /** Parse `{claimed_by, claimed_by_kind}` from ALREADY_CLAIMED's details; null if absent/malformed. */
205
+ function claimantFromDetails(details) {
206
+ if (typeof details !== "object" || details === null) {
207
+ return null;
208
+ }
209
+ const record = details;
210
+ const claimedBy = record["claimed_by"];
211
+ const claimedByKind = record["claimed_by_kind"];
212
+ return typeof claimedBy === "string" && typeof claimedByKind === "string"
213
+ ? { claimedBy, claimedByKind }
214
+ : null;
215
+ }
216
+ /**
217
+ * Read-after-write echo for the no-op branch: fetch the ACTUAL card row via
218
+ * `GET /board` (the only card-reading endpoint) and return it only if it
219
+ * still shows `status='claimed'` by exactly this identity — a defensive
220
+ * re-verification against state drift between the 409 and this read. Returns
221
+ * null when the readback fails (e.g. a cards:claim-only key lacks board:read
222
+ * — 403), the card is absent, or the state drifted; the caller then falls
223
+ * back to the honest typed conflict. The row is echoed as the upstream
224
+ * serialized it — never synthesized — so the normal successResult path
225
+ * validates it against claim_card's outputSchema like any real claim.
226
+ */
227
+ async function fetchClaimedCardEcho(cardId, self, signal) {
228
+ const result = await callApi({ method: "GET", path: "/board", signal });
229
+ if (!result.ok || typeof result.data !== "object" || result.data === null) {
230
+ return null;
231
+ }
232
+ const columns = result.data["columns"];
233
+ if (!Array.isArray(columns)) {
234
+ return null;
235
+ }
236
+ for (const column of columns) {
237
+ if (typeof column !== "object" || column === null) {
238
+ continue;
239
+ }
240
+ const cards = column["cards"];
241
+ if (!Array.isArray(cards)) {
242
+ continue;
243
+ }
244
+ for (const card of cards) {
245
+ if (typeof card !== "object" || card === null) {
246
+ continue;
247
+ }
248
+ const record = card;
249
+ if (record["id"] !== cardId) {
250
+ continue;
251
+ }
252
+ if (record["status"] === "claimed" && record["claimed_by"] === self.id && record["claimed_by_kind"] === self.kind) {
253
+ return record;
254
+ }
255
+ return null; // found, but no longer claimed by this identity — do not echo
256
+ }
257
+ }
258
+ return null;
259
+ }
260
+ /** Typed ALREADY_CLAIMED tool error with the claimant echoed into the surfaced text. */
261
+ function claimConflictResult(result, claimant) {
262
+ if (claimant === null) {
263
+ return errorResult(result);
264
+ }
265
+ // Claimant ids are workspace principal ids (uuid/uid), not credentials; the
266
+ // composed text still passes redact() inside errorResult as a final scrub.
267
+ return errorResult({
268
+ ...result,
269
+ message: `${result.message} (claimed_by=${claimant.claimedBy}, claimed_by_kind=${claimant.claimedByKind})`,
270
+ });
271
+ }
272
+ async function claimCard(args, signal) {
273
+ const cardId = stringArg(args, "card_id");
274
+ if (cardId === undefined) {
275
+ return errorResult({ ok: false, code: "VALIDATION", message: 'missing or invalid required argument "card_id".', status: 0 });
276
+ }
277
+ // CAS claim via the parent API, exactly as before: fresh Idempotency-Key
278
+ // per MCP invocation (c7), same key reused only by client.ts's own
279
+ // transport retry. On success the parent's RETURNING* row comes back and
280
+ // is the typed read-after-write echo.
281
+ const result = await callApi({
282
+ method: "POST",
283
+ path: `/cards/${encodeURIComponent(cardId)}/claim`,
284
+ idempotencyKey: crypto.randomUUID(),
285
+ signal,
286
+ });
287
+ if (result.ok) {
288
+ return successResult("claim_card", result.data);
289
+ }
290
+ if (result.code !== "ALREADY_CLAIMED") {
291
+ // NOT_FOUND, CARD_STATE_CONFLICT (terminal 'done' is unclaimable — the
292
+ // no-op carve-out is claim-state only), scope/auth failures, network:
293
+ // all pass through typed, unchanged.
294
+ return errorResult(result);
295
+ }
296
+ const claimant = claimantFromDetails(result.details);
297
+ if (claimant !== null) {
298
+ const self = await fetchSelfIdentity(signal);
299
+ // V5 RED anchor (do not reformat): the same-identity check below is the
300
+ // mutation target proving the no-op is load-bearing.
301
+ if (self !== null && claimant.claimedBy === self.id && claimant.claimedByKind === self.kind) {
302
+ // Re-claim by the SAME identity => no-op success (NEW Seam-A
303
+ // semantics). The result body is the ACTUAL row from a live readback,
304
+ // never a body assembled from assumptions; if the readback cannot
305
+ // prove the row (no board:read, drift, failure), fall through to the
306
+ // honest typed conflict below.
307
+ const echoed = await fetchClaimedCardEcho(cardId, self, signal);
308
+ if (echoed !== null) {
309
+ return successResult("claim_card", { card: echoed });
310
+ }
311
+ }
312
+ }
313
+ return claimConflictResult(result, claimant);
314
+ }
315
+ async function completeCard(args, signal) {
316
+ const cardId = stringArg(args, "card_id");
317
+ if (cardId === undefined) {
318
+ return errorResult({ ok: false, code: "VALIDATION", message: 'missing or invalid required argument "card_id".', status: 0 });
319
+ }
320
+ // Claimant-only CAS via the parent API, unchanged; `409
321
+ // CARD_STATE_CONFLICT` passes through TYPED for every wrong state.
322
+ //
323
+ // Phase-1 Seam A, deliberate asymmetry with claim_card (FLAGGED, build-plan
324
+ // resolution (c)): a same-identity re-complete no-op is INFEASIBLE without
325
+ // a parent change. Ground truth (src/routes/board.js, complete CAS-miss
326
+ // branch): the conflict payload is `{ status: cur.status }` ONLY — it does
327
+ // NOT echo the claimant, so "this card is done AND this identity completed
328
+ // it" cannot be proven from the payload; a card completed by X and
329
+ // re-completed by Y yields byte-identical conflicts. Honesty over reach:
330
+ // the strict typed passthrough stays until the parent ever echoes the
331
+ // claimant here. (Effect-idempotence still holds: a re-complete mutates
332
+ // nothing — the CAS-miss branch is read-only.)
333
+ const result = await callApi({
334
+ method: "POST",
335
+ path: `/cards/${encodeURIComponent(cardId)}/complete`,
336
+ idempotencyKey: crypto.randomUUID(),
337
+ signal,
338
+ });
339
+ return finish("complete_card", result);
340
+ }
341
+ async function createCard(args, signal) {
342
+ // Phase-1 Seam A (build-plan resolution (c), unchanged behavior, pinned by
343
+ // control V5): ONE fresh Idempotency-Key per MCP invocation (c7 discipline);
344
+ // a transport-level retry inside client.ts replays the SAME key, so the
345
+ // parent byte-replays the SAME card — no duplicate. No cross-invocation
346
+ // dedup is claimed: a second MCP call is a second card by design.
347
+ const rawTitle = stringArg(args, "title");
348
+ const result = await callApi({
349
+ method: "POST",
350
+ path: "/cards",
351
+ body: {
352
+ title: rawTitle === undefined ? undefined : rawTitle.trim(),
353
+ body_md: stringArg(args, "body_md"),
354
+ column_id: stringArg(args, "column_id"),
355
+ },
356
+ idempotencyKey: crypto.randomUUID(),
357
+ signal,
358
+ });
359
+ return finish("create_card", result);
360
+ }
361
+ // ---- registry ----
362
+ export const TOOLS = {
363
+ read_board: { name: "read_board", run: readBoard },
364
+ read_channels: { name: "read_channels", run: readChannels },
365
+ read_messages: { name: "read_messages", run: readMessages },
366
+ list_asks: { name: "list_asks", run: listAsks },
367
+ whoami: { name: "whoami", run: whoami },
368
+ post_message: { name: "post_message", run: postMessage },
369
+ claim_card: { name: "claim_card", run: claimCard },
370
+ complete_card: { name: "complete_card", run: completeCard },
371
+ create_card: { name: "create_card", run: createCard },
372
+ read_roster: { name: "read_roster", run: readRoster },
373
+ list_conversations: { name: "list_conversations", run: listConversations },
374
+ create_conversation: { name: "create_conversation", run: createConversation },
375
+ read_conversation_messages: { name: "read_conversation_messages", run: readConversationMessages },
376
+ post_conversation_message: { name: "post_conversation_message", run: postConversationMessage },
377
+ };
378
+ /**
379
+ * Accurate per-tool annotations for all tools.
380
+ *
381
+ * Semantics (MCP spec): `readOnlyHint` — the tool does not modify its
382
+ * environment; `destructiveHint` — the tool may perform DESTRUCTIVE (not
383
+ * merely additive) updates; `idempotentHint` — repeated calls with the same
384
+ * arguments have no ADDITIONAL effect on the environment; `openWorldHint` —
385
+ * the tool touches an open external world (all 9 tools operate on the closed
386
+ * AgentMesh workspace upstream, hence false everywhere).
387
+ *
388
+ * Write-tool rationale:
389
+ * - claim_card: CAS — a repeat claim either no-ops (same identity) or is a
390
+ * typed conflict that mutates nothing ⇒ idempotent, additive-only.
391
+ * - complete_card: claimant-only CAS — a repeat complete is a typed conflict
392
+ * whose CAS-miss branch is read-only ⇒ effect-idempotent, additive-only
393
+ * (the response is a conflict, but the ENVIRONMENT is unchanged — the
394
+ * hint speaks to environmental effect, per spec wording).
395
+ * - post_message / create_card: every invocation appends a NEW row by design
396
+ * (fresh Idempotency-Key per invocation) ⇒ NOT idempotent; additive-only.
397
+ *
398
+ * Serving these from ListTools is a one-line integration in server.ts
399
+ * (`annotations: TOOL_ANNOTATIONS[name]`) — server.ts is Seam B's file, so
400
+ * that wiring is FLAGGED to the integrator rather than edited here.
401
+ */
402
+ export const TOOL_ANNOTATIONS = {
403
+ read_board: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
404
+ read_channels: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
405
+ read_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
406
+ list_asks: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
407
+ whoami: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
408
+ post_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
409
+ claim_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
410
+ complete_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
411
+ create_card: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
412
+ read_roster: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
413
+ list_conversations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
414
+ create_conversation: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
415
+ read_conversation_messages: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
416
+ post_conversation_message: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
417
+ };
418
+ function isToolName(name) {
419
+ return TOOL_NAMES.some((n) => n === name);
420
+ }
421
+ /** Look up a registered tool by its wire-level name (which may be any string a client sends). */
422
+ export function getTool(name) {
423
+ return isToolName(name) ? TOOLS[name] : undefined;
424
+ }
@@ -0,0 +1,111 @@
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 { findSessionPid } from "./session.js";
23
+ export { findSessionPid };
24
+ const INTERVAL_MS = 2_000;
25
+ function readJson(file) {
26
+ try {
27
+ return JSON.parse(fs.readFileSync(file, "utf8"));
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ function alive(pid) {
34
+ if (typeof pid !== "number")
35
+ return false;
36
+ try {
37
+ process.kill(pid, 0);
38
+ return true;
39
+ }
40
+ catch (err) {
41
+ return err.code === "EPERM";
42
+ }
43
+ }
44
+ const flat = (value) => String(value ?? "").replace(/[\r\n\u2028\u2029]+/g, " ");
45
+ /** One line per event, with its identities; message text cannot forge extra lines. */
46
+ export function formatLine(item, replay) {
47
+ const meta = (item["meta"] ?? {});
48
+ const kind = typeof item["kind"] === "string" ? item["kind"] : "notice";
49
+ const ids = ["message_id", "conversation_id", "channel", "event_key"]
50
+ .filter((k) => typeof meta[k] === "string")
51
+ .map((k) => `${k}=${flat(meta[k])}`);
52
+ if (replay)
53
+ ids.push("replay=possible");
54
+ return `agentmesh.md ${kind}: ${flat(item["content"])} (${ids.join(", ")})`;
55
+ }
56
+ /** Prints and removes this session's poll-mode items. Returns how many lines were written. */
57
+ export function drain(root, write, sessionPid) {
58
+ if (sessionPid === null)
59
+ return 0; // cannot tell which session we are in: deliver nothing
60
+ let delivered = 0;
61
+ let agents;
62
+ try {
63
+ agents = fs.readdirSync(root);
64
+ }
65
+ catch {
66
+ return 0; // nothing written yet
67
+ }
68
+ for (const agent of agents) {
69
+ const dir = path.join(root, agent);
70
+ const mode = readJson(path.join(dir, "mode.json"));
71
+ if (mode?.["mode"] !== "poll" || mode["session_pid"] !== sessionPid || !alive(mode["pid"]))
72
+ continue;
73
+ const queue = path.join(dir, "queue");
74
+ let files;
75
+ try {
76
+ files = fs.readdirSync(queue).filter((f) => f.endsWith(".json") || f.endsWith(".sending"));
77
+ }
78
+ catch {
79
+ continue;
80
+ }
81
+ const items = files
82
+ .map((f) => ({ file: path.join(queue, f), replay: f.endsWith(".sending"), item: readJson(path.join(queue, f)) }))
83
+ .filter((x) => x.item !== undefined)
84
+ .sort((a, b) => String(a.item["queued_at"]).localeCompare(String(b.item["queued_at"])));
85
+ for (const { file, replay, item } of items) {
86
+ const sending = replay ? file : file.replace(/\.json$/, ".sending");
87
+ if (!replay)
88
+ fs.renameSync(file, sending);
89
+ write(formatLine(item, replay));
90
+ fs.rmSync(sending, { force: true });
91
+ delivered += 1;
92
+ }
93
+ }
94
+ return delivered;
95
+ }
96
+ const isMain = process.argv[1] !== undefined && path.resolve(process.argv[1]).endsWith("wake-monitor.js");
97
+ if (isMain) {
98
+ const root = process.argv[2];
99
+ if (root === undefined || !path.isAbsolute(root)) {
100
+ console.error("wake-monitor: usage: wake-monitor.js <absolute state root>");
101
+ process.exit(2);
102
+ }
103
+ const session = findSessionPid();
104
+ if (session === null)
105
+ console.error("wake-monitor: no Claude Code session found above this process; poll delivery is off.");
106
+ const tick = () => {
107
+ drain(root, (line) => process.stdout.write(`${line}\n`), session);
108
+ };
109
+ tick();
110
+ setInterval(tick, INTERVAL_MS);
111
+ }