@unagents/messenger-protocol 0.0.0-stage → 0.10.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.
@@ -0,0 +1,561 @@
1
+ /**
2
+ * Protocol constants shared by broker, client and CLI.
3
+ *
4
+ * Values are transcribed from the current JavaScript implementation
5
+ * (`legacy/src/config.js`, `legacy/src/broker.js`, `legacy/src/server.js`). Do not change them here
6
+ * without changing the implementation on both ends.
7
+ */
8
+ /** Broker HTTP listen port (`AGENT_MESSENGER_PORT` default). */
9
+ declare const DEFAULT_HTTP_PORT = 7901;
10
+ /** Broker HTTP bind address (`AGENT_MESSENGER_BIND` default). */
11
+ declare const DEFAULT_BIND = "0.0.0.0";
12
+ /** UDP discovery port (`AGENT_MESSENGER_DISCOVERY_PORT` default). */
13
+ declare const DEFAULT_DISCOVERY_PORT = 7902;
14
+ /** How long a client waits for discovery answers (`AGENT_MESSENGER_DISCOVERY_TIMEOUT_MS` default). */
15
+ declare const DEFAULT_DISCOVERY_TIMEOUT_MS = 1000;
16
+ /** Client heartbeat interval (`AGENT_MESSENGER_HEARTBEAT_MS` default). */
17
+ declare const HEARTBEAT_INTERVAL_MS = 15000;
18
+ /** Broker drops a peer whose `last_seen` is older than this. Not configurable. */
19
+ declare const HEARTBEAT_TIMEOUT_MS = 60000;
20
+ /** Client `/poll-messages` interval. Not configurable. */
21
+ declare const POLL_INTERVAL_MS = 1000;
22
+ /** Loopback hosts treated as "local broker" by the client resolver. */
23
+ declare const LOCAL_HOSTS: readonly ["127.0.0.1", "localhost", "::1"];
24
+ /**
25
+ * Environment variable names. Source of truth: `legacy/src/config.js`
26
+ * (`DELIVERY` lives in `legacy/src/server.js`).
27
+ */
28
+ declare const ENV: {
29
+ /** Explicit broker host. `"auto"` or unset = resolve by config / discovery / local. */
30
+ readonly HOST: "AGENT_MESSENGER_HOST";
31
+ /** Broker HTTP port (client target / broker listen). */
32
+ readonly PORT: "AGENT_MESSENGER_PORT";
33
+ /** Broker bind address. */
34
+ readonly BIND: "AGENT_MESSENGER_BIND";
35
+ /** Bearer token; when set, every POST must carry `Authorization: Bearer <token>`. */
36
+ readonly TOKEN: "AGENT_MESSENGER_TOKEN";
37
+ /** Peer name for this session. */
38
+ readonly NAME: "AGENT_MESSENGER_NAME";
39
+ /** Broker id shown in `/health` and discovery replies (default hostname). */
40
+ readonly BROKER_ID: "AGENT_MESSENGER_BROKER_ID";
41
+ /** Broker state file (default `~/.agent-messenger/broker.json`). */
42
+ readonly STATE: "AGENT_MESSENGER_STATE";
43
+ /** Client config file (default `~/.agent-messenger/config.json`). */
44
+ readonly CONFIG: "AGENT_MESSENGER_CONFIG";
45
+ /** `"off"` disables UDP discovery (broker responder and client probe). */
46
+ readonly DISCOVERY: "AGENT_MESSENGER_DISCOVERY";
47
+ /** UDP discovery port. */
48
+ readonly DISCOVERY_PORT: "AGENT_MESSENGER_DISCOVERY_PORT";
49
+ /** Discovery probe target address. */
50
+ readonly DISCOVERY_ADDR: "AGENT_MESSENGER_DISCOVERY_ADDR";
51
+ /** Discovery answer wait time in ms. */
52
+ readonly DISCOVERY_TIMEOUT_MS: "AGENT_MESSENGER_DISCOVERY_TIMEOUT_MS";
53
+ /** Client heartbeat interval in ms. */
54
+ readonly HEARTBEAT_MS: "AGENT_MESSENGER_HEARTBEAT_MS";
55
+ /** Inbound delivery mode: `"auto"` (default) / `"socket"` / `"channel"`. */
56
+ readonly DELIVERY: "AGENT_MESSENGER_DELIVERY";
57
+ };
58
+ type EnvName = (typeof ENV)[keyof typeof ENV];
59
+ /**
60
+ * Extra POST routes of the protocol registry. Like `RELAY_ROUTE`, not part of `BROKER_POST_ROUTES`
61
+ * (that table mirrors the legacy broker); request / response shapes are `ProtocolRouteMap` in `http.ts`.
62
+ */
63
+ declare const PROTOCOL_ROUTES: readonly ["/set-protocol", "/unset-protocol", "/get-protocol"];
64
+ type ProtocolRoute = (typeof PROTOCOL_ROUTES)[number];
65
+ /** Max size of `protocol.json` (UTF-8 bytes). */
66
+ declare const PROTOCOL_MANIFEST_MAX_BYTES: number;
67
+ /** Max size of `PROTOCOL.md` (UTF-8 bytes). */
68
+ declare const PROTOCOL_DOC_MAX_BYTES: number;
69
+ /** Max size of manifest + doc together (UTF-8 bytes). */
70
+ declare const PROTOCOL_TOTAL_MAX_BYTES: number;
71
+ /** Max number of `(name, version)` definitions one broker holds; more is `LIMIT`. */
72
+ declare const PROTOCOL_MAX_STORED = 256;
73
+ /** Max length (characters) of each of `meta.protocol` and `meta.version`. */
74
+ declare const PROTOCOL_META_MAX_LENGTH = 128;
75
+ /** Valid protocol `name`. */
76
+ declare const PROTOCOL_NAME_PATTERN: RegExp;
77
+ /**
78
+ * Error `code`s of the protocol feature (design 7.2). `NO_TAG` is not listed: a repo without tags is
79
+ * not an error (`0.0.0+<sha7>`). Raised by the broker: HASH_MISMATCH, PROTOCOL_CONFLICT, LIMIT,
80
+ * PROTOCOL_NOT_FOUND, and TOO_LARGE / INVALID_DEFINITION on re-check. The rest are raised by the client.
81
+ */
82
+ declare const PROTOCOL_ERROR_CODES: readonly ["REPO_UNREACHABLE", "UNSUPPORTED_REPO", "VERSION_NOT_FOUND", "INVALID_DEFINITION", "VERSION_MISMATCH", "TOO_LARGE", "HASH_MISMATCH", "PROTOCOL_CONFLICT", "LIMIT", "PROTOCOL_NOT_FOUND", "BROKER_UNSUPPORTED", "INVALID_META"];
83
+ type ProtocolErrorCode = (typeof PROTOCOL_ERROR_CODES)[number];
84
+
85
+ /**
86
+ * Broker HTTP API — request / response JSON shapes.
87
+ *
88
+ * Transcribed from `legacy/src/broker.js` (handlers) and `legacy/src/server.js` /
89
+ * `legacy/bin/agent-messenger.js` (callers). Field optionality follows the broker:
90
+ * a field the broker defaults with `??` is optional here.
91
+ *
92
+ * Transport rules (from `legacy/src/broker.js` `startBroker`):
93
+ * - `GET /health` is the only GET route.
94
+ * - Every other route is `POST` with a JSON body; empty body is treated as `{}`.
95
+ * - When the broker has a token, each POST must send `Authorization: Bearer <token>`,
96
+ * otherwise `401 {"error":"unauthorized"}`.
97
+ * - Unknown POST path: `404 {"error":"not found"}`. Handler exception: `500 {"error":<message>}`.
98
+ * - Any other method: `200 text/plain` `agent-messenger broker <version>\n`.
99
+ */
100
+
101
+ /** A registered session as stored and returned by the broker. */
102
+ interface Peer {
103
+ /** 8-char broker-generated id (`[a-z0-9]`). */
104
+ id: string;
105
+ /** Stable name set via `/register` or `/set-name`; `""` when unset. */
106
+ name: string;
107
+ /** Client process id. */
108
+ pid: number;
109
+ hostname: string;
110
+ cwd: string;
111
+ git_root: string | null;
112
+ tty: string | null;
113
+ summary: string;
114
+ /** ISO 8601 timestamp. */
115
+ registered_at: string;
116
+ /** ISO 8601 timestamp; refreshed by `/heartbeat`. */
117
+ last_seen: string;
118
+ /**
119
+ * Mesh only: id of the permanent broker this peer is registered with, set on
120
+ * copies a mesh broker replicated from another one. Absent for peers that
121
+ * registered directly. Never returned by `/list-peers`.
122
+ */
123
+ origin?: string;
124
+ /**
125
+ * Protocols this peer serves (`/set-protocol`, re-sent on `/register` and `/heartbeat`). Hash only; the
126
+ * definition body lives in the broker's protocol store. Absent when none (and from 0.9.x brokers).
127
+ */
128
+ protocols?: ProtocolDecl[];
129
+ }
130
+ /** A protocol a peer declares: identity (`name` + `version`) and the hash of its definition body. */
131
+ interface ProtocolDecl {
132
+ /** `^[a-z0-9][a-z0-9._-]{0,63}$` (`PROTOCOL_NAME_PATTERN`). */
133
+ name: string;
134
+ /** semver, or `0.0.0+<sha7>` for a repo without tags. */
135
+ version: string;
136
+ /** `sha256(canonicalJSON({manifest, doc}))` as lower-case hex. */
137
+ hash: string;
138
+ }
139
+ /** The definition body a server fetched from its protocol repo. */
140
+ interface ProtocolDefinition {
141
+ /** Parsed `protocol.json`. */
142
+ manifest: object;
143
+ /** `PROTOCOL.md` text; `""` when the repo has none. */
144
+ doc: string;
145
+ /** Normalized repo notation (`github:o/r`, `gitea:<base>/o/r`, `file:<abs path>`). Not part of the hash. */
146
+ source: string;
147
+ /** tag or sha the body was read at (`local` for a local path). Not part of the hash. */
148
+ ref: string;
149
+ }
150
+ /** What the broker keeps per `(name, version)`. */
151
+ interface StoredProtocol extends ProtocolDecl {
152
+ definition: ProtocolDefinition;
153
+ /** ISO 8601 timestamp of the first successful `/set-protocol` for this `(name, version)`. */
154
+ registered_at: string;
155
+ }
156
+ /** Protocol tag of a message: which protocol (and version) the sender spoke. Both fields are required when present. */
157
+ interface MessageMeta {
158
+ protocol: string;
159
+ version: string;
160
+ }
161
+ type MessageMode = "pull" | "push" | "ping";
162
+ /** A message as stored and returned by the broker. */
163
+ interface Message {
164
+ /** Broker-assigned incrementing integer. */
165
+ id: number;
166
+ /** Sender peer id, or `"cli"` when sent from the CLI. */
167
+ from_id: string;
168
+ from_name: string;
169
+ to_id: string;
170
+ text: string;
171
+ /**
172
+ * How the receiver shows it: `"pull"` = unread notice only, text via
173
+ * `check_messages`; `"push"` = text shown directly; `"ping"` = liveness
174
+ * notice; `text` is its optional subject (e.g. a task id), `""` when none. Missing (older broker / sender) means `"pull"`.
175
+ */
176
+ mode?: MessageMode;
177
+ /** ISO 8601 timestamp. */
178
+ sent_at: string;
179
+ /** 0 until returned by `/poll-messages`, then 1. */
180
+ delivered: 0 | 1;
181
+ /** Always 0 in the current implementation (acknowledged messages are deleted). */
182
+ acknowledged: 0 | 1;
183
+ /** Mesh only: `<sender broker id>:<id there>` of a message forwarded by another broker (duplicate guard). */
184
+ mesh_key?: string;
185
+ /** Protocol tag given to `/send-message`; returned by `/poll-messages` and kept across relay / mesh forwarding. */
186
+ meta?: MessageMeta;
187
+ }
188
+ /** `/list-peers` scope filter. Unknown values behave as `"all"`. */
189
+ type PeerScope = "all" | "host" | "directory" | "repo";
190
+ /** Generic `{ok:true}` / `{ok:false,error}` result. */
191
+ type OkResult = {
192
+ ok: true;
193
+ } | {
194
+ ok: false;
195
+ error: string;
196
+ };
197
+ /** Body of a non-2xx broker response. */
198
+ interface BrokerErrorResponse {
199
+ error: string;
200
+ }
201
+ interface HealthResponse {
202
+ status: "ok";
203
+ /** Broker package version. */
204
+ version: string;
205
+ /** Broker id (`AGENT_MESSENGER_BROKER_ID`, default hostname). */
206
+ id: string;
207
+ /** Broker HTTP port. */
208
+ port: number;
209
+ /** Count of peers seen within `HEARTBEAT_TIMEOUT_MS`. */
210
+ peers: number;
211
+ /** Present (`true`) only when the broker was started as a local fallback (`AGENT_MESSENGER_FALLBACK=1`). */
212
+ fallback?: true;
213
+ }
214
+ interface RegisterRequest {
215
+ pid: number;
216
+ hostname?: string;
217
+ cwd?: string;
218
+ git_root?: string | null;
219
+ tty?: string | null;
220
+ summary?: string;
221
+ name?: string;
222
+ /** Protocols to declare right away (hash only; bodies follow via `/set-protocol`). */
223
+ protocols?: ProtocolDecl[];
224
+ }
225
+ interface RegisterResponse {
226
+ id: string;
227
+ }
228
+ interface HeartbeatRequest {
229
+ id: string;
230
+ /** Every protocol the peer currently serves (hash only), sent on each heartbeat. */
231
+ protocols?: ProtocolDecl[];
232
+ }
233
+ /**
234
+ * `ok:false` with `"unknown peer (re-register)"` when the broker does not know the id.
235
+ * `resend` lists the `"name@version"` of declared protocols whose body the broker does not hold; the client answers
236
+ * with `/set-protocol`. Absent when nothing is missing (and from 0.9.x brokers).
237
+ */
238
+ type HeartbeatResponse = {
239
+ ok: true;
240
+ resend?: string[];
241
+ } | {
242
+ ok: false;
243
+ error: string;
244
+ };
245
+ interface SetSummaryRequest {
246
+ id: string;
247
+ summary?: string;
248
+ }
249
+ type SetSummaryResponse = OkResult;
250
+ interface SetNameRequest {
251
+ id: string;
252
+ name?: string;
253
+ }
254
+ type SetNameResponse = OkResult;
255
+ interface ListPeersRequest {
256
+ scope?: PeerScope;
257
+ /** Used by scope `"host"`. */
258
+ hostname?: string;
259
+ /** Used by scope `"directory"`, and by `"repo"` when `git_root` is empty. */
260
+ cwd?: string;
261
+ /** Used by scope `"repo"`. */
262
+ git_root?: string | null;
263
+ /** Peer id to omit from the result (the caller itself). */
264
+ exclude_id?: string;
265
+ /** Only peers that declare this protocol (AND with `scope`). */
266
+ protocol?: string;
267
+ /** Only with `protocol`: only peers that declare exactly this version. */
268
+ version?: string;
269
+ }
270
+ type ListPeersResponse = Peer[];
271
+ interface SendMessageRequest {
272
+ /** Target peer id or unique peer name. */
273
+ to: string;
274
+ /** Defaults to `"cli"`. */
275
+ from_id?: string;
276
+ from_name?: string;
277
+ text?: string;
278
+ /** Defaults to `"pull"`. Unknown values are rejected. */
279
+ mode?: MessageMode;
280
+ /** Protocol tag. Both fields must be strings of at most `PROTOCOL_META_MAX_LENGTH` characters. */
281
+ meta?: MessageMeta;
282
+ }
283
+ type SendMessageResponse = {
284
+ ok: true;
285
+ to_id: string;
286
+ to_name: string;
287
+ message_id: number;
288
+ } | {
289
+ ok: false;
290
+ error: string;
291
+ };
292
+ interface PollMessagesRequest {
293
+ id: string;
294
+ }
295
+ /** Undelivered messages for `id`; each is marked `delivered: 1` on return. */
296
+ interface PollMessagesResponse {
297
+ messages: Message[];
298
+ }
299
+ interface AcknowledgeMessagesRequest {
300
+ id: string;
301
+ message_ids?: number[];
302
+ }
303
+ type AcknowledgeMessagesResponse = {
304
+ ok: true;
305
+ };
306
+ interface GetBufferedMessagesRequest {
307
+ id: string;
308
+ }
309
+ /** Messages for `id` with `delivered: 1` and `acknowledged: 0`. */
310
+ interface GetBufferedMessagesResponse {
311
+ messages: Message[];
312
+ }
313
+ interface UnregisterRequest {
314
+ id: string;
315
+ }
316
+ type UnregisterResponse = {
317
+ ok: true;
318
+ };
319
+ /** One undelivered message handed over by a fallback broker. The recipient is addressed by name: peer ids are broker-local. */
320
+ interface RelayedMessage {
321
+ from_id: string;
322
+ from_name: string;
323
+ /** Recipient peer name on the sending broker. Items without a name cannot be relayed. */
324
+ to_name: string;
325
+ /** Recipient hostname on the sending broker; narrows ambiguous names. */
326
+ to_hostname?: string;
327
+ text: string;
328
+ mode?: MessageMode;
329
+ sent_at: string;
330
+ meta?: MessageMeta;
331
+ }
332
+ interface RelayMessagesRequest {
333
+ messages: RelayedMessage[];
334
+ }
335
+ /** `delivered` = queued for a registered peer, `queued` = held until a peer of that name registers, `dropped` = no usable name. */
336
+ interface RelayMessagesResponse {
337
+ ok: true;
338
+ delivered: number;
339
+ queued: number;
340
+ dropped: number;
341
+ }
342
+ /** Extra POST route served by the TypeScript broker. Not in `BROKER_POST_ROUTES` (that table mirrors the legacy broker). */
343
+ declare const RELAY_ROUTE: "/relay-messages";
344
+ /** `{ok:false}` answer of the protocol routes; `code` is one of `PROTOCOL_ERROR_CODES`. */
345
+ interface ProtocolErrorResponse {
346
+ ok: false;
347
+ error: string;
348
+ code: ProtocolErrorCode;
349
+ /** `PROTOCOL_CONFLICT`: hash the broker already holds for this `(name, version)`. */
350
+ existing_hash?: string;
351
+ /** `PROTOCOL_CONFLICT`: servers (`name@host`) that hold it. */
352
+ servers?: string[];
353
+ /** `PROTOCOL_NOT_FOUND`: versions the broker does hold for the name (may be empty). */
354
+ versions?: string[];
355
+ }
356
+ interface SetProtocolRequest {
357
+ /** Peer id of the server. */
358
+ id: string;
359
+ name: string;
360
+ version: string;
361
+ /** Re-computed by the broker; a different value is `HASH_MISMATCH`. */
362
+ hash: string;
363
+ definition: ProtocolDefinition;
364
+ }
365
+ /** `{ok:false, error}` without `code` only for an unknown peer id. */
366
+ type SetProtocolResponse = {
367
+ ok: true;
368
+ } | ProtocolErrorResponse | {
369
+ ok: false;
370
+ error: string;
371
+ };
372
+ interface UnsetProtocolRequest {
373
+ id: string;
374
+ /** Protocol to drop; all declarations of the peer when omitted. */
375
+ name?: string;
376
+ }
377
+ type UnsetProtocolResponse = {
378
+ ok: true;
379
+ removed: number;
380
+ } | {
381
+ ok: false;
382
+ error: string;
383
+ };
384
+ interface GetProtocolRequest {
385
+ name: string;
386
+ /** Highest version the broker holds when omitted (`0.0.0+sha` counts as lowest). */
387
+ version?: string;
388
+ }
389
+ /** `servers` = number of alive peers (replicas included) that declare the returned protocol. */
390
+ type GetProtocolResponse = {
391
+ ok: true;
392
+ protocol: StoredProtocol;
393
+ servers: number;
394
+ } | ProtocolErrorResponse;
395
+ /** Request / response pair per protocol route. */
396
+ interface ProtocolRouteMap {
397
+ "/set-protocol": {
398
+ request: SetProtocolRequest;
399
+ response: SetProtocolResponse;
400
+ };
401
+ "/unset-protocol": {
402
+ request: UnsetProtocolRequest;
403
+ response: UnsetProtocolResponse;
404
+ };
405
+ "/get-protocol": {
406
+ request: GetProtocolRequest;
407
+ response: GetProtocolResponse;
408
+ };
409
+ }
410
+ /** The only GET route. */
411
+ declare const HEALTH_ROUTE: "/health";
412
+ /** POST routes, in the order of `ROUTES` in `legacy/src/broker.js`. */
413
+ declare const BROKER_POST_ROUTES: readonly ["/register", "/heartbeat", "/set-summary", "/set-name", "/list-peers", "/send-message", "/poll-messages", "/acknowledge-messages", "/get-buffered-messages", "/unregister"];
414
+ type BrokerPostRoute = (typeof BROKER_POST_ROUTES)[number];
415
+ /** Request / response pair per POST route. */
416
+ interface BrokerRouteMap {
417
+ "/register": {
418
+ request: RegisterRequest;
419
+ response: RegisterResponse;
420
+ };
421
+ "/heartbeat": {
422
+ request: HeartbeatRequest;
423
+ response: HeartbeatResponse;
424
+ };
425
+ "/set-summary": {
426
+ request: SetSummaryRequest;
427
+ response: SetSummaryResponse;
428
+ };
429
+ "/set-name": {
430
+ request: SetNameRequest;
431
+ response: SetNameResponse;
432
+ };
433
+ "/list-peers": {
434
+ request: ListPeersRequest;
435
+ response: ListPeersResponse;
436
+ };
437
+ "/send-message": {
438
+ request: SendMessageRequest;
439
+ response: SendMessageResponse;
440
+ };
441
+ "/poll-messages": {
442
+ request: PollMessagesRequest;
443
+ response: PollMessagesResponse;
444
+ };
445
+ "/acknowledge-messages": {
446
+ request: AcknowledgeMessagesRequest;
447
+ response: AcknowledgeMessagesResponse;
448
+ };
449
+ "/get-buffered-messages": {
450
+ request: GetBufferedMessagesRequest;
451
+ response: GetBufferedMessagesResponse;
452
+ };
453
+ "/unregister": {
454
+ request: UnregisterRequest;
455
+ response: UnregisterResponse;
456
+ };
457
+ }
458
+ type BrokerRequest<R extends BrokerPostRoute> = BrokerRouteMap[R]["request"];
459
+ type BrokerResponse<R extends BrokerPostRoute> = BrokerRouteMap[R]["response"];
460
+ /** Broker-to-broker sync route. Old brokers answer 404 and are simply not part of the mesh. */
461
+ declare const MESH_SYNC_ROUTE: "/mesh/sync";
462
+ /**
463
+ * POST /mesh/sync — one round of peer / message replication, sent by each
464
+ * mesh broker to every other one.
465
+ */
466
+ interface MeshSyncRequest {
467
+ /** Id of the sending broker (= `origin` of the peers below). */
468
+ from: string;
469
+ /** Live peers that registered directly with the sender (replaces what the receiver holds for `from`). */
470
+ peers: Peer[];
471
+ /** Undelivered messages the sender holds for peers that live on the receiver. Ids are the sender's. */
472
+ messages: Message[];
473
+ /** Definitions declared by the sender's direct peers. Absent from 0.9.x brokers. */
474
+ protocols?: StoredProtocol[];
475
+ }
476
+ interface MeshSyncResponse {
477
+ /** Id of the receiving broker. */
478
+ id: string;
479
+ /** Live peers that registered directly with the receiver. */
480
+ peers: Peer[];
481
+ /** Sender-side ids of the messages the receiver took over; the sender drops them. */
482
+ accepted: number[];
483
+ /** Definitions declared by the receiver's direct peers. Absent from 0.9.x brokers. */
484
+ protocols?: StoredProtocol[];
485
+ }
486
+
487
+ /**
488
+ * UDP LAN discovery — probe / reply JSON shapes.
489
+ *
490
+ * Transcribed from `legacy/src/resolve.js` (`discoverBrokers`) and `legacy/src/broker.js`
491
+ * (discovery responder). Both packets are single JSON objects; the broker's
492
+ * address is the reply packet's UDP source address.
493
+ */
494
+ /** JSON key present in both probe and reply. */
495
+ declare const DISCOVERY_KEY: "agent-messenger";
496
+ /** Value of `DISCOVERY_KEY` in a client probe. */
497
+ declare const DISCOVERY_PROBE_VALUE: "probe";
498
+ /** Value of `DISCOVERY_KEY` in a broker reply. */
499
+ declare const DISCOVERY_REPLY_VALUE: "broker";
500
+ /** Client → broadcast: `{"agent-messenger":"probe"}` */
501
+ interface DiscoveryProbe {
502
+ [DISCOVERY_KEY]: typeof DISCOVERY_PROBE_VALUE;
503
+ }
504
+ /** Broker → client: `{"agent-messenger":"broker","id":..,"port":..,"version":..}` */
505
+ interface DiscoveryReply {
506
+ [DISCOVERY_KEY]: typeof DISCOVERY_REPLY_VALUE;
507
+ /** Broker id (`AGENT_MESSENGER_BROKER_ID`, default hostname). */
508
+ id: string;
509
+ /** Broker HTTP port. */
510
+ port: number;
511
+ /** Broker package version. */
512
+ version: string;
513
+ /** Present (`true`) only when the broker is a local fallback; clients prefer other brokers, fallbacks never relay to each other. */
514
+ fallback?: true;
515
+ }
516
+ /** The exact probe object sent by the client. */
517
+ declare const DISCOVERY_PROBE: DiscoveryProbe;
518
+ /** Default probe target when `AGENT_MESSENGER_DISCOVERY_ADDR` is unset (plus per-interface directed broadcast). */
519
+ declare const DISCOVERY_BROADCAST_ADDR = "255.255.255.255";
520
+
521
+ /**
522
+ * Claude Code session inbox socket — line shapes.
523
+ *
524
+ * Transcribed from `legacy/src/server.js` (`postToSession`). The client connects to
525
+ * the unix socket named by `CLAUDE_CODE_MESSAGING_SOCKET`, writes one JSON
526
+ * object per line (`\n` terminated), then half-closes:
527
+ *
528
+ * 1. `{"type":"auth","token":<CLAUDE_CODE_MESSAGING_TOKEN>}` only when the token is set
529
+ * 2. `{"type":"user","message":{"role":"user","content":<text>}}`
530
+ */
531
+ /** Environment variable holding the session socket path. */
532
+ declare const SESSION_SOCKET_ENV = "CLAUDE_CODE_MESSAGING_SOCKET";
533
+ /** Environment variable holding the session socket auth token. */
534
+ declare const SESSION_TOKEN_ENV = "CLAUDE_CODE_MESSAGING_TOKEN";
535
+ interface SessionAuthLine {
536
+ type: "auth";
537
+ token: string;
538
+ }
539
+ interface SessionUserLine {
540
+ type: "user";
541
+ message: {
542
+ role: "user";
543
+ content: string;
544
+ };
545
+ }
546
+ type SessionSocketLine = SessionAuthLine | SessionUserLine;
547
+
548
+ /**
549
+ * Canonical JSON for protocol hashes: object keys in ascending (UTF-16 code unit) order at every depth,
550
+ * no whitespace, otherwise exactly what `JSON.stringify` writes for each value. Pure TypeScript with no
551
+ * Node dependency, so any runtime can import it. The hash itself,
552
+ * `sha256(canonicalJSON({manifest, doc}))` in lower-case hex, is computed by each side with its own
553
+ * sha256 (broker: `node:crypto`).
554
+ *
555
+ * Input is expected to be JSON data (what `JSON.parse` returns). As in `JSON.stringify`, an object member whose
556
+ * value is `undefined` / a function / a symbol is skipped, and such an array element becomes `null`.
557
+ */
558
+ declare function canonicalJSON(value: unknown): string;
559
+
560
+ export { BROKER_POST_ROUTES, DEFAULT_BIND, DEFAULT_DISCOVERY_PORT, DEFAULT_DISCOVERY_TIMEOUT_MS, DEFAULT_HTTP_PORT, DISCOVERY_BROADCAST_ADDR, DISCOVERY_KEY, DISCOVERY_PROBE, DISCOVERY_PROBE_VALUE, DISCOVERY_REPLY_VALUE, ENV, HEALTH_ROUTE, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, LOCAL_HOSTS, MESH_SYNC_ROUTE, POLL_INTERVAL_MS, PROTOCOL_DOC_MAX_BYTES, PROTOCOL_ERROR_CODES, PROTOCOL_MANIFEST_MAX_BYTES, PROTOCOL_MAX_STORED, PROTOCOL_META_MAX_LENGTH, PROTOCOL_NAME_PATTERN, PROTOCOL_ROUTES, PROTOCOL_TOTAL_MAX_BYTES, RELAY_ROUTE, SESSION_SOCKET_ENV, SESSION_TOKEN_ENV, canonicalJSON };
561
+ export type { AcknowledgeMessagesRequest, AcknowledgeMessagesResponse, BrokerErrorResponse, BrokerPostRoute, BrokerRequest, BrokerResponse, BrokerRouteMap, DiscoveryProbe, DiscoveryReply, EnvName, GetBufferedMessagesRequest, GetBufferedMessagesResponse, GetProtocolRequest, GetProtocolResponse, HealthResponse, HeartbeatRequest, HeartbeatResponse, ListPeersRequest, ListPeersResponse, MeshSyncRequest, MeshSyncResponse, Message, MessageMeta, MessageMode, OkResult, Peer, PeerScope, PollMessagesRequest, PollMessagesResponse, ProtocolDecl, ProtocolDefinition, ProtocolErrorCode, ProtocolErrorResponse, ProtocolRoute, ProtocolRouteMap, RegisterRequest, RegisterResponse, RelayMessagesRequest, RelayMessagesResponse, RelayedMessage, SendMessageRequest, SendMessageResponse, SessionAuthLine, SessionSocketLine, SessionUserLine, SetNameRequest, SetNameResponse, SetProtocolRequest, SetProtocolResponse, SetSummaryRequest, SetSummaryResponse, StoredProtocol, UnregisterRequest, UnregisterResponse, UnsetProtocolRequest, UnsetProtocolResponse };
@@ -0,0 +1,561 @@
1
+ /**
2
+ * Protocol constants shared by broker, client and CLI.
3
+ *
4
+ * Values are transcribed from the current JavaScript implementation
5
+ * (`legacy/src/config.js`, `legacy/src/broker.js`, `legacy/src/server.js`). Do not change them here
6
+ * without changing the implementation on both ends.
7
+ */
8
+ /** Broker HTTP listen port (`AGENT_MESSENGER_PORT` default). */
9
+ declare const DEFAULT_HTTP_PORT = 7901;
10
+ /** Broker HTTP bind address (`AGENT_MESSENGER_BIND` default). */
11
+ declare const DEFAULT_BIND = "0.0.0.0";
12
+ /** UDP discovery port (`AGENT_MESSENGER_DISCOVERY_PORT` default). */
13
+ declare const DEFAULT_DISCOVERY_PORT = 7902;
14
+ /** How long a client waits for discovery answers (`AGENT_MESSENGER_DISCOVERY_TIMEOUT_MS` default). */
15
+ declare const DEFAULT_DISCOVERY_TIMEOUT_MS = 1000;
16
+ /** Client heartbeat interval (`AGENT_MESSENGER_HEARTBEAT_MS` default). */
17
+ declare const HEARTBEAT_INTERVAL_MS = 15000;
18
+ /** Broker drops a peer whose `last_seen` is older than this. Not configurable. */
19
+ declare const HEARTBEAT_TIMEOUT_MS = 60000;
20
+ /** Client `/poll-messages` interval. Not configurable. */
21
+ declare const POLL_INTERVAL_MS = 1000;
22
+ /** Loopback hosts treated as "local broker" by the client resolver. */
23
+ declare const LOCAL_HOSTS: readonly ["127.0.0.1", "localhost", "::1"];
24
+ /**
25
+ * Environment variable names. Source of truth: `legacy/src/config.js`
26
+ * (`DELIVERY` lives in `legacy/src/server.js`).
27
+ */
28
+ declare const ENV: {
29
+ /** Explicit broker host. `"auto"` or unset = resolve by config / discovery / local. */
30
+ readonly HOST: "AGENT_MESSENGER_HOST";
31
+ /** Broker HTTP port (client target / broker listen). */
32
+ readonly PORT: "AGENT_MESSENGER_PORT";
33
+ /** Broker bind address. */
34
+ readonly BIND: "AGENT_MESSENGER_BIND";
35
+ /** Bearer token; when set, every POST must carry `Authorization: Bearer <token>`. */
36
+ readonly TOKEN: "AGENT_MESSENGER_TOKEN";
37
+ /** Peer name for this session. */
38
+ readonly NAME: "AGENT_MESSENGER_NAME";
39
+ /** Broker id shown in `/health` and discovery replies (default hostname). */
40
+ readonly BROKER_ID: "AGENT_MESSENGER_BROKER_ID";
41
+ /** Broker state file (default `~/.agent-messenger/broker.json`). */
42
+ readonly STATE: "AGENT_MESSENGER_STATE";
43
+ /** Client config file (default `~/.agent-messenger/config.json`). */
44
+ readonly CONFIG: "AGENT_MESSENGER_CONFIG";
45
+ /** `"off"` disables UDP discovery (broker responder and client probe). */
46
+ readonly DISCOVERY: "AGENT_MESSENGER_DISCOVERY";
47
+ /** UDP discovery port. */
48
+ readonly DISCOVERY_PORT: "AGENT_MESSENGER_DISCOVERY_PORT";
49
+ /** Discovery probe target address. */
50
+ readonly DISCOVERY_ADDR: "AGENT_MESSENGER_DISCOVERY_ADDR";
51
+ /** Discovery answer wait time in ms. */
52
+ readonly DISCOVERY_TIMEOUT_MS: "AGENT_MESSENGER_DISCOVERY_TIMEOUT_MS";
53
+ /** Client heartbeat interval in ms. */
54
+ readonly HEARTBEAT_MS: "AGENT_MESSENGER_HEARTBEAT_MS";
55
+ /** Inbound delivery mode: `"auto"` (default) / `"socket"` / `"channel"`. */
56
+ readonly DELIVERY: "AGENT_MESSENGER_DELIVERY";
57
+ };
58
+ type EnvName = (typeof ENV)[keyof typeof ENV];
59
+ /**
60
+ * Extra POST routes of the protocol registry. Like `RELAY_ROUTE`, not part of `BROKER_POST_ROUTES`
61
+ * (that table mirrors the legacy broker); request / response shapes are `ProtocolRouteMap` in `http.ts`.
62
+ */
63
+ declare const PROTOCOL_ROUTES: readonly ["/set-protocol", "/unset-protocol", "/get-protocol"];
64
+ type ProtocolRoute = (typeof PROTOCOL_ROUTES)[number];
65
+ /** Max size of `protocol.json` (UTF-8 bytes). */
66
+ declare const PROTOCOL_MANIFEST_MAX_BYTES: number;
67
+ /** Max size of `PROTOCOL.md` (UTF-8 bytes). */
68
+ declare const PROTOCOL_DOC_MAX_BYTES: number;
69
+ /** Max size of manifest + doc together (UTF-8 bytes). */
70
+ declare const PROTOCOL_TOTAL_MAX_BYTES: number;
71
+ /** Max number of `(name, version)` definitions one broker holds; more is `LIMIT`. */
72
+ declare const PROTOCOL_MAX_STORED = 256;
73
+ /** Max length (characters) of each of `meta.protocol` and `meta.version`. */
74
+ declare const PROTOCOL_META_MAX_LENGTH = 128;
75
+ /** Valid protocol `name`. */
76
+ declare const PROTOCOL_NAME_PATTERN: RegExp;
77
+ /**
78
+ * Error `code`s of the protocol feature (design 7.2). `NO_TAG` is not listed: a repo without tags is
79
+ * not an error (`0.0.0+<sha7>`). Raised by the broker: HASH_MISMATCH, PROTOCOL_CONFLICT, LIMIT,
80
+ * PROTOCOL_NOT_FOUND, and TOO_LARGE / INVALID_DEFINITION on re-check. The rest are raised by the client.
81
+ */
82
+ declare const PROTOCOL_ERROR_CODES: readonly ["REPO_UNREACHABLE", "UNSUPPORTED_REPO", "VERSION_NOT_FOUND", "INVALID_DEFINITION", "VERSION_MISMATCH", "TOO_LARGE", "HASH_MISMATCH", "PROTOCOL_CONFLICT", "LIMIT", "PROTOCOL_NOT_FOUND", "BROKER_UNSUPPORTED", "INVALID_META"];
83
+ type ProtocolErrorCode = (typeof PROTOCOL_ERROR_CODES)[number];
84
+
85
+ /**
86
+ * Broker HTTP API — request / response JSON shapes.
87
+ *
88
+ * Transcribed from `legacy/src/broker.js` (handlers) and `legacy/src/server.js` /
89
+ * `legacy/bin/agent-messenger.js` (callers). Field optionality follows the broker:
90
+ * a field the broker defaults with `??` is optional here.
91
+ *
92
+ * Transport rules (from `legacy/src/broker.js` `startBroker`):
93
+ * - `GET /health` is the only GET route.
94
+ * - Every other route is `POST` with a JSON body; empty body is treated as `{}`.
95
+ * - When the broker has a token, each POST must send `Authorization: Bearer <token>`,
96
+ * otherwise `401 {"error":"unauthorized"}`.
97
+ * - Unknown POST path: `404 {"error":"not found"}`. Handler exception: `500 {"error":<message>}`.
98
+ * - Any other method: `200 text/plain` `agent-messenger broker <version>\n`.
99
+ */
100
+
101
+ /** A registered session as stored and returned by the broker. */
102
+ interface Peer {
103
+ /** 8-char broker-generated id (`[a-z0-9]`). */
104
+ id: string;
105
+ /** Stable name set via `/register` or `/set-name`; `""` when unset. */
106
+ name: string;
107
+ /** Client process id. */
108
+ pid: number;
109
+ hostname: string;
110
+ cwd: string;
111
+ git_root: string | null;
112
+ tty: string | null;
113
+ summary: string;
114
+ /** ISO 8601 timestamp. */
115
+ registered_at: string;
116
+ /** ISO 8601 timestamp; refreshed by `/heartbeat`. */
117
+ last_seen: string;
118
+ /**
119
+ * Mesh only: id of the permanent broker this peer is registered with, set on
120
+ * copies a mesh broker replicated from another one. Absent for peers that
121
+ * registered directly. Never returned by `/list-peers`.
122
+ */
123
+ origin?: string;
124
+ /**
125
+ * Protocols this peer serves (`/set-protocol`, re-sent on `/register` and `/heartbeat`). Hash only; the
126
+ * definition body lives in the broker's protocol store. Absent when none (and from 0.9.x brokers).
127
+ */
128
+ protocols?: ProtocolDecl[];
129
+ }
130
+ /** A protocol a peer declares: identity (`name` + `version`) and the hash of its definition body. */
131
+ interface ProtocolDecl {
132
+ /** `^[a-z0-9][a-z0-9._-]{0,63}$` (`PROTOCOL_NAME_PATTERN`). */
133
+ name: string;
134
+ /** semver, or `0.0.0+<sha7>` for a repo without tags. */
135
+ version: string;
136
+ /** `sha256(canonicalJSON({manifest, doc}))` as lower-case hex. */
137
+ hash: string;
138
+ }
139
+ /** The definition body a server fetched from its protocol repo. */
140
+ interface ProtocolDefinition {
141
+ /** Parsed `protocol.json`. */
142
+ manifest: object;
143
+ /** `PROTOCOL.md` text; `""` when the repo has none. */
144
+ doc: string;
145
+ /** Normalized repo notation (`github:o/r`, `gitea:<base>/o/r`, `file:<abs path>`). Not part of the hash. */
146
+ source: string;
147
+ /** tag or sha the body was read at (`local` for a local path). Not part of the hash. */
148
+ ref: string;
149
+ }
150
+ /** What the broker keeps per `(name, version)`. */
151
+ interface StoredProtocol extends ProtocolDecl {
152
+ definition: ProtocolDefinition;
153
+ /** ISO 8601 timestamp of the first successful `/set-protocol` for this `(name, version)`. */
154
+ registered_at: string;
155
+ }
156
+ /** Protocol tag of a message: which protocol (and version) the sender spoke. Both fields are required when present. */
157
+ interface MessageMeta {
158
+ protocol: string;
159
+ version: string;
160
+ }
161
+ type MessageMode = "pull" | "push" | "ping";
162
+ /** A message as stored and returned by the broker. */
163
+ interface Message {
164
+ /** Broker-assigned incrementing integer. */
165
+ id: number;
166
+ /** Sender peer id, or `"cli"` when sent from the CLI. */
167
+ from_id: string;
168
+ from_name: string;
169
+ to_id: string;
170
+ text: string;
171
+ /**
172
+ * How the receiver shows it: `"pull"` = unread notice only, text via
173
+ * `check_messages`; `"push"` = text shown directly; `"ping"` = liveness
174
+ * notice; `text` is its optional subject (e.g. a task id), `""` when none. Missing (older broker / sender) means `"pull"`.
175
+ */
176
+ mode?: MessageMode;
177
+ /** ISO 8601 timestamp. */
178
+ sent_at: string;
179
+ /** 0 until returned by `/poll-messages`, then 1. */
180
+ delivered: 0 | 1;
181
+ /** Always 0 in the current implementation (acknowledged messages are deleted). */
182
+ acknowledged: 0 | 1;
183
+ /** Mesh only: `<sender broker id>:<id there>` of a message forwarded by another broker (duplicate guard). */
184
+ mesh_key?: string;
185
+ /** Protocol tag given to `/send-message`; returned by `/poll-messages` and kept across relay / mesh forwarding. */
186
+ meta?: MessageMeta;
187
+ }
188
+ /** `/list-peers` scope filter. Unknown values behave as `"all"`. */
189
+ type PeerScope = "all" | "host" | "directory" | "repo";
190
+ /** Generic `{ok:true}` / `{ok:false,error}` result. */
191
+ type OkResult = {
192
+ ok: true;
193
+ } | {
194
+ ok: false;
195
+ error: string;
196
+ };
197
+ /** Body of a non-2xx broker response. */
198
+ interface BrokerErrorResponse {
199
+ error: string;
200
+ }
201
+ interface HealthResponse {
202
+ status: "ok";
203
+ /** Broker package version. */
204
+ version: string;
205
+ /** Broker id (`AGENT_MESSENGER_BROKER_ID`, default hostname). */
206
+ id: string;
207
+ /** Broker HTTP port. */
208
+ port: number;
209
+ /** Count of peers seen within `HEARTBEAT_TIMEOUT_MS`. */
210
+ peers: number;
211
+ /** Present (`true`) only when the broker was started as a local fallback (`AGENT_MESSENGER_FALLBACK=1`). */
212
+ fallback?: true;
213
+ }
214
+ interface RegisterRequest {
215
+ pid: number;
216
+ hostname?: string;
217
+ cwd?: string;
218
+ git_root?: string | null;
219
+ tty?: string | null;
220
+ summary?: string;
221
+ name?: string;
222
+ /** Protocols to declare right away (hash only; bodies follow via `/set-protocol`). */
223
+ protocols?: ProtocolDecl[];
224
+ }
225
+ interface RegisterResponse {
226
+ id: string;
227
+ }
228
+ interface HeartbeatRequest {
229
+ id: string;
230
+ /** Every protocol the peer currently serves (hash only), sent on each heartbeat. */
231
+ protocols?: ProtocolDecl[];
232
+ }
233
+ /**
234
+ * `ok:false` with `"unknown peer (re-register)"` when the broker does not know the id.
235
+ * `resend` lists the `"name@version"` of declared protocols whose body the broker does not hold; the client answers
236
+ * with `/set-protocol`. Absent when nothing is missing (and from 0.9.x brokers).
237
+ */
238
+ type HeartbeatResponse = {
239
+ ok: true;
240
+ resend?: string[];
241
+ } | {
242
+ ok: false;
243
+ error: string;
244
+ };
245
+ interface SetSummaryRequest {
246
+ id: string;
247
+ summary?: string;
248
+ }
249
+ type SetSummaryResponse = OkResult;
250
+ interface SetNameRequest {
251
+ id: string;
252
+ name?: string;
253
+ }
254
+ type SetNameResponse = OkResult;
255
+ interface ListPeersRequest {
256
+ scope?: PeerScope;
257
+ /** Used by scope `"host"`. */
258
+ hostname?: string;
259
+ /** Used by scope `"directory"`, and by `"repo"` when `git_root` is empty. */
260
+ cwd?: string;
261
+ /** Used by scope `"repo"`. */
262
+ git_root?: string | null;
263
+ /** Peer id to omit from the result (the caller itself). */
264
+ exclude_id?: string;
265
+ /** Only peers that declare this protocol (AND with `scope`). */
266
+ protocol?: string;
267
+ /** Only with `protocol`: only peers that declare exactly this version. */
268
+ version?: string;
269
+ }
270
+ type ListPeersResponse = Peer[];
271
+ interface SendMessageRequest {
272
+ /** Target peer id or unique peer name. */
273
+ to: string;
274
+ /** Defaults to `"cli"`. */
275
+ from_id?: string;
276
+ from_name?: string;
277
+ text?: string;
278
+ /** Defaults to `"pull"`. Unknown values are rejected. */
279
+ mode?: MessageMode;
280
+ /** Protocol tag. Both fields must be strings of at most `PROTOCOL_META_MAX_LENGTH` characters. */
281
+ meta?: MessageMeta;
282
+ }
283
+ type SendMessageResponse = {
284
+ ok: true;
285
+ to_id: string;
286
+ to_name: string;
287
+ message_id: number;
288
+ } | {
289
+ ok: false;
290
+ error: string;
291
+ };
292
+ interface PollMessagesRequest {
293
+ id: string;
294
+ }
295
+ /** Undelivered messages for `id`; each is marked `delivered: 1` on return. */
296
+ interface PollMessagesResponse {
297
+ messages: Message[];
298
+ }
299
+ interface AcknowledgeMessagesRequest {
300
+ id: string;
301
+ message_ids?: number[];
302
+ }
303
+ type AcknowledgeMessagesResponse = {
304
+ ok: true;
305
+ };
306
+ interface GetBufferedMessagesRequest {
307
+ id: string;
308
+ }
309
+ /** Messages for `id` with `delivered: 1` and `acknowledged: 0`. */
310
+ interface GetBufferedMessagesResponse {
311
+ messages: Message[];
312
+ }
313
+ interface UnregisterRequest {
314
+ id: string;
315
+ }
316
+ type UnregisterResponse = {
317
+ ok: true;
318
+ };
319
+ /** One undelivered message handed over by a fallback broker. The recipient is addressed by name: peer ids are broker-local. */
320
+ interface RelayedMessage {
321
+ from_id: string;
322
+ from_name: string;
323
+ /** Recipient peer name on the sending broker. Items without a name cannot be relayed. */
324
+ to_name: string;
325
+ /** Recipient hostname on the sending broker; narrows ambiguous names. */
326
+ to_hostname?: string;
327
+ text: string;
328
+ mode?: MessageMode;
329
+ sent_at: string;
330
+ meta?: MessageMeta;
331
+ }
332
+ interface RelayMessagesRequest {
333
+ messages: RelayedMessage[];
334
+ }
335
+ /** `delivered` = queued for a registered peer, `queued` = held until a peer of that name registers, `dropped` = no usable name. */
336
+ interface RelayMessagesResponse {
337
+ ok: true;
338
+ delivered: number;
339
+ queued: number;
340
+ dropped: number;
341
+ }
342
+ /** Extra POST route served by the TypeScript broker. Not in `BROKER_POST_ROUTES` (that table mirrors the legacy broker). */
343
+ declare const RELAY_ROUTE: "/relay-messages";
344
+ /** `{ok:false}` answer of the protocol routes; `code` is one of `PROTOCOL_ERROR_CODES`. */
345
+ interface ProtocolErrorResponse {
346
+ ok: false;
347
+ error: string;
348
+ code: ProtocolErrorCode;
349
+ /** `PROTOCOL_CONFLICT`: hash the broker already holds for this `(name, version)`. */
350
+ existing_hash?: string;
351
+ /** `PROTOCOL_CONFLICT`: servers (`name@host`) that hold it. */
352
+ servers?: string[];
353
+ /** `PROTOCOL_NOT_FOUND`: versions the broker does hold for the name (may be empty). */
354
+ versions?: string[];
355
+ }
356
+ interface SetProtocolRequest {
357
+ /** Peer id of the server. */
358
+ id: string;
359
+ name: string;
360
+ version: string;
361
+ /** Re-computed by the broker; a different value is `HASH_MISMATCH`. */
362
+ hash: string;
363
+ definition: ProtocolDefinition;
364
+ }
365
+ /** `{ok:false, error}` without `code` only for an unknown peer id. */
366
+ type SetProtocolResponse = {
367
+ ok: true;
368
+ } | ProtocolErrorResponse | {
369
+ ok: false;
370
+ error: string;
371
+ };
372
+ interface UnsetProtocolRequest {
373
+ id: string;
374
+ /** Protocol to drop; all declarations of the peer when omitted. */
375
+ name?: string;
376
+ }
377
+ type UnsetProtocolResponse = {
378
+ ok: true;
379
+ removed: number;
380
+ } | {
381
+ ok: false;
382
+ error: string;
383
+ };
384
+ interface GetProtocolRequest {
385
+ name: string;
386
+ /** Highest version the broker holds when omitted (`0.0.0+sha` counts as lowest). */
387
+ version?: string;
388
+ }
389
+ /** `servers` = number of alive peers (replicas included) that declare the returned protocol. */
390
+ type GetProtocolResponse = {
391
+ ok: true;
392
+ protocol: StoredProtocol;
393
+ servers: number;
394
+ } | ProtocolErrorResponse;
395
+ /** Request / response pair per protocol route. */
396
+ interface ProtocolRouteMap {
397
+ "/set-protocol": {
398
+ request: SetProtocolRequest;
399
+ response: SetProtocolResponse;
400
+ };
401
+ "/unset-protocol": {
402
+ request: UnsetProtocolRequest;
403
+ response: UnsetProtocolResponse;
404
+ };
405
+ "/get-protocol": {
406
+ request: GetProtocolRequest;
407
+ response: GetProtocolResponse;
408
+ };
409
+ }
410
+ /** The only GET route. */
411
+ declare const HEALTH_ROUTE: "/health";
412
+ /** POST routes, in the order of `ROUTES` in `legacy/src/broker.js`. */
413
+ declare const BROKER_POST_ROUTES: readonly ["/register", "/heartbeat", "/set-summary", "/set-name", "/list-peers", "/send-message", "/poll-messages", "/acknowledge-messages", "/get-buffered-messages", "/unregister"];
414
+ type BrokerPostRoute = (typeof BROKER_POST_ROUTES)[number];
415
+ /** Request / response pair per POST route. */
416
+ interface BrokerRouteMap {
417
+ "/register": {
418
+ request: RegisterRequest;
419
+ response: RegisterResponse;
420
+ };
421
+ "/heartbeat": {
422
+ request: HeartbeatRequest;
423
+ response: HeartbeatResponse;
424
+ };
425
+ "/set-summary": {
426
+ request: SetSummaryRequest;
427
+ response: SetSummaryResponse;
428
+ };
429
+ "/set-name": {
430
+ request: SetNameRequest;
431
+ response: SetNameResponse;
432
+ };
433
+ "/list-peers": {
434
+ request: ListPeersRequest;
435
+ response: ListPeersResponse;
436
+ };
437
+ "/send-message": {
438
+ request: SendMessageRequest;
439
+ response: SendMessageResponse;
440
+ };
441
+ "/poll-messages": {
442
+ request: PollMessagesRequest;
443
+ response: PollMessagesResponse;
444
+ };
445
+ "/acknowledge-messages": {
446
+ request: AcknowledgeMessagesRequest;
447
+ response: AcknowledgeMessagesResponse;
448
+ };
449
+ "/get-buffered-messages": {
450
+ request: GetBufferedMessagesRequest;
451
+ response: GetBufferedMessagesResponse;
452
+ };
453
+ "/unregister": {
454
+ request: UnregisterRequest;
455
+ response: UnregisterResponse;
456
+ };
457
+ }
458
+ type BrokerRequest<R extends BrokerPostRoute> = BrokerRouteMap[R]["request"];
459
+ type BrokerResponse<R extends BrokerPostRoute> = BrokerRouteMap[R]["response"];
460
+ /** Broker-to-broker sync route. Old brokers answer 404 and are simply not part of the mesh. */
461
+ declare const MESH_SYNC_ROUTE: "/mesh/sync";
462
+ /**
463
+ * POST /mesh/sync — one round of peer / message replication, sent by each
464
+ * mesh broker to every other one.
465
+ */
466
+ interface MeshSyncRequest {
467
+ /** Id of the sending broker (= `origin` of the peers below). */
468
+ from: string;
469
+ /** Live peers that registered directly with the sender (replaces what the receiver holds for `from`). */
470
+ peers: Peer[];
471
+ /** Undelivered messages the sender holds for peers that live on the receiver. Ids are the sender's. */
472
+ messages: Message[];
473
+ /** Definitions declared by the sender's direct peers. Absent from 0.9.x brokers. */
474
+ protocols?: StoredProtocol[];
475
+ }
476
+ interface MeshSyncResponse {
477
+ /** Id of the receiving broker. */
478
+ id: string;
479
+ /** Live peers that registered directly with the receiver. */
480
+ peers: Peer[];
481
+ /** Sender-side ids of the messages the receiver took over; the sender drops them. */
482
+ accepted: number[];
483
+ /** Definitions declared by the receiver's direct peers. Absent from 0.9.x brokers. */
484
+ protocols?: StoredProtocol[];
485
+ }
486
+
487
+ /**
488
+ * UDP LAN discovery — probe / reply JSON shapes.
489
+ *
490
+ * Transcribed from `legacy/src/resolve.js` (`discoverBrokers`) and `legacy/src/broker.js`
491
+ * (discovery responder). Both packets are single JSON objects; the broker's
492
+ * address is the reply packet's UDP source address.
493
+ */
494
+ /** JSON key present in both probe and reply. */
495
+ declare const DISCOVERY_KEY: "agent-messenger";
496
+ /** Value of `DISCOVERY_KEY` in a client probe. */
497
+ declare const DISCOVERY_PROBE_VALUE: "probe";
498
+ /** Value of `DISCOVERY_KEY` in a broker reply. */
499
+ declare const DISCOVERY_REPLY_VALUE: "broker";
500
+ /** Client → broadcast: `{"agent-messenger":"probe"}` */
501
+ interface DiscoveryProbe {
502
+ [DISCOVERY_KEY]: typeof DISCOVERY_PROBE_VALUE;
503
+ }
504
+ /** Broker → client: `{"agent-messenger":"broker","id":..,"port":..,"version":..}` */
505
+ interface DiscoveryReply {
506
+ [DISCOVERY_KEY]: typeof DISCOVERY_REPLY_VALUE;
507
+ /** Broker id (`AGENT_MESSENGER_BROKER_ID`, default hostname). */
508
+ id: string;
509
+ /** Broker HTTP port. */
510
+ port: number;
511
+ /** Broker package version. */
512
+ version: string;
513
+ /** Present (`true`) only when the broker is a local fallback; clients prefer other brokers, fallbacks never relay to each other. */
514
+ fallback?: true;
515
+ }
516
+ /** The exact probe object sent by the client. */
517
+ declare const DISCOVERY_PROBE: DiscoveryProbe;
518
+ /** Default probe target when `AGENT_MESSENGER_DISCOVERY_ADDR` is unset (plus per-interface directed broadcast). */
519
+ declare const DISCOVERY_BROADCAST_ADDR = "255.255.255.255";
520
+
521
+ /**
522
+ * Claude Code session inbox socket — line shapes.
523
+ *
524
+ * Transcribed from `legacy/src/server.js` (`postToSession`). The client connects to
525
+ * the unix socket named by `CLAUDE_CODE_MESSAGING_SOCKET`, writes one JSON
526
+ * object per line (`\n` terminated), then half-closes:
527
+ *
528
+ * 1. `{"type":"auth","token":<CLAUDE_CODE_MESSAGING_TOKEN>}` only when the token is set
529
+ * 2. `{"type":"user","message":{"role":"user","content":<text>}}`
530
+ */
531
+ /** Environment variable holding the session socket path. */
532
+ declare const SESSION_SOCKET_ENV = "CLAUDE_CODE_MESSAGING_SOCKET";
533
+ /** Environment variable holding the session socket auth token. */
534
+ declare const SESSION_TOKEN_ENV = "CLAUDE_CODE_MESSAGING_TOKEN";
535
+ interface SessionAuthLine {
536
+ type: "auth";
537
+ token: string;
538
+ }
539
+ interface SessionUserLine {
540
+ type: "user";
541
+ message: {
542
+ role: "user";
543
+ content: string;
544
+ };
545
+ }
546
+ type SessionSocketLine = SessionAuthLine | SessionUserLine;
547
+
548
+ /**
549
+ * Canonical JSON for protocol hashes: object keys in ascending (UTF-16 code unit) order at every depth,
550
+ * no whitespace, otherwise exactly what `JSON.stringify` writes for each value. Pure TypeScript with no
551
+ * Node dependency, so any runtime can import it. The hash itself,
552
+ * `sha256(canonicalJSON({manifest, doc}))` in lower-case hex, is computed by each side with its own
553
+ * sha256 (broker: `node:crypto`).
554
+ *
555
+ * Input is expected to be JSON data (what `JSON.parse` returns). As in `JSON.stringify`, an object member whose
556
+ * value is `undefined` / a function / a symbol is skipped, and such an array element becomes `null`.
557
+ */
558
+ declare function canonicalJSON(value: unknown): string;
559
+
560
+ export { BROKER_POST_ROUTES, DEFAULT_BIND, DEFAULT_DISCOVERY_PORT, DEFAULT_DISCOVERY_TIMEOUT_MS, DEFAULT_HTTP_PORT, DISCOVERY_BROADCAST_ADDR, DISCOVERY_KEY, DISCOVERY_PROBE, DISCOVERY_PROBE_VALUE, DISCOVERY_REPLY_VALUE, ENV, HEALTH_ROUTE, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, LOCAL_HOSTS, MESH_SYNC_ROUTE, POLL_INTERVAL_MS, PROTOCOL_DOC_MAX_BYTES, PROTOCOL_ERROR_CODES, PROTOCOL_MANIFEST_MAX_BYTES, PROTOCOL_MAX_STORED, PROTOCOL_META_MAX_LENGTH, PROTOCOL_NAME_PATTERN, PROTOCOL_ROUTES, PROTOCOL_TOTAL_MAX_BYTES, RELAY_ROUTE, SESSION_SOCKET_ENV, SESSION_TOKEN_ENV, canonicalJSON };
561
+ export type { AcknowledgeMessagesRequest, AcknowledgeMessagesResponse, BrokerErrorResponse, BrokerPostRoute, BrokerRequest, BrokerResponse, BrokerRouteMap, DiscoveryProbe, DiscoveryReply, EnvName, GetBufferedMessagesRequest, GetBufferedMessagesResponse, GetProtocolRequest, GetProtocolResponse, HealthResponse, HeartbeatRequest, HeartbeatResponse, ListPeersRequest, ListPeersResponse, MeshSyncRequest, MeshSyncResponse, Message, MessageMeta, MessageMode, OkResult, Peer, PeerScope, PollMessagesRequest, PollMessagesResponse, ProtocolDecl, ProtocolDefinition, ProtocolErrorCode, ProtocolErrorResponse, ProtocolRoute, ProtocolRouteMap, RegisterRequest, RegisterResponse, RelayMessagesRequest, RelayMessagesResponse, RelayedMessage, SendMessageRequest, SendMessageResponse, SessionAuthLine, SessionSocketLine, SessionUserLine, SetNameRequest, SetNameResponse, SetProtocolRequest, SetProtocolResponse, SetSummaryRequest, SetSummaryResponse, StoredProtocol, UnregisterRequest, UnregisterResponse, UnsetProtocolRequest, UnsetProtocolResponse };
package/dist/index.mjs ADDED
@@ -0,0 +1,103 @@
1
+ const DEFAULT_HTTP_PORT = 7901;
2
+ const DEFAULT_BIND = "0.0.0.0";
3
+ const DEFAULT_DISCOVERY_PORT = 7902;
4
+ const DEFAULT_DISCOVERY_TIMEOUT_MS = 1e3;
5
+ const HEARTBEAT_INTERVAL_MS = 15e3;
6
+ const HEARTBEAT_TIMEOUT_MS = 6e4;
7
+ const POLL_INTERVAL_MS = 1e3;
8
+ const LOCAL_HOSTS = ["127.0.0.1", "localhost", "::1"];
9
+ const ENV = {
10
+ /** Explicit broker host. `"auto"` or unset = resolve by config / discovery / local. */
11
+ HOST: "AGENT_MESSENGER_HOST",
12
+ /** Broker HTTP port (client target / broker listen). */
13
+ PORT: "AGENT_MESSENGER_PORT",
14
+ /** Broker bind address. */
15
+ BIND: "AGENT_MESSENGER_BIND",
16
+ /** Bearer token; when set, every POST must carry `Authorization: Bearer <token>`. */
17
+ TOKEN: "AGENT_MESSENGER_TOKEN",
18
+ /** Peer name for this session. */
19
+ NAME: "AGENT_MESSENGER_NAME",
20
+ /** Broker id shown in `/health` and discovery replies (default hostname). */
21
+ BROKER_ID: "AGENT_MESSENGER_BROKER_ID",
22
+ /** Broker state file (default `~/.agent-messenger/broker.json`). */
23
+ STATE: "AGENT_MESSENGER_STATE",
24
+ /** Client config file (default `~/.agent-messenger/config.json`). */
25
+ CONFIG: "AGENT_MESSENGER_CONFIG",
26
+ /** `"off"` disables UDP discovery (broker responder and client probe). */
27
+ DISCOVERY: "AGENT_MESSENGER_DISCOVERY",
28
+ /** UDP discovery port. */
29
+ DISCOVERY_PORT: "AGENT_MESSENGER_DISCOVERY_PORT",
30
+ /** Discovery probe target address. */
31
+ DISCOVERY_ADDR: "AGENT_MESSENGER_DISCOVERY_ADDR",
32
+ /** Discovery answer wait time in ms. */
33
+ DISCOVERY_TIMEOUT_MS: "AGENT_MESSENGER_DISCOVERY_TIMEOUT_MS",
34
+ /** Client heartbeat interval in ms. */
35
+ HEARTBEAT_MS: "AGENT_MESSENGER_HEARTBEAT_MS",
36
+ /** Inbound delivery mode: `"auto"` (default) / `"socket"` / `"channel"`. */
37
+ DELIVERY: "AGENT_MESSENGER_DELIVERY"
38
+ };
39
+ const PROTOCOL_ROUTES = ["/set-protocol", "/unset-protocol", "/get-protocol"];
40
+ const PROTOCOL_MANIFEST_MAX_BYTES = 64 * 1024;
41
+ const PROTOCOL_DOC_MAX_BYTES = 64 * 1024;
42
+ const PROTOCOL_TOTAL_MAX_BYTES = 128 * 1024;
43
+ const PROTOCOL_MAX_STORED = 256;
44
+ const PROTOCOL_META_MAX_LENGTH = 128;
45
+ const PROTOCOL_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
46
+ const PROTOCOL_ERROR_CODES = [
47
+ "REPO_UNREACHABLE",
48
+ "UNSUPPORTED_REPO",
49
+ "VERSION_NOT_FOUND",
50
+ "INVALID_DEFINITION",
51
+ "VERSION_MISMATCH",
52
+ "TOO_LARGE",
53
+ "HASH_MISMATCH",
54
+ "PROTOCOL_CONFLICT",
55
+ "LIMIT",
56
+ "PROTOCOL_NOT_FOUND",
57
+ "BROKER_UNSUPPORTED",
58
+ "INVALID_META"
59
+ ];
60
+
61
+ const RELAY_ROUTE = "/relay-messages";
62
+ const HEALTH_ROUTE = "/health";
63
+ const BROKER_POST_ROUTES = [
64
+ "/register",
65
+ "/heartbeat",
66
+ "/set-summary",
67
+ "/set-name",
68
+ "/list-peers",
69
+ "/send-message",
70
+ "/poll-messages",
71
+ "/acknowledge-messages",
72
+ "/get-buffered-messages",
73
+ "/unregister"
74
+ ];
75
+ const MESH_SYNC_ROUTE = "/mesh/sync";
76
+
77
+ const DISCOVERY_KEY = "agent-messenger";
78
+ const DISCOVERY_PROBE_VALUE = "probe";
79
+ const DISCOVERY_REPLY_VALUE = "broker";
80
+ const DISCOVERY_PROBE = { [DISCOVERY_KEY]: DISCOVERY_PROBE_VALUE };
81
+ const DISCOVERY_BROADCAST_ADDR = "255.255.255.255";
82
+
83
+ const SESSION_SOCKET_ENV = "CLAUDE_CODE_MESSAGING_SOCKET";
84
+ const SESSION_TOKEN_ENV = "CLAUDE_CODE_MESSAGING_TOKEN";
85
+
86
+ function canonicalJSON(value) {
87
+ if (value === null || typeof value !== "object") {
88
+ return JSON.stringify(value) ?? "null";
89
+ }
90
+ if (Array.isArray(value)) {
91
+ return `[${value.map((v) => canonicalJSON(v)).join(",")}]`;
92
+ }
93
+ const obj = value;
94
+ const parts = [];
95
+ for (const k of Object.keys(obj).sort()) {
96
+ const v = obj[k];
97
+ if (v === void 0 || typeof v === "function" || typeof v === "symbol") continue;
98
+ parts.push(`${JSON.stringify(k)}:${canonicalJSON(v)}`);
99
+ }
100
+ return `{${parts.join(",")}}`;
101
+ }
102
+
103
+ export { BROKER_POST_ROUTES, DEFAULT_BIND, DEFAULT_DISCOVERY_PORT, DEFAULT_DISCOVERY_TIMEOUT_MS, DEFAULT_HTTP_PORT, DISCOVERY_BROADCAST_ADDR, DISCOVERY_KEY, DISCOVERY_PROBE, DISCOVERY_PROBE_VALUE, DISCOVERY_REPLY_VALUE, ENV, HEALTH_ROUTE, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, LOCAL_HOSTS, MESH_SYNC_ROUTE, POLL_INTERVAL_MS, PROTOCOL_DOC_MAX_BYTES, PROTOCOL_ERROR_CODES, PROTOCOL_MANIFEST_MAX_BYTES, PROTOCOL_MAX_STORED, PROTOCOL_META_MAX_LENGTH, PROTOCOL_NAME_PATTERN, PROTOCOL_ROUTES, PROTOCOL_TOTAL_MAX_BYTES, RELAY_ROUTE, SESSION_SOCKET_ENV, SESSION_TOKEN_ENV, canonicalJSON };
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@unagents/messenger-protocol",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.10.0",
4
+ "description": "agent-messenger protocol: types and constants shared by broker, client and CLI. No runtime logic.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/unagents/agent-messenger.git",
10
+ "directory": "packages/protocol"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.mts",
15
+ "import": "./dist/index.mjs"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "build": "unbuild",
26
+ "typecheck": "tsgo -p tsconfig.json",
27
+ "test": "vitest run"
28
+ }
29
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.