agent-coord-mcp 0.26.16 → 0.26.18

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 (79) hide show
  1. package/hooks/replay.mjs +107 -0
  2. package/hooks/tier.mjs +11 -0
  3. package/hooks/tmux-pusher.mjs +27 -0
  4. package/package.json +1 -1
  5. package/scripts/coord-pusher.mjs +16 -32
  6. package/src/server.ts +40 -20
  7. package/src/tools/admin.ts +8 -1
  8. package/src/tools/away.ts +48 -4
  9. package/src/tools/board-ref.ts +47 -2
  10. package/src/tools/messaging.ts +43 -2
  11. package/src/tools/records.ts +381 -25
  12. package/src/tools/registry.ts +5 -2
  13. package/src/tools/rooms.ts +2 -1
  14. package/src/tools/shared.ts +28 -0
  15. package/src/tools/stall.ts +29 -1
  16. package/src/tools/transport.ts +79 -10
  17. package/src/tools/work.ts +70 -4
  18. package/src/tools/worktrees.ts +64 -2
  19. package/src/work.ts +4 -0
  20. package/dist/build.js +0 -113
  21. package/dist/build.js.map +0 -1
  22. package/dist/capabilities.js +0 -158
  23. package/dist/capabilities.js.map +0 -1
  24. package/dist/prefix.js +0 -64
  25. package/dist/prefix.js.map +0 -1
  26. package/dist/roles.js +0 -132
  27. package/dist/roles.js.map +0 -1
  28. package/dist/server-identity.js +0 -82
  29. package/dist/server-identity.js.map +0 -1
  30. package/dist/server.js +0 -625
  31. package/dist/server.js.map +0 -1
  32. package/dist/store.js +0 -553
  33. package/dist/store.js.map +0 -1
  34. package/dist/tools/admin.js +0 -317
  35. package/dist/tools/admin.js.map +0 -1
  36. package/dist/tools/attention.js +0 -73
  37. package/dist/tools/attention.js.map +0 -1
  38. package/dist/tools/away.js +0 -243
  39. package/dist/tools/away.js.map +0 -1
  40. package/dist/tools/board-ref.js +0 -164
  41. package/dist/tools/board-ref.js.map +0 -1
  42. package/dist/tools/event-kinds.js +0 -39
  43. package/dist/tools/event-kinds.js.map +0 -1
  44. package/dist/tools/events.js +0 -234
  45. package/dist/tools/events.js.map +0 -1
  46. package/dist/tools/index.js +0 -14
  47. package/dist/tools/index.js.map +0 -1
  48. package/dist/tools/logwatch.js +0 -85
  49. package/dist/tools/logwatch.js.map +0 -1
  50. package/dist/tools/messaging.js +0 -667
  51. package/dist/tools/messaging.js.map +0 -1
  52. package/dist/tools/record-events.js +0 -380
  53. package/dist/tools/record-events.js.map +0 -1
  54. package/dist/tools/records.js +0 -686
  55. package/dist/tools/records.js.map +0 -1
  56. package/dist/tools/registry.js +0 -497
  57. package/dist/tools/registry.js.map +0 -1
  58. package/dist/tools/render.js +0 -2
  59. package/dist/tools/render.js.map +0 -1
  60. package/dist/tools/rooms.js +0 -210
  61. package/dist/tools/rooms.js.map +0 -1
  62. package/dist/tools/rotate.js +0 -143
  63. package/dist/tools/rotate.js.map +0 -1
  64. package/dist/tools/scopes.js +0 -126
  65. package/dist/tools/scopes.js.map +0 -1
  66. package/dist/tools/shared.js +0 -86
  67. package/dist/tools/shared.js.map +0 -1
  68. package/dist/tools/stall.js +0 -387
  69. package/dist/tools/stall.js.map +0 -1
  70. package/dist/tools/transport.js +0 -1810
  71. package/dist/tools/transport.js.map +0 -1
  72. package/dist/tools/work.js +0 -319
  73. package/dist/tools/work.js.map +0 -1
  74. package/dist/tools/worktrees.js +0 -339
  75. package/dist/tools/worktrees.js.map +0 -1
  76. package/dist/typed-records.js +0 -174
  77. package/dist/typed-records.js.map +0 -1
  78. package/dist/work.js +0 -2
  79. package/dist/work.js.map +0 -1
@@ -1,667 +0,0 @@
1
- import { adjustCursors } from "./admin.js";
2
- import { RECORD_AUTHORITY, isHuman, recordAuthorityFor, resolveRole, roleMatches } from "../roles.js";
3
- import { TYPED_RECORD_CUTOVER_ISO, suggestRecordType, typedRecordGuidance, typedRecordMode, } from "../typed-records.js";
4
- import { ARCHIVE_STATUS_FILE, ARCHIVE_INBOX_DIR, ARCHIVE_ROOMS_DIR, archiveJsonl, archiveInboxFile, archiveRoomFile } from "../store.js";
5
- import { randomUUID } from "node:crypto";
6
- import { existsSync, watch } from "node:fs";
7
- import { promises as fsp } from "node:fs";
8
- import { z } from "zod";
9
- import { readLog } from "./logwatch.js";
10
- import { renderRecord } from "./render.js";
11
- import path from "node:path";
12
- import { AGENTS_FILE, DEFAULT_ROOM, INBOX_DIR, ROOM_FILE, ROOMS_DIR, STATUS_FILE, appendJsonl, cursorFile, ensureRoom, fileSize, getRooms, inboxFile, listInboxFiles, memberRooms, normalizeRoom, readJson, readJsonl, roomFile, stashHistory, retrieveHistory, updateJson, } from "../store.js";
13
- import { sourceFile, getOffset, setOffset, MAX_WAIT_MS, isDecision, } from "./shared.js";
14
- // ---------- send_message ----------
15
- // Typed protocol record (Phase 8). Additive: omitting it reproduces v1
16
- // behavior exactly.
17
- const citationSchema = z.object({
18
- kind: z.enum(["pr", "file", "commit", "url"]),
19
- ref: z.string().min(1),
20
- });
21
- // Payloads are LOOSE objects: a v3 sender's extra keys ride through to disk
22
- // untouched rather than being silently stripped. That is safe precisely
23
- // because payload is nested — it is caller data, and nothing in it is ever
24
- // read as a top-level Message field (which is what keeps a forged `tag` or
25
- // `urgent` out; see the source-level lock in test/tier.test.mjs).
26
- const summaryPayload = z.looseObject({ summary: z.string().min(1) });
27
- // All five fields, or none. A `decision` carrying three of them is
28
- // structurally wrong for the type it claims — and would render as a truncated
29
- // packet, which is worse than no packet.
30
- const decisionPayload = z.looseObject({
31
- title: z.string().min(1),
32
- context: z.string().min(1),
33
- options: z.array(z.string().min(1)).min(1),
34
- recommendation: z.string().min(1),
35
- ifNoAction: z.string().min(1),
36
- });
37
- const verdictPayload = z.looseObject({
38
- result: z.enum(["pass", "fail"]),
39
- headRefOid: z.string().min(1),
40
- notes: z.string().optional(),
41
- });
42
- // Discriminated on `type`, so an unknown type is rejected outright while a
43
- // known type is checked only against its own shape. `payload` is optional on
44
- // every arm: Phase 8 is additive and may not put a new required field on the
45
- // wire. `cites` is optional here too — `done` needs a PR citation, but that is
46
- // enforced in sendMessageTool as a plain {ok:false,error}, mirroring the
47
- // identity-binding rejection, rather than as a schema throw.
48
- export const messageRecordSchema = z.discriminatedUnion("type", [
49
- z.object({ type: z.literal("decision"), payload: decisionPayload.optional(), cites: z.array(citationSchema).optional() }),
50
- z.object({ type: z.literal("verdict"), payload: verdictPayload.optional(), cites: z.array(citationSchema).optional() }),
51
- z.object({ type: z.literal("done"), payload: summaryPayload.optional(), cites: z.array(citationSchema).optional() }),
52
- z.object({ type: z.literal("blocker"), payload: summaryPayload.optional(), cites: z.array(citationSchema).optional() }),
53
- z.object({ type: z.literal("risk"), payload: summaryPayload.optional(), cites: z.array(citationSchema).optional() }),
54
- z.object({ type: z.literal("fyi"), payload: summaryPayload.optional(), cites: z.array(citationSchema).optional() }),
55
- z.object({ type: z.literal("action"), payload: summaryPayload.optional(), cites: z.array(citationSchema).optional() }),
56
- z.object({ type: z.literal("go"), payload: summaryPayload.optional(), cites: z.array(citationSchema).optional() }),
57
- z.object({ type: z.literal("scope"), payload: summaryPayload.optional(), cites: z.array(citationSchema).optional() }),
58
- ]);
59
- // ---------- record authority (Phase 8 Task 4) ----------
60
- // The table (RECORD_AUTHORITY, ../roles.ts) is a floor on the three types
61
- // other agents ACT on; everything else is unrestricted.
62
- //
63
- // NOT A TRUST BOUNDARY. A role is self-declared at register/join (there is no
64
- // authority issuing them), so this is a CONSISTENCY check: it stops a worker
65
- // from accidentally emitting a `verdict` or countersigning its own `scope`,
66
- // the same way a linter stops a typo. Anything that must actually be
67
- // authenticated has to resolve identity-bound tokens (see tokens.json), never
68
- // this table.
69
- // Rejection shape mirrors the identity-binding rejection in server.ts: the
70
- // caller gets a plain `{ok: false, error}`, and nothing is written.
71
- export async function checkRecordAuthority(from, record) {
72
- if (!record)
73
- return { ok: true };
74
- const rule = RECORD_AUTHORITY[record.type];
75
- if (!rule)
76
- return { ok: true };
77
- const reg = await readJson(AGENTS_FILE, {});
78
- const entry = reg[from];
79
- if (roleMatches(entry, rule.roles))
80
- return { ok: true };
81
- const held = resolveRole(entry);
82
- return {
83
- ok: false,
84
- error: `record.type '${record.type}' is restricted to ${rule.label} roles ` +
85
- `(${[...rule.roles].join(", ")}); sender '${from}' holds ` +
86
- `${held ? `role '${held.roleId}'` : entry ? "no role" : "no registry entry"}. ` +
87
- `Send it as text, or register with the role that owns this record type.`,
88
- };
89
- }
90
- // ---------- typed records obligatory (Phase 5.1 Task 12) ----------
91
- // An untyped agent→agent message must not be able to EXIST. Enforced HERE, at
92
- // the send, and not at the render: a rule applied where the message is read
93
- // leaves the untyped message on disk, and the next reader re-derives the type
94
- // from prose. See src/typed-records.ts for the staging, the suggestion rules,
95
- // and why `fyi` stays an honest catch-all.
96
- //
97
- // Returns `undefined` when the send is fine, a WARNING string while the rule is
98
- // staged, or a REFUSAL after the cutover.
99
- //
100
- // TWO EXEMPTIONS, AND THEY ARE DIFFERENT IN KIND:
101
- // - the RECIPIENT is a human. Canon: "David-facing messages may use normal
102
- // prose". Scoped to agent→agent traffic, so the one channel whose reader is
103
- // a person is untouched. Nothing is declared for this — it is a property of
104
- // who is being written to.
105
- // - the SENDER holds a prose-only exemption, declared per agent at join and
106
- // visible in list_agents. That one is a statement about a model's ability
107
- // to pick a type, and it is paid for by every reader.
108
- async function typedRecordCheck(args) {
109
- if (args.record?.type)
110
- return { ok: true };
111
- const reg = await readJson(AGENTS_FILE, {});
112
- // David-facing prose stays prose. An UNREGISTERED recipient is treated as an
113
- // agent, not as a human: the safe reading of "I cannot tell" is the rule, and
114
- // a human on this bus has a registry entry (that is how the pane is found).
115
- if (args.to && isHuman(reg[args.to]))
116
- return { ok: true };
117
- const sender = reg[args.from];
118
- if (sender?.proseOnly)
119
- return { ok: true };
120
- const suggestion = suggestRecordType(args.text, recordAuthorityFor(sender).mayNotEmit);
121
- const guidance = typedRecordGuidance(suggestion);
122
- if (typedRecordMode() === "warn") {
123
- return {
124
- ok: true,
125
- warning: `UNTYPED — stored, but this send is REFUSED from ${TYPED_RECORD_CUTOVER_ISO}. ` +
126
- `${guidance} Until then an untyped multi-line message arrives in full in every reader's context ` +
127
- `instead of one line plus a retrieve_message handle. ` +
128
- `A model that cannot pick a type declares proseOnly:true at join (per-agent, visible in list_agents).`,
129
- };
130
- }
131
- return {
132
- ok: false,
133
- error: `agent→agent messages must carry a typed record (since ${TYPED_RECORD_CUTOVER_ISO}) — nothing was written. ` +
134
- `${guidance} ` +
135
- `Types: decision · verdict · done · blocker · risk · fyi · action · go · scope; 'fyi' is the honest ` +
136
- `catch-all — do not force a false 'decision'/'risk' to get past this. ` +
137
- `Messages TO a human are exempt, and an agent that cannot pick a type declares proseOnly:true at join.`,
138
- };
139
- }
140
- export const sendMessageSchema = {
141
- from: z.string().min(1),
142
- to: z.string().optional(),
143
- room: z.string().optional(),
144
- // Optional ONLY so a record can fill it (Task 3.3). This relaxes a
145
- // constraint rather than adding one, so v1 senders are unaffected; a call
146
- // with neither `text` nor a renderable `record` is rejected in the tool.
147
- text: z.string().min(1).optional(),
148
- kind: z.enum(["decision", "status", "chatter"]).optional(),
149
- record: messageRecordSchema.optional(),
150
- // Additive reply link. Validated in the tool (malformed → {ok:false};
151
- // unknown → store + warn) so the rejection shape matches identity-binding
152
- // / unknown-recipient, not a schema throw. Existing records unchanged.
153
- inReplyTo: z.string().optional(),
154
- };
155
- const MESSAGE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
156
- async function messageIdExists(id) {
157
- const files = [];
158
- for (const n of await listInboxFiles())
159
- files.push(path.join(INBOX_DIR, n));
160
- files.push(ROOM_FILE);
161
- if (existsSync(ROOMS_DIR)) {
162
- for (const n of await fsp.readdir(ROOMS_DIR)) {
163
- if (n.endsWith(".jsonl"))
164
- files.push(path.join(ROOMS_DIR, n));
165
- }
166
- }
167
- if (existsSync(ARCHIVE_INBOX_DIR)) {
168
- for (const n of await fsp.readdir(ARCHIVE_INBOX_DIR)) {
169
- if (n.endsWith(".jsonl"))
170
- files.push(path.join(ARCHIVE_INBOX_DIR, n));
171
- }
172
- }
173
- if (existsSync(ARCHIVE_ROOMS_DIR)) {
174
- for (const n of await fsp.readdir(ARCHIVE_ROOMS_DIR)) {
175
- if (n.endsWith(".jsonl"))
176
- files.push(path.join(ARCHIVE_ROOMS_DIR, n));
177
- }
178
- }
179
- for (const f of files) {
180
- const entries = await readJsonl(f);
181
- if (entries.some((m) => m.id === id))
182
- return true;
183
- }
184
- return false;
185
- }
186
- export async function sendMessageTool(args) {
187
- // Record authority first — a sender who may not emit this type is refused
188
- // before any other check runs, so a rejected record writes nothing anywhere.
189
- const authority = await checkRecordAuthority(args.from, args.record);
190
- if (!authority.ok)
191
- return { ok: false, error: authority.error };
192
- // A `done` must cite the work it claims. Presence and shape only — resolving
193
- // the ref against gh/git is a consumer's job, and the send path makes no
194
- // network calls. Rejected as a value, not a throw, mirroring the
195
- // identity-binding rejection in src/server.ts.
196
- if (args.record?.type === "done") {
197
- const hasPr = (args.record.cites ?? []).some((c) => c.kind === "pr" && c.ref.trim().length > 0);
198
- if (!hasPr) {
199
- return {
200
- ok: false,
201
- error: "a 'done' record must carry at least one {kind:'pr'} citation — an uncited DONE is an unverifiable claim",
202
- };
203
- }
204
- }
205
- // `text` is what every consumer reads, so it must exist. The author's
206
- // wording ALWAYS wins: a record renders only to fill an absent text, never
207
- // to overwrite one.
208
- const text = args.text ?? (args.record ? renderRecord(args.record) : null);
209
- if (!text) {
210
- return {
211
- ok: false,
212
- error: args.record
213
- ? `record type '${args.record.type}' has no payload to render — supply 'text', or a payload the type's layout can render`
214
- : "'text' is required when no record is supplied",
215
- };
216
- }
217
- // After `text` is resolved (a record can fill it) and before anything is
218
- // written, so a refusal leaves nothing on disk.
219
- const typed = await typedRecordCheck({ from: args.from, to: args.to, text, record: args.record });
220
- if (!typed.ok)
221
- return { ok: false, error: typed.error };
222
- const typedWarning = typed.warning;
223
- let replyWarning;
224
- if (args.inReplyTo !== undefined) {
225
- if (!MESSAGE_ID_RE.test(args.inReplyTo)) {
226
- return {
227
- ok: false,
228
- error: `inReplyTo '${args.inReplyTo}' is not a message id (expected uuid)`,
229
- };
230
- }
231
- if (!(await messageIdExists(args.inReplyTo))) {
232
- replyWarning =
233
- `inReplyTo '${args.inReplyTo}' is not a known message — reply stored but no matching parent may exist`;
234
- }
235
- }
236
- // The tmux pusher's injection guard (hooks/tmux-pusher.mjs `shouldInject`)
237
- // never types leading-slash text into a pane — only `send_command`'s
238
- // allowlist goes in raw. The message is still stored and readable, so say so
239
- // here instead of letting the sender assume it landed on screen.
240
- const slashWarning = /^\s*\//.test(text)
241
- ? "text starts with '/' — stored, but tmux-push transports never type leading-slash text into a pane (injection guard); prefix it (e.g. `AGENT_ACTION: run /<skill> …`) or use `send_command` for /clear and /compact"
242
- : undefined;
243
- // DM → inbox. Otherwise resolve the channel (default `general`), make sure it
244
- // exists in the registry, and tag the message with its channel.
245
- if (args.to) {
246
- // A ROOM NAME IN `to:` IS REFUSED, AND THE GUARD SITS ABOVE THE WRITE.
247
- //
248
- // `to: "<room>"` used to append the message to `inbox/<room>.jsonl` — a file
249
- // nothing reads — and return `ok: true`. A coordinator's CANON post landed
250
- // nowhere and it took a stranded file on disk to find it. The ordering IS the
251
- // defect: the append ran BEFORE the registry lookup, so a refusal added after
252
- // the existing check would still have left the message written.
253
- //
254
- // REFUSE rather than warn-and-store, and the distinction is not fussiness: a
255
- // typo'd agent id is a plausible mistake worth a warning, because the id might
256
- // become real. A room name is a CATEGORY ERROR the server can identify with
257
- // certainty — rooms and agents are different namespaces and the confusion is
258
- // one keystroke. Measured when this shipped: zero overlap between room names
259
- // and registered agent ids, so a refusal cannot misfire on a real recipient.
260
- const rooms = await getRooms();
261
- if (Object.prototype.hasOwnProperty.call(rooms, normalizeRoom(args.to))) {
262
- return {
263
- ok: false,
264
- error: `'${args.to}' is a ROOM, not an agent — nothing was written. ` +
265
- `A DM to a room name lands in an inbox no one reads and would have returned ok. ` +
266
- `Post to the channel with room:'${normalizeRoom(args.to)}' (omit 'to'), or name an agent id.`,
267
- };
268
- }
269
- const msg = {
270
- id: randomUUID(),
271
- ts: Date.now(),
272
- from: args.from,
273
- to: args.to,
274
- text,
275
- ...(args.record ? { record: args.record } : {}),
276
- ...(args.inReplyTo ? { inReplyTo: args.inReplyTo } : {}),
277
- };
278
- const target = inboxFile(args.to);
279
- await appendJsonl(target, msg);
280
- // Offline delivery is intentional (the inbox is created on demand), but a
281
- // typo'd recipient shouldn't vanish silently — surface a warning when the
282
- // target isn't a known agent so the caller can catch the mistake.
283
- const reg = await readJson(AGENTS_FILE, {});
284
- const recipientWarning = reg[args.to]
285
- ? undefined
286
- : `recipient '${args.to}' is not a registered agent — message stored in their inbox but no one may be listening`;
287
- const warning = [typedWarning, recipientWarning, replyWarning, slashWarning].filter(Boolean).join("; ") || undefined;
288
- return { ok: true, id: msg.id, target, room: undefined, warning };
289
- }
290
- const chan = normalizeRoom(args.room);
291
- if (chan !== DEFAULT_ROOM)
292
- await ensureRoom(chan, args.from);
293
- const msg = {
294
- id: randomUUID(),
295
- ts: Date.now(),
296
- from: args.from,
297
- room: chan,
298
- text,
299
- ...(args.kind ? { kind: args.kind } : {}),
300
- ...(args.record ? { record: args.record } : {}),
301
- ...(args.inReplyTo ? { inReplyTo: args.inReplyTo } : {}),
302
- };
303
- const target = roomFile(chan);
304
- await appendJsonl(target, msg);
305
- await maybeCompactRoom(chan);
306
- const roomWarning = [typedWarning, replyWarning, slashWarning].filter(Boolean).join("; ") || undefined;
307
- return { ok: true, id: msg.id, target, room: chan, ...(roomWarning ? { warning: roomWarning } : {}) };
308
- }
309
- // ---------- live compaction (self-limiting streams) ----------
310
- // Rooms and the status stream compact themselves on write: once a live file
311
- // grows past its threshold, the oldest entries move to the archive (never
312
- // deleted) and every cursor shifts down. Fresh decisions (< decisionDays old)
313
- // are exempt — they stay in the live file. Cursor adjustment subtracts the
314
- // full removed count, so an agent parked behind a kept decision may re-read
315
- // it once; at-least-once beats silently skipping.
316
- function envInt(name, fallback) {
317
- const n = Number(process.env[name]);
318
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
319
- }
320
- const ROOM_COMPACT_THRESHOLD = envInt("AGENT_COORD_ROOM_MAX", 1000);
321
- const ROOM_COMPACT_KEEP = envInt("AGENT_COORD_ROOM_KEEP", 500);
322
- const STATUS_COMPACT_THRESHOLD = envInt("AGENT_COORD_STATUS_MAX", 2000);
323
- const STATUS_COMPACT_KEEP = envInt("AGENT_COORD_STATUS_KEEP", 1000);
324
- // Skip the entry count entirely while the file is small — the common case on
325
- // every send. ~150 bytes/entry means the threshold can't be hit below this.
326
- const COMPACT_SIZE_GATE = 100 * 1024;
327
- const DECISION_FRESH_MS = 30 * 24 * 60 * 60 * 1000;
328
- async function maybeCompactRoom(chan) {
329
- const file = roomFile(chan);
330
- if ((await fileSize(file)) < COMPACT_SIZE_GATE)
331
- return;
332
- const entries = await readJsonl(file);
333
- if (entries.length <= ROOM_COMPACT_THRESHOLD)
334
- return;
335
- const boundaryTs = entries[entries.length - ROOM_COMPACT_KEEP].ts;
336
- const decisionCutoff = Date.now() - DECISION_FRESH_MS;
337
- const r = await archiveJsonl(file, archiveRoomFile(chan), (e) => e.ts >= boundaryTs || (isDecision(e) && e.ts > decisionCutoff));
338
- if (r.removed > 0)
339
- await adjustCursors({ roomRemovedByChan: { [chan]: r.removed } });
340
- }
341
- async function maybeCompactStatus() {
342
- if ((await fileSize(STATUS_FILE)) < COMPACT_SIZE_GATE)
343
- return;
344
- const entries = await readJsonl(STATUS_FILE);
345
- if (entries.length <= STATUS_COMPACT_THRESHOLD)
346
- return;
347
- const boundaryTs = entries[entries.length - STATUS_COMPACT_KEEP].ts;
348
- const r = await archiveJsonl(STATUS_FILE, ARCHIVE_STATUS_FILE, (e) => e.ts >= boundaryTs);
349
- if (r.removed > 0)
350
- await adjustCursors({ statusRemoved: r.removed });
351
- }
352
- // ---------- read_messages ----------
353
- export const readMessagesSchema = {
354
- agentId: z.string().min(1),
355
- source: z.enum(["inbox", "room", "status"]),
356
- room: z.string().optional(),
357
- limit: z.number().int().positive().max(500).optional(),
358
- peek: z.boolean().optional(),
359
- sinceTs: z.number().optional(),
360
- };
361
- export async function readMessagesTool(args) {
362
- const file = sourceFile(args.source, args.agentId, args.room);
363
- const all = await readJsonl(file);
364
- let entries = [];
365
- let totalNew = 0;
366
- // Room and status reads default to 50 entries to prevent agents flooding
367
- // themselves with full history on join — the status stream grows unbounded
368
- // across the fleet. Inbox drains fully since it is targeted by nature.
369
- const effectiveLimit = args.limit ?? (args.source === "inbox" ? undefined : 50);
370
- if (args.peek) {
371
- const cursor = await readJson(cursorFile(args.agentId), {});
372
- const startOffset = getOffset(cursor, args.source, args.room);
373
- entries = all.slice(startOffset);
374
- if (args.sinceTs !== undefined)
375
- entries = entries.filter((e) => e.ts > args.sinceTs);
376
- totalNew = entries.length;
377
- }
378
- else {
379
- await updateJson(cursorFile(args.agentId), {}, (current) => {
380
- const startOffset = getOffset(current, args.source, args.room);
381
- let e = all.slice(startOffset);
382
- if (args.sinceTs !== undefined)
383
- e = e.filter((x) => x.ts > args.sinceTs);
384
- totalNew = e.length;
385
- entries = e;
386
- // Advance past EVERYTHING we account for here (recent window + any
387
- // overflow we stash below). The overflow is recoverable via the history
388
- // hash, so it must not requeue for the next read — that would re-flood.
389
- if (e.length > 0)
390
- setOffset(current, args.source, args.room, startOffset + e.length);
391
- return current;
392
- });
393
- }
394
- // CCR overflow handling (room and status sources). When the backlog exceeds
395
- // the window, return the RECENT slice raw and replace the older overflow with
396
- // a compact digest carrying a retrieval hash. The agent expands it on demand
397
- // via retrieve_room_history. Peek is side-effect-free, so it never stashes —
398
- // it reports the count and tells the agent to do a real read to get a hash.
399
- let recent = entries;
400
- let history;
401
- if (args.source !== "inbox" && effectiveLimit && entries.length > effectiveLimit) {
402
- const overflow = entries.slice(0, entries.length - effectiveLimit);
403
- recent = entries.slice(entries.length - effectiveLimit);
404
- const stashKey = args.source === "room" ? normalizeRoom(args.room) : "status";
405
- if (args.peek) {
406
- history = { digest: digestOverflow(overflow, undefined), older: overflow.length };
407
- }
408
- else {
409
- const hash = await stashHistory(stashKey, args.agentId, overflow);
410
- history = { digest: digestOverflow(overflow, hash), hash, older: overflow.length };
411
- }
412
- }
413
- else if (effectiveLimit && entries.length > effectiveLimit) {
414
- // Inbox keeps the legacy oldest-first chunking (no stash) — targeted
415
- // messages must never be skipped over.
416
- recent = entries.slice(0, effectiveLimit);
417
- }
418
- // Drop the agent's own posts on shared channels — reading your own broadcast
419
- // back is never useful and confuses turn-based agents into self-replies.
420
- // Cursor has already advanced past them, so they won't reappear.
421
- const visible = args.source === "room" || args.source === "status"
422
- ? recent.filter((e) => entryAuthor(e) !== args.agentId)
423
- : recent;
424
- return {
425
- ok: true,
426
- messages: visible,
427
- totalNew,
428
- returned: visible.length,
429
- room: args.source === "room" ? normalizeRoom(args.room) : undefined,
430
- ...(history ? { history } : {}),
431
- };
432
- }
433
- // Lossless summary of a stashed backlog slice: surfaces error/failure posts
434
- // verbatim (the lines that usually matter most in a flood) and collapses the
435
- // rest to counts. Mirrors headroom's content-aware digest, kept deliberately
436
- // simple — the full originals are one retrieve_room_history call away.
437
- function digestOverflow(over, hash) {
438
- const authors = new Set(over.map(entryAuthor).filter(Boolean));
439
- const errorRe = /\b(error|fatal|fail(ed|ure)?|panic|exception)\b/i;
440
- const errors = over.filter((m) => errorRe.test(JSON.stringify(m)));
441
- const first = over[0]?.ts;
442
- const last = over[over.length - 1]?.ts;
443
- const span = first && last && last > first ? ` over ${Math.round((last - first) / 60000)}m` : "";
444
- const parts = [
445
- `[${over.length} earlier message${over.length === 1 ? "" : "s"} compressed`,
446
- `${authors.size} agent${authors.size === 1 ? "" : "s"}${span}`,
447
- ];
448
- if (errors.length)
449
- parts.push(`${errors.length} error post${errors.length === 1 ? "" : "s"}`);
450
- const head = parts.join(", ");
451
- const tail = hash
452
- ? ` hash=${hash}] — call retrieve_room_history(hash="${hash}") to expand`
453
- : `] — read without peek to get an expandable hash`;
454
- // Decisions are the one thing a digest must not bury — quote them verbatim
455
- // (capped) below the summary line.
456
- const decisions = over.filter((m) => isDecision(m));
457
- const quoted = decisions
458
- .slice(-5)
459
- .map((d) => ` [decision] ${d.from}: ${d.text.length > 200 ? d.text.slice(0, 200) + "…" : d.text}`);
460
- const decisionBlock = decisions.length
461
- ? `\n${quoted.join("\n")}${decisions.length > 5 ? `\n (+${decisions.length - 5} earlier decisions in hash)` : ""}`
462
- : "";
463
- return head + tail + decisionBlock;
464
- }
465
- // ---------- retrieve_message (Phase 8 Task 6) ----------
466
- export const retrieveMessageSchema = {
467
- agentId: z.string().min(1),
468
- id: z.string().min(1),
469
- };
470
- // Expand a digest handle back into the full typed record.
471
- //
472
- // NOT a cache. The handle is the message's own `id`, and this reads the source
473
- // of truth — rooms/<chan>.jsonl or inbox/<agent>.jsonl. That matters for two
474
- // reasons the CCR history cache could not offer: nothing is duplicated, and
475
- // nothing expires. A stashed copy would have carried HISTORY_TTL_MS and become
476
- // permanently unrecoverable after 30 minutes, which is exactly when a handle
477
- // that outlived a /clear would be expanded.
478
- //
479
- // It also sidesteps the cursor: the pusher SHARES the cursor file with
480
- // read_messages, so anything already delivered to a pane is behind the cursor
481
- // and re-reading the channel would not return it. A by-id lookup never
482
- // consults a cursor.
483
- //
484
- // AUTHORITY BY CONSTRUCTION: we only ever open files this agent is entitled to
485
- // read — its own inbox, and the rooms it is a member of. There is no separate
486
- // permission check that could disagree with the search, and a handle for a
487
- // message delivered somewhere else simply is not found. That is the same
488
- // property the history cache spent `forAgent` scoping to get.
489
- export async function retrieveMessageTool(args) {
490
- const rooms = await memberRooms(args.agentId);
491
- const scopes = [
492
- {
493
- source: "inbox",
494
- room: undefined,
495
- live: inboxFile(args.agentId),
496
- archived: archiveInboxFile(args.agentId),
497
- },
498
- ...rooms.map((r) => ({
499
- source: "room",
500
- room: r,
501
- live: roomFile(r),
502
- archived: archiveRoomFile(r),
503
- })),
504
- ];
505
- // Live files first. The archive is opened ONLY on a miss, so no normal
506
- // retrieval touches it and compaction/prune semantics are unchanged — but a
507
- // record that compaction moved is still recoverable, because archive/ is
508
- // append-only and complete.
509
- for (const pass of ["live", "archived"]) {
510
- for (const s of scopes) {
511
- const entries = await readJsonl(s[pass]);
512
- const msg = entries.find((m) => m.id === args.id);
513
- if (msg) {
514
- return {
515
- ok: true,
516
- id: msg.id,
517
- source: s.source,
518
- room: s.room,
519
- archived: pass === "archived",
520
- message: msg,
521
- record: msg.record,
522
- };
523
- }
524
- }
525
- }
526
- return {
527
- ok: false,
528
- error: `no message '${args.id}' in any channel you can read — it may never have been delivered to you`,
529
- };
530
- }
531
- // ---------- retrieve_room_history ----------
532
- export const retrieveRoomHistorySchema = {
533
- agentId: z.string().min(1),
534
- hash: z.string().min(1),
535
- query: z.string().optional(),
536
- };
537
- export async function retrieveRoomHistoryTool(args) {
538
- const res = await retrieveHistory(args.hash, args.agentId, args.query);
539
- if (!res.ok) {
540
- const reason = res.reason === "expired"
541
- ? "That history entry has expired (30m TTL). Re-read the channel with a higher limit to fetch it again."
542
- : res.reason === "forbidden"
543
- ? "That history hash was produced for a different agent and cannot be retrieved by you."
544
- : "No history entry for that hash. It may have expired or never existed.";
545
- return { ok: false, reason: res.reason, message: reason };
546
- }
547
- return {
548
- ok: true,
549
- room: res.room,
550
- hash: args.hash,
551
- total: res.total,
552
- returned: res.messages.length,
553
- messages: res.messages,
554
- };
555
- }
556
- function entryAuthor(e) {
557
- return "from" in e ? e.from : e.agentId;
558
- }
559
- // ---------- post_status ----------
560
- export const postStatusSchema = {
561
- agentId: z.string().min(1),
562
- status: z.string().min(1),
563
- detail: z.string().optional(),
564
- };
565
- export async function postStatusTool(args) {
566
- const entry = {
567
- id: randomUUID(),
568
- ts: Date.now(),
569
- agentId: args.agentId,
570
- status: args.status,
571
- detail: args.detail,
572
- };
573
- await appendJsonl(STATUS_FILE, entry);
574
- await maybeCompactStatus();
575
- return { ok: true, id: entry.id };
576
- }
577
- // ---------- wait_for_message ----------
578
- export const waitForMessageSchema = {
579
- agentId: z.string().min(1),
580
- source: z.enum(["inbox", "room", "status"]),
581
- room: z.string().optional(),
582
- timeoutMs: z.number().int().positive().max(MAX_WAIT_MS).optional(),
583
- };
584
- export async function waitForMessageTool(args) {
585
- const totalTimeout = Math.min(args.timeoutMs ?? 30_000, MAX_WAIT_MS);
586
- const file = sourceFile(args.source, args.agentId, args.room);
587
- const deadline = Date.now() + totalTimeout;
588
- // Loop so that file growth caused only by the agent's own self-posts (which
589
- // readMessagesTool now filters out for room/status) doesn't return an empty
590
- // result — keep waiting until we have something to deliver or time out.
591
- while (Date.now() < deadline) {
592
- // ALREADY-UNREAD CONTENT WAKES THIS IMMEDIATELY.
593
- //
594
- // The loop below waits for the file to GROW from the size captured at entry,
595
- // so anything that arrived before the wait started could not wake it: the
596
- // agent sat through the full timeout with messages readable the whole time.
597
- // Seven real posts landed across consecutive 60s waits that all returned
598
- // `timedOut`, while `read_messages` returned every one.
599
- //
600
- // Growth is the wrong question on its own — "is there anything for me" is
601
- // the right one, and it is also the cheaper check.
602
- const pending = await readMessagesTool({ agentId: args.agentId, source: args.source, room: args.room });
603
- if (pending.messages.length > 0)
604
- return { ...pending, waited: true, timedOut: false };
605
- // 8.4 — THE SAME POSITION THE WATCH USES, not a second mechanism beside it.
606
- //
607
- // This compared byte SIZE, which answers "did the file grow" — a proxy for
608
- // "is there a new line". The watch keys on LINE OFFSET, which is the thing
609
- // itself, and reusing it means the wait and the watch cannot disagree about
610
- // what "new" means. A second mechanism beside the first is how two answers
611
- // to one question start drifting.
612
- //
613
- // It still consumes nothing by itself: the offset is read, never written
614
- // back to the cursor (8.2).
615
- const startLines = readLog(file).total;
616
- const startSize = await fileSize(file);
617
- const remaining = deadline - Date.now();
618
- if (remaining <= 0)
619
- break;
620
- const changed = await new Promise((resolve) => {
621
- let settled = false;
622
- const finish = (v) => {
623
- if (settled)
624
- return;
625
- settled = true;
626
- clearInterval(poll);
627
- try {
628
- watcher?.close();
629
- }
630
- catch {
631
- // ignore
632
- }
633
- clearTimeout(t);
634
- resolve(v);
635
- };
636
- const check = async () => {
637
- // Line count first — a write that changes bytes without adding a line
638
- // (a rewrite, a truncation) is not new traffic, and size alone reports
639
- // it as such.
640
- if (readLog(file).total > startLines)
641
- return finish(true);
642
- const sz = await fileSize(file);
643
- if (sz > startSize)
644
- finish(true);
645
- };
646
- let watcher;
647
- try {
648
- watcher = watch(file, () => {
649
- void check();
650
- });
651
- }
652
- catch {
653
- // file may not exist; polling will handle
654
- }
655
- const poll = setInterval(() => void check(), 500);
656
- const t = setTimeout(() => finish(false), remaining);
657
- });
658
- if (!changed)
659
- break;
660
- const result = await readMessagesTool({ agentId: args.agentId, source: args.source, room: args.room });
661
- if (result.returned > 0)
662
- return result;
663
- // otherwise, only self-posts arrived; keep waiting on the remaining budget
664
- }
665
- return { ok: false, timedOut: true };
666
- }
667
- //# sourceMappingURL=messaging.js.map