@agentmesh-md/mcp-server 0.2.2 → 0.3.4

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.
Files changed (45) hide show
  1. package/README.md +143 -4
  2. package/dist/client.js +16 -5
  3. package/dist/codex-hooks.js +142 -0
  4. package/dist/connect.js +75 -205
  5. package/dist/context.js +7 -0
  6. package/dist/contract.js +5 -1
  7. package/dist/errors.js +0 -55
  8. package/dist/index.js +41 -8
  9. package/dist/legacy.js +2 -66
  10. package/dist/oauth-client.js +131 -26
  11. package/dist/plugin-install.js +154 -0
  12. package/dist/plugin-monitor.js +292 -0
  13. package/dist/plugin-permissions.js +212 -0
  14. package/dist/plugin-proxy.js +75 -0
  15. package/dist/plugin-session.js +381 -0
  16. package/dist/plugin-storage.js +94 -0
  17. package/dist/plugin-target.js +16 -0
  18. package/dist/schemas.js +8 -2
  19. package/dist/server.js +30 -5
  20. package/dist/session.js +118 -14
  21. package/dist/terminal-diagnostic.js +1 -1
  22. package/dist/terminal-runtime.js +96 -161
  23. package/dist/tool-annotations.js +57 -0
  24. package/dist/tools.js +36 -55
  25. package/dist/wake-storage.js +33 -49
  26. package/package.json +5 -4
  27. package/plugin-marketplace/.claude-plugin/marketplace.json +11 -0
  28. package/plugin-marketplace/plugins/agentmesh/.claude-plugin/plugin.json +23 -0
  29. package/plugin-marketplace/plugins/agentmesh/README.md +36 -0
  30. package/plugin-marketplace/plugins/agentmesh/hooks/codex.json +44 -0
  31. package/plugin-marketplace/plugins/agentmesh/hooks/hooks.json +44 -0
  32. package/plugin-marketplace/plugins/agentmesh/mcp.json +15 -0
  33. package/plugin-marketplace/plugins/agentmesh/monitors/monitors.json +7 -0
  34. package/plugin-marketplace/plugins/agentmesh/plugin.json +6 -0
  35. package/plugin-marketplace/plugins/agentmesh/release.json +1 -0
  36. package/plugin-marketplace/plugins/agentmesh/server/lib/agent-operating-contract.txt +120 -0
  37. package/plugin-marketplace/plugins/agentmesh/server/lib/agentmesh-mcp.js +39419 -0
  38. package/plugin-marketplace/plugins/agentmesh/server/package.json +4 -0
  39. package/plugin-marketplace/plugins/agentmesh/server/schemas/defs.json +121 -0
  40. package/plugin-marketplace/plugins/agentmesh/server/schemas/tools.json +1933 -0
  41. package/schemas/tools.json +592 -3
  42. package/dist/connect-bridge.js +0 -62
  43. package/dist/mentions.cjs +0 -22
  44. package/dist/wake-monitor.js +0 -117
  45. package/dist/wake.js +0 -521
package/dist/wake.js DELETED
@@ -1,521 +0,0 @@
1
- /**
2
- * Session wake (td-ef46e2, plan v3 e90bf43d): turns agentmesh.md @mentions and
3
- * DMs addressed to THIS agent key into wake events for the local session.
4
- *
5
- * Runs only in the stdio entry (never the per-request HTTP server) and only
6
- * when AGENTMESH_WAKE_MODE is "channel" or "poll". It is the ONE reader of the
7
- * agentmesh.md positions for its (origin, workspace, agent); both delivery
8
- * modes consume the same local queue, so channel and poll never share a cursor.
9
- *
10
- * activity long-poll ─┐
11
- * ├─> trusted-sender gate ─> queue/<key>.json ─> deliver
12
- * DM participant poll ┘ (written BEFORE a position moves)
13
- *
14
- * deliver = channel: push notifications/claude/channel, then delete the item.
15
- * poll: the plugin monitor of the SAME Claude Code session prints
16
- * it (wake-monitor.ts; bound by session pid in mode.json).
17
- *
18
- * Delivery boundary: an item is removed once it has been written to the
19
- * session transport (channel) or to the monitor's output (poll). Neither
20
- * proves the session acted on it. Items still queued at restart are sent
21
- * again marked as a possible replay. Channel pushes made while the channel is
22
- * not registered are dropped by Claude Code without an error.
23
- *
24
- * Message text is untrusted content. Only messages whose server-recorded
25
- * author is in AGENTMESH_WAKE_TRUSTED (exact, case-sensitive "kind:id")
26
- * produce a wake with content. An untrusted author produces at most one
27
- * content-free notice so the operator can decide whether to trust them.
28
- */
29
- import crypto from "node:crypto";
30
- import fs from "node:fs";
31
- import path from "node:path";
32
- import { callApi } from "./client.js";
33
- import { config } from "./config.js";
34
- import { logStderr } from "./logger.js";
35
- import { writeAtomic, readJson, claimLock } from "./wake-storage.js";
36
- import { findSessionPid } from "./session.js";
37
- const WAIT_S = 10; // client.ts aborts each attempt at 15 s; 25 would always time out
38
- const PAGE = 200;
39
- const PREVIEW_CHARS = 500;
40
- const MAX_LOCATE_PAGES = 5; // per iteration; progress is saved, so a deep search resumes
41
- const MAX_DM_PAGES = 5; // per conversation scan; beyond this a gap is reported, never skipped silently
42
- const BACKOFF_MS = [2_000, 5_000, 15_000, 30_000, 60_000];
43
- const LOCK_RETRY_MS = 5_000;
44
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
45
- class Stop extends Error {
46
- }
47
- class Retry extends Error {
48
- delayMs;
49
- constructor(message, delayMs) {
50
- super(message);
51
- this.delayMs = delayMs;
52
- }
53
- }
54
- /** Bounded work for this iteration is done; continue on the next one without backoff. */
55
- class Continue extends Error {
56
- }
57
- class CursorExpired extends Error {
58
- latest;
59
- constructor(latest) {
60
- super("CURSOR_EXPIRED");
61
- this.latest = latest;
62
- }
63
- }
64
- // ---------- config ----------
65
- export function readWakeConfig(env = process.env) {
66
- const mode = env["AGENTMESH_WAKE_MODE"] ?? "off";
67
- if (mode === "off" || mode === "")
68
- return null;
69
- if (mode !== "channel" && mode !== "poll") {
70
- logStderr(`agentmesh-mcp: wake disabled: AGENTMESH_WAKE_MODE "${mode}" is not channel, poll or off.`);
71
- return null;
72
- }
73
- const stateRoot = env["AGENTMESH_WAKE_STATE_DIR"] ?? "";
74
- if (!path.isAbsolute(stateRoot)) {
75
- logStderr("agentmesh-mcp: wake disabled: AGENTMESH_WAKE_STATE_DIR must be an absolute path.");
76
- return null;
77
- }
78
- const trusted = new Set();
79
- for (const raw of (env["AGENTMESH_WAKE_TRUSTED"] ?? "").split(/[\s,]+/)) {
80
- if (raw === "")
81
- continue;
82
- const m = /^(human|agent):(.+)$/.exec(raw);
83
- if (m === null || m[2].includes("*")) {
84
- logStderr(`agentmesh-mcp: wake ignores trusted entry "${raw}" (expected human:<id> or agent:<id>).`);
85
- continue;
86
- }
87
- trusted.add(raw); // ids are case-sensitive (Firebase UIDs)
88
- }
89
- const names = (key, what) => {
90
- const out = new Set();
91
- for (const raw of (env[key] ?? "").split(/[\s,]+/)) {
92
- const name = raw.replace(/^[@#]/, "").toLowerCase();
93
- if (name === "")
94
- continue;
95
- if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name)) {
96
- logStderr(`agentmesh-mcp: wake ignores ${what} "${raw}".`);
97
- continue;
98
- }
99
- out.add(name);
100
- }
101
- return out;
102
- };
103
- return {
104
- mode,
105
- stateRoot,
106
- trusted,
107
- groups: names("AGENTMESH_WAKE_GROUPS", "group"),
108
- wakeChannels: names("AGENTMESH_WAKE_CHANNELS", "channel"),
109
- };
110
- }
111
- // ---------- small file helpers (0600 files, atomic replace) ----------
112
- // ---------- API ----------
113
- async function api(apiPath, query, signal) {
114
- const res = await callApi({ method: "GET", path: apiPath, query, signal });
115
- if (res.ok)
116
- return res.data;
117
- if (signal.aborted)
118
- throw new Stop("aborted");
119
- if (res.status === 401 || res.status === 403)
120
- throw new Stop(`http_${res.status}`);
121
- if (res.code === "CURSOR_EXPIRED") {
122
- const latest = res.details?.latest;
123
- throw new CursorExpired(typeof latest === "number" ? latest : null);
124
- }
125
- // 429, 5xx, network and timeouts keep progress and back off (at least as
126
- // long as the server's Retry-After asks).
127
- throw new Retry(res.status === 0 ? res.code : `http_${res.status}`, res.retryAfterMs);
128
- }
129
- async function whoami(signal) {
130
- const body = (await api("/me", {}, signal));
131
- const p = body?.principal;
132
- if (p?.["kind"] !== "agent" || typeof p["id"] !== "string" || typeof p["name"] !== "string" || typeof p["workspace_id"] !== "string") {
133
- throw new Stop("identity_not_agent");
134
- }
135
- return { id: p["id"], name: p["name"], workspace_id: p["workspace_id"] };
136
- }
137
- // ---------- matching ----------
138
- // Shared pure matcher, copied into the distributable by copy-contract.mjs.
139
- export { mentionedGroups, mentionsAnyone, mentionsAgent } from './mentions.cjs';
140
- import { mentionedGroups, mentionsAnyone, mentionsAgent } from './mentions.cjs';
141
- function preview(body) {
142
- const flat = body.replace(/\s+/g, " ").trim();
143
- return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS)}…` : flat;
144
- }
145
- // ---------- the loop ----------
146
- export class WakeLoop {
147
- opts;
148
- dir = "";
149
- state;
150
- origin;
151
- failures = 0;
152
- constructor(opts) {
153
- this.opts = opts;
154
- this.origin = crypto.createHash("sha256").update(config.apiBaseUrl).digest("hex").slice(0, 12);
155
- }
156
- async run() {
157
- const { signal } = this.opts;
158
- // Identity, retried until it answers: only a rejected key stops here.
159
- let identity;
160
- while (identity === undefined) {
161
- if (signal.aborted)
162
- return;
163
- try {
164
- identity = await whoami(signal);
165
- }
166
- catch (err) {
167
- if (err instanceof Stop) {
168
- if (!signal.aborted)
169
- logStderr(`agentmesh-mcp: wake stopped before start: ${describe(err)}. Reconnect the agent key to resume.`);
170
- return;
171
- }
172
- await this.backoff(err);
173
- }
174
- }
175
- this.dir = path.join(this.opts.stateRoot, `${this.origin}-${identity.workspace_id}-${identity.id}`);
176
- fs.mkdirSync(path.join(this.dir, "queue"), { recursive: true, mode: 0o700 });
177
- // Another live reader (a second session, or a previous server still
178
- // exiting) keeps the lock; wait and take over when it is gone.
179
- let told = false;
180
- while (!claimLock(this.dir)) {
181
- if (!told)
182
- logStderr("agentmesh-mcp: wake waiting: another session already reads wake events for this agent.");
183
- told = true;
184
- await sleep(LOCK_RETRY_MS, signal);
185
- if (signal.aborted)
186
- return;
187
- }
188
- // session_pid binds poll delivery to this Claude Code session's own monitor.
189
- writeAtomic(path.join(this.dir, "mode.json"), { mode: this.opts.mode, pid: process.pid, session_pid: findSessionPid() });
190
- this.state = this.loadState(identity);
191
- logStderr(`agentmesh-mcp: wake on (mode=${this.opts.mode}) for agent ${identity.name}.`);
192
- let ready = false;
193
- while (!signal.aborted) {
194
- try {
195
- if (!ready) {
196
- // Positions first, then "ready": a message sent in answer to the
197
- // ready notice is always after the saved positions.
198
- await this.flush(true);
199
- while (this.state.cursor === null)
200
- await this.pollActivity();
201
- while (!this.state.dm.initialized)
202
- await this.pollDms();
203
- this.enqueue({
204
- key: `connected-${process.pid}-${Date.now()}`,
205
- kind: "notice",
206
- content: `Connected to agentmesh.md as @${identity.name}. Mentions and DMs from trusted senders will appear here.`,
207
- meta: { kind: "notice" },
208
- });
209
- ready = true;
210
- }
211
- else {
212
- await this.pollActivity();
213
- await this.pollDms();
214
- }
215
- await this.flush(false);
216
- this.failures = 0;
217
- }
218
- catch (err) {
219
- if (err instanceof Continue) {
220
- await this.flush(false).catch(() => undefined);
221
- continue;
222
- }
223
- if (err instanceof Stop) {
224
- if (!signal.aborted) {
225
- logStderr(`agentmesh-mcp: wake stopped: ${describe(err)}. Reconnect the agent key to resume.`);
226
- this.enqueue({
227
- key: `stopped-${Date.now()}`,
228
- kind: "notice",
229
- content: "agentmesh.md wake stopped: the agent key was rejected. Reconnect the key to resume.",
230
- meta: { kind: "notice" },
231
- });
232
- await this.flush(false).catch(() => undefined);
233
- }
234
- return;
235
- }
236
- await this.backoff(err);
237
- }
238
- }
239
- }
240
- async backoff(err) {
241
- const base = BACKOFF_MS[Math.min(this.failures, BACKOFF_MS.length - 1)];
242
- const asked = err instanceof Retry && err.delayMs !== undefined ? err.delayMs : 0;
243
- const delay = Math.max(base, asked);
244
- this.failures += 1;
245
- logStderr(`agentmesh-mcp: wake retry in ${Math.round(delay / 1000)}s: ${describe(err)}.`);
246
- await sleep(delay, this.opts.signal);
247
- }
248
- // ----- state -----
249
- loadState(identity) {
250
- const file = path.join(this.dir, "state.json");
251
- const saved = readJson(file);
252
- if (saved?.version === 1 && saved.identity?.id === identity.id && saved.identity.workspace_id === identity.workspace_id) {
253
- return { ...saved, identity };
254
- }
255
- return { version: 1, identity, cursor: null, dm: { initialized: false, high: {} }, noticed: [] };
256
- }
257
- save() {
258
- writeAtomic(path.join(this.dir, "state.json"), this.state);
259
- }
260
- itemFile(key) {
261
- return path.join(this.dir, "queue", `${crypto.createHash("sha256").update(key).digest("hex").slice(0, 32)}.json`);
262
- }
263
- enqueue(item) {
264
- const file = this.itemFile(item.key);
265
- if (fs.existsSync(file) || fs.existsSync(file.replace(/\.json$/, ".sending")))
266
- return; // already queued
267
- writeAtomic(file, { ...item, meta: { ...item.meta, event_key: item.key }, queued_at: new Date().toISOString() });
268
- }
269
- queued() {
270
- return fs
271
- .readdirSync(path.join(this.dir, "queue"))
272
- .filter((f) => f.endsWith(".json"))
273
- .map((f) => path.join(this.dir, "queue", f));
274
- }
275
- /** Channel mode: push every queued item oldest first, deleting each after the write. */
276
- async flush(startup) {
277
- if (this.opts.mode !== "channel" || this.opts.push === undefined)
278
- return;
279
- const items = this.queued()
280
- .map((file) => ({ file, item: readJson(file) }))
281
- .filter((x) => x.item !== undefined)
282
- .sort((a, b) => a.item.queued_at.localeCompare(b.item.queued_at));
283
- for (const { file, item } of items) {
284
- await this.opts.push(item, startup);
285
- fs.rmSync(file, { force: true });
286
- }
287
- }
288
- // ----- channel messages via the activity feed -----
289
- async pollActivity() {
290
- const { signal } = this.opts;
291
- let body;
292
- try {
293
- body = (await api("/activity", { since: this.state.cursor ?? "latest", wait: this.state.cursor === null ? 0 : WAIT_S, limit: PAGE }, signal));
294
- }
295
- catch (err) {
296
- if (!(err instanceof CursorExpired))
297
- throw err;
298
- const old = this.state.cursor;
299
- this.enqueue({
300
- key: `gap-${old}-${err.latest}`,
301
- kind: "notice",
302
- content: `agentmesh.md history moved past this session's position (from ${old} to ${err.latest ?? "latest"}). Some mentions may have been missed; check recent messages with read_messages.`,
303
- meta: { kind: "notice", gap_from: String(old), gap_to: String(err.latest ?? "latest") },
304
- });
305
- this.state.cursor = err.latest;
306
- delete this.state.locate;
307
- this.save();
308
- return;
309
- }
310
- if (!Array.isArray(body.events) || typeof body.latest !== "number")
311
- throw new Retry("activity_shape");
312
- if (this.state.cursor === null) {
313
- // First run starts at the present: earlier messages never wake this session.
314
- this.state.cursor = body.latest;
315
- this.save();
316
- return;
317
- }
318
- for (const event of body.events) {
319
- const seq = event["seq"];
320
- if (typeof seq !== "number")
321
- throw new Retry("activity_shape");
322
- if (event["event_type"] === "message.created")
323
- await this.handleMessage(event, seq, signal);
324
- this.state.cursor = seq; // only after any wake for this event is on disk
325
- delete this.state.locate;
326
- this.save();
327
- }
328
- if (body.latest > (this.state.cursor ?? 0)) {
329
- this.state.cursor = body.latest;
330
- this.save();
331
- }
332
- }
333
- async handleMessage(event, seq, signal) {
334
- const payload = (event["payload"] ?? {});
335
- const messageId = payload["message_id"];
336
- const channel = payload["channel"];
337
- if (typeof messageId !== "string" || typeof channel !== "string")
338
- throw new Retry("activity_shape");
339
- const row = await this.locate(seq, channel, messageId, String(event["created_at"] ?? ""), signal);
340
- if (row === null)
341
- return; // deleted before we read it
342
- const bodyMd = typeof row["body_md"] === "string" ? row["body_md"] : "";
343
- const author = `${String(row["author_kind"])}:${String(row["author_id"])}`;
344
- if (author === `agent:${this.state.identity.id}`)
345
- return;
346
- // Direct @name from anyone; @group and channel wakes only from humans, so
347
- // agents cannot start wake storms (same rule as the mesh router).
348
- const human = row["author_kind"] === "human";
349
- let via = "";
350
- if (mentionsAgent(bodyMd, this.state.identity.name))
351
- via = "mention";
352
- else if (human) {
353
- const tagged = mentionedGroups(bodyMd, this.opts.groups ?? []);
354
- if (tagged.length > 0)
355
- via = `group:${tagged[0]}`;
356
- else if (this.opts.wakeChannels?.has(channel.toLowerCase()) === true && !mentionsAnyone(bodyMd))
357
- via = "channel";
358
- }
359
- if (via === "")
360
- return;
361
- if (!this.gate(author, `#${channel}`))
362
- return;
363
- this.enqueue({
364
- key: `${this.origin}|${this.state.identity.workspace_id}|${this.state.identity.id}|seq:${seq}`,
365
- kind: "mention",
366
- content: via === "mention"
367
- ? `${author} mentioned you in #${channel}: ${preview(bodyMd)}`
368
- : via === "channel"
369
- ? `${author} posted in #${channel}: ${preview(bodyMd)}`
370
- : `${author} mentioned @${via.slice(6)} in #${channel}: ${preview(bodyMd)}`,
371
- meta: { kind: "mention", via, channel, message_id: messageId, sender: author, seq: String(seq) },
372
- });
373
- }
374
- /**
375
- * Exact keyset search for one message id; null only after evidence it is
376
- * gone. At most MAX_LOCATE_PAGES per iteration; the page position is saved
377
- * after every page, so a failure or the cap resumes where it stopped.
378
- */
379
- async locate(seq, channel, messageId, eventAt, signal) {
380
- let before = this.state.locate?.seq === seq ? this.state.locate.before : undefined;
381
- for (let pages = 0;; pages += 1) {
382
- if (pages === MAX_LOCATE_PAGES)
383
- throw new Continue("locate_cap");
384
- const page = (await api("/messages", { channel, limit: PAGE, before_id: before }, signal));
385
- if (!Array.isArray(page.messages))
386
- throw new Retry("messages_shape");
387
- const rows = page.messages;
388
- const hit = rows.find((r) => r["id"] === messageId);
389
- if (hit !== undefined)
390
- return hit;
391
- const stamps = rows.map((r) => r["created_at"]).filter((s) => typeof s === "string");
392
- const oldest = stamps.length > 0 ? stamps.reduce((a, b) => (a < b ? a : b)) : null;
393
- if (rows.length === 0 || typeof page.next_before_id !== "string" || (oldest !== null && oldest < eventAt))
394
- return null;
395
- before = page.next_before_id;
396
- this.state.locate = { seq, before };
397
- this.save();
398
- }
399
- }
400
- /** True when the author may wake this session. Untrusted authors get one content-free notice. */
401
- gate(author, where) {
402
- // No list: any workspace member may wake it (only @mentions and DMs reach here).
403
- if (this.opts.trusted.size === 0 || this.opts.trusted.has(author))
404
- return true;
405
- if (!this.state.noticed.includes(author)) {
406
- this.state.noticed.push(author);
407
- this.enqueue({
408
- key: `untrusted-${author}`,
409
- kind: "notice",
410
- content: `A sender not on your trusted senders list (${author}) contacted you in ${where}. Their message is not shown. To accept wakes from them, add "${author}" to the agentmesh trusted senders setting.`,
411
- meta: { kind: "notice", sender: author },
412
- });
413
- this.save();
414
- }
415
- return false;
416
- }
417
- // ----- DMs: participant polling with this agent's own key -----
418
- /** One page of the conversation listing per iteration; the position is saved. */
419
- async pollDms() {
420
- const { signal } = this.opts;
421
- const dm = this.state.dm;
422
- const page = (await api("/conversations", { limit: PAGE, before_id: dm.listBefore }, signal));
423
- if (!Array.isArray(page.conversations))
424
- throw new Retry("conversations_shape");
425
- for (const c of page.conversations) {
426
- const id = c["id"];
427
- if (typeof id !== "string" || !UUID_RE.test(id))
428
- continue;
429
- // A conversation first seen after initialization is new: all of it wakes.
430
- await this.scanConversation(id, dm.high[id], !dm.initialized, signal);
431
- }
432
- if (typeof page.next_before_id === "string") {
433
- dm.listBefore = page.next_before_id;
434
- }
435
- else {
436
- delete dm.listBefore;
437
- dm.initialized = true; // a full listing pass has completed
438
- }
439
- this.save();
440
- }
441
- /**
442
- * Pages a conversation newest-first down to the saved watermark. bootstrap
443
- * records the head without waking. Hitting MAX_DM_PAGES with older pages
444
- * still unread, or never finding the watermark, produces an explicit gap
445
- * notice; nothing is skipped silently.
446
- */
447
- async scanConversation(conversation, high, bootstrap, signal) {
448
- const fresh = [];
449
- let head;
450
- let before;
451
- let complete = false; // reached the watermark, or the conversation's first message
452
- for (let pages = 0; pages < MAX_DM_PAGES; pages += 1) {
453
- const page = (await api(`/conversations/${conversation}/messages`, { limit: PAGE, before_id: before }, signal));
454
- if (!Array.isArray(page.messages))
455
- throw new Retry("dm_messages_shape");
456
- const rows = page.messages; // newest first
457
- if (head === undefined && rows.length > 0)
458
- head = String(rows[0]["id"]);
459
- if (bootstrap) {
460
- complete = true;
461
- break;
462
- }
463
- const at = high === undefined ? -1 : rows.findIndex((r) => r["id"] === high);
464
- fresh.push(...(at === -1 ? rows : rows.slice(0, at)));
465
- if (at !== -1) {
466
- complete = true;
467
- break;
468
- }
469
- if (typeof page.next_before_id !== "string") {
470
- complete = high === undefined; // a known watermark that is gone is a gap
471
- break;
472
- }
473
- before = page.next_before_id;
474
- }
475
- if (head === undefined)
476
- return; // empty conversation
477
- if (!complete) {
478
- this.enqueue({
479
- key: `dmgap-${conversation}-${head}`,
480
- kind: "notice",
481
- content: "Some older direct messages in a conversation could not be read in order; they may have been missed. Check the conversation with read_conversation_messages.",
482
- meta: { kind: "notice", conversation_id: conversation },
483
- });
484
- }
485
- // Oldest first so wakes arrive in conversation order.
486
- for (const row of fresh.reverse()) {
487
- const author = `${String(row["author_kind"])}:${String(row["author_id"])}`;
488
- if (author === `agent:${this.state.identity.id}`)
489
- continue;
490
- if (!this.gate(author, "a direct message"))
491
- continue;
492
- const messageId = String(row["id"]);
493
- this.enqueue({
494
- key: `${this.origin}|${this.state.identity.workspace_id}|${this.state.identity.id}|dm:${conversation}:${messageId}`,
495
- kind: "dm",
496
- content: `${author} sent you a direct message: ${preview(typeof row["body_md"] === "string" ? row["body_md"] : "")}`,
497
- meta: { kind: "dm", conversation_id: conversation, message_id: messageId, sender: author },
498
- });
499
- }
500
- if (this.state.dm.high[conversation] !== head) {
501
- this.state.dm.high[conversation] = head;
502
- this.save();
503
- }
504
- }
505
- }
506
- function describe(err) {
507
- if (err instanceof Stop || err instanceof Retry || err instanceof CursorExpired || err instanceof Continue)
508
- return err.message;
509
- if (err instanceof Error)
510
- return err.name; // never echo API bodies
511
- return "unknown";
512
- }
513
- function sleep(ms, signal) {
514
- return new Promise((resolve) => {
515
- const timer = setTimeout(resolve, ms);
516
- signal.addEventListener("abort", () => {
517
- clearTimeout(timer);
518
- resolve();
519
- }, { once: true });
520
- });
521
- }