@casimesh/contracts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,506 @@
1
+ import { z } from 'zod';
2
+
3
+ // src/agent.ts
4
+ var CapabilityName = z.string().regex(/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*$/, "Dotted lowercase name, e.g. terrain.analysis").max(100);
5
+ var Capability = z.object({
6
+ name: CapabilityName,
7
+ version: z.string().max(32).default("1.0.0"),
8
+ description: z.string().max(500).optional()
9
+ }).meta({ id: "Capability", description: "A machine-discoverable description of what an agent can perform." });
10
+ var Timestamp = z.iso.datetime().meta({ example: "2026-09-28T09:28:12.123Z" });
11
+ var Version = z.int().min(1).meta({ description: "Monotonic per-entity version" });
12
+ var DisplayName = z.string().trim().min(1).max(120);
13
+ var Slug = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Lowercase letters, digits and single hyphens").max(63);
14
+ var Metadata = z.record(z.string(), z.unknown());
15
+ var EntityAudit = {
16
+ version: Version,
17
+ createdAt: Timestamp,
18
+ updatedAt: Timestamp
19
+ };
20
+ var ID_PREFIX = {
21
+ node: "node",
22
+ organization: "org",
23
+ agent: "agt",
24
+ link: "lnk",
25
+ event: "evt",
26
+ command: "cmd",
27
+ principal: "prn",
28
+ roleBinding: "rol",
29
+ apiKey: "key",
30
+ task: "tsk"
31
+ };
32
+ var ULID_PATTERN = "[0-9A-HJKMNP-TV-Z]{26}";
33
+ var prefixedId = (kind) => z.string().regex(new RegExp(`^${ID_PREFIX[kind]}_${ULID_PATTERN}$`), `Expected a ${kind} id (${ID_PREFIX[kind]}_<ULID>)`).meta({ description: `${kind} identifier`, example: `${ID_PREFIX[kind]}_01J9Z3K7Q8R5T2V4W6X8Y0A1B2` });
34
+ var NodeId = prefixedId("node");
35
+ var OrganizationId = prefixedId("organization");
36
+ var AgentId = prefixedId("agent");
37
+ var LinkId = prefixedId("link");
38
+ var EventId = prefixedId("event");
39
+ var CommandId = prefixedId("command");
40
+ var PrincipalId = prefixedId("principal");
41
+ var RoleBindingId = prefixedId("roleBinding");
42
+ var TaskId = prefixedId("task");
43
+
44
+ // src/agent.ts
45
+ var AgentKind = z.enum(["standard", "mesh"]);
46
+ var AgentStatus = z.enum(["created", "starting", "running", "stopped", "error"]);
47
+ var capabilityList = z.array(Capability).max(64).refine((caps) => new Set(caps.map((c) => c.name)).size === caps.length, "Capability names must be unique");
48
+ var Agent = z.object({
49
+ id: AgentId,
50
+ organizationId: OrganizationId,
51
+ nodeId: NodeId,
52
+ name: DisplayName,
53
+ kind: AgentKind,
54
+ status: AgentStatus,
55
+ capabilities: capabilityList,
56
+ /** Model backing the agent, e.g. `claude-sonnet-5`; null for rule-based agents. */
57
+ model: z.string().max(100).nullable(),
58
+ metadata: Metadata,
59
+ ...EntityAudit
60
+ }).meta({ id: "Agent", description: "An autonomous software entity with identity, capabilities and policies." });
61
+ var CreateAgentRequest = z.object({
62
+ name: DisplayName,
63
+ capabilities: capabilityList.default([]),
64
+ model: z.string().max(100).nullable().default(null),
65
+ metadata: Metadata.optional()
66
+ }).meta({ id: "CreateAgentRequest" });
67
+ var UpdateAgentRequest = z.object({
68
+ name: DisplayName.optional(),
69
+ capabilities: capabilityList.optional(),
70
+ model: z.string().max(100).nullable().optional(),
71
+ metadata: Metadata.optional()
72
+ }).refine((body) => Object.keys(body).length > 0, "At least one field must be provided").meta({ id: "UpdateAgentRequest" });
73
+ var PrincipalKind = z.enum(["user", "service"]);
74
+ var Principal = z.object({
75
+ id: PrincipalId,
76
+ kind: PrincipalKind,
77
+ name: DisplayName,
78
+ publicKey: z.string().nullable(),
79
+ createdAt: Timestamp
80
+ }).meta({ id: "Principal", description: "A user or service that can be authenticated and granted roles." });
81
+ var Role = z.enum(["node_owner", "org_owner"]);
82
+ var RoleScope = z.discriminatedUnion("type", [
83
+ z.object({ type: z.literal("node"), nodeId: NodeId }),
84
+ z.object({ type: z.literal("organization"), organizationId: OrganizationId, nodeId: NodeId })
85
+ ]);
86
+ var RoleBinding = z.object({
87
+ id: RoleBindingId,
88
+ principalId: PrincipalId,
89
+ role: Role,
90
+ scope: RoleScope,
91
+ createdAt: Timestamp
92
+ }).refine(
93
+ (b) => b.role === "node_owner" ? b.scope.type === "node" : b.scope.type === "organization",
94
+ "node_owner must be node-scoped and org_owner organization-scoped"
95
+ ).meta({ id: "RoleBinding" });
96
+ var GrantOwnerRequest = z.object({ principalId: PrincipalId }).meta({ id: "GrantOwnerRequest" });
97
+ var TransportKind = z.enum(["memory", "ws-peer", "tcp", "mqtt", "meshtastic", "meshcore"]);
98
+ var LinkState = z.enum(["requested", "up", "down"]);
99
+ var LinkQuality = z.object({
100
+ latencyMs: z.number().nonnegative().optional(),
101
+ rssi: z.number().optional()
102
+ });
103
+ var Link = z.object({
104
+ id: LinkId,
105
+ aNodeId: NodeId,
106
+ bNodeId: NodeId,
107
+ transport: TransportKind,
108
+ state: LinkState,
109
+ quality: LinkQuality,
110
+ lastSeenAt: Timestamp.nullable(),
111
+ ...EntityAudit
112
+ }).refine((link) => link.aNodeId !== link.bNodeId, "A link must connect two different nodes").meta({ id: "Link", description: "Transport-level adjacency between two nodes \u2014 the edges of the topology." });
113
+ var CreateLinkRequest = z.object({ aNodeId: NodeId, bNodeId: NodeId, transport: TransportKind }).refine((body) => body.aNodeId !== body.bNodeId, "A link must connect two different nodes").meta({ id: "CreateLinkRequest" });
114
+ var NodeStatus = z.enum(["online", "degraded", "offline"]);
115
+ var Node = z.object({
116
+ id: NodeId,
117
+ name: DisplayName,
118
+ publicKey: z.string().min(1),
119
+ /** Base URL where other nodes and clients reach this node, e.g. `https://node-a.example:7700` (ADR-0017). */
120
+ endpoint: z.url().nullable(),
121
+ status: NodeStatus,
122
+ metadata: Metadata,
123
+ lastSeenAt: Timestamp.nullable(),
124
+ ...EntityAudit
125
+ }).meta({ id: "Node", description: "A physical or virtual endpoint connected to the mesh." });
126
+ var UpdateNodeRequest = z.object({
127
+ name: DisplayName.optional(),
128
+ endpoint: z.url().nullable().optional(),
129
+ metadata: Metadata.optional()
130
+ }).refine((body) => Object.keys(body).length > 0, "At least one field must be provided").meta({ id: "UpdateNodeRequest" });
131
+ var Organization = z.object({
132
+ id: OrganizationId,
133
+ nodeId: NodeId,
134
+ name: DisplayName,
135
+ slug: Slug,
136
+ metadata: Metadata,
137
+ ...EntityAudit
138
+ }).meta({ id: "Organization", description: "A logical boundary on a node that owns policies, identities and agents." });
139
+ var CreateOrganizationRequest = z.object({
140
+ name: DisplayName,
141
+ /** Derived from `name` when omitted. */
142
+ slug: Slug.optional(),
143
+ metadata: Metadata.optional(),
144
+ /** Principal to make the first org owner; defaults to the caller. */
145
+ ownerPrincipalId: PrincipalId.optional()
146
+ }).meta({ id: "CreateOrganizationRequest" });
147
+ var UpdateOrganizationRequest = z.object({
148
+ name: DisplayName.optional(),
149
+ metadata: Metadata.optional()
150
+ }).refine((body) => Object.keys(body).length > 0, "At least one field must be provided").meta({ id: "UpdateOrganizationRequest" });
151
+ var TaskStatus = z.enum(["requested", "accepted", "completed", "failed"]);
152
+ var TERMINAL_TASK_STATUSES = ["completed", "failed"];
153
+ var TaskParty = z.object({ agentId: AgentId, organizationId: OrganizationId, nodeId: NodeId });
154
+ var TaskAssignee = z.object({ organizationId: OrganizationId, nodeId: NodeId, meshAgentId: AgentId });
155
+ var TaskStep = z.object({
156
+ name: z.enum(["observe", "reason", "act", "verify"]),
157
+ at: Timestamp,
158
+ summary: z.string().max(1e3)
159
+ });
160
+ var TaskError = z.object({ code: z.string().max(64), message: z.string().max(1e3) });
161
+ var Task = z.object({
162
+ id: TaskId,
163
+ capability: CapabilityName,
164
+ input: Metadata,
165
+ status: TaskStatus,
166
+ requester: TaskParty,
167
+ /** The requester organization's Mesh Agent, the first hop of the route. */
168
+ requesterMeshAgentId: AgentId,
169
+ assignee: TaskAssignee,
170
+ /** The agent that does the work, chosen by the assignee's Mesh Agent on acceptance. */
171
+ provider: TaskParty.nullable(),
172
+ output: Metadata.nullable(),
173
+ error: TaskError.nullable(),
174
+ steps: z.array(TaskStep).max(32),
175
+ /** Model that produced the result; null when a rule-based model did. */
176
+ model: z.string().max(100).nullable(),
177
+ version: Version,
178
+ createdAt: Timestamp,
179
+ updatedAt: Timestamp
180
+ }).meta({
181
+ id: "Task",
182
+ description: "A capability request routed through Mesh Agents, with its result and provenance (ADR-0020)."
183
+ });
184
+ var RequestTaskRequest = z.object({
185
+ capability: CapabilityName,
186
+ input: Metadata.default({})
187
+ }).meta({ id: "RequestTaskRequest" });
188
+ var CapabilityProvider = z.object({
189
+ agentId: AgentId,
190
+ agentName: z.string(),
191
+ organizationId: OrganizationId,
192
+ organizationName: z.string(),
193
+ nodeId: NodeId,
194
+ /** Running, on a node that is not offline — i.e. a task could be routed to it now. */
195
+ available: z.boolean()
196
+ }).meta({ id: "CapabilityProvider" });
197
+
198
+ // src/events.ts
199
+ var subject = (kind, id) => z.object({ kind: z.literal(kind), id, version: Version });
200
+ var NodeSubject = subject("node", NodeId);
201
+ var OrganizationSubject = subject("organization", OrganizationId);
202
+ var AgentSubject = subject("agent", AgentId);
203
+ var LinkSubject = subject("link", LinkId);
204
+ var RoleBindingSubject = subject("roleBinding", RoleBindingId);
205
+ var TaskSubject = subject("task", TaskId);
206
+ var event = (type, subjectSchema, payload) => z.object({ type: z.literal(type), subject: subjectSchema, payload });
207
+ var AgentRegistration = z.object({
208
+ meshAgentId: AgentId,
209
+ agentId: AgentId,
210
+ organizationId: OrganizationId,
211
+ nodeId: NodeId
212
+ });
213
+ var NodeCreated = event("node.created", NodeSubject, z.object({ node: Node }));
214
+ var NodeUpdated = event("node.updated", NodeSubject, z.object({ node: Node }));
215
+ var NodeRemoved = event("node.removed", NodeSubject, z.object({ nodeId: NodeId }));
216
+ var NodeStatusChanged = event(
217
+ "node.status_changed",
218
+ NodeSubject,
219
+ z.object({ nodeId: NodeId, status: NodeStatus, previousStatus: NodeStatus, lastSeenAt: Timestamp.nullable() })
220
+ );
221
+ var NodeHeartbeat = event("node.heartbeat", NodeSubject, z.object({ nodeId: NodeId, at: Timestamp }));
222
+ var OrganizationCreated = event(
223
+ "organization.created",
224
+ OrganizationSubject,
225
+ z.object({ organization: Organization })
226
+ );
227
+ var OrganizationUpdated = event(
228
+ "organization.updated",
229
+ OrganizationSubject,
230
+ z.object({ organization: Organization })
231
+ );
232
+ var OrganizationRemoved = event(
233
+ "organization.removed",
234
+ OrganizationSubject,
235
+ z.object({ organizationId: OrganizationId, nodeId: NodeId })
236
+ );
237
+ var AgentCreated = event("agent.created", AgentSubject, z.object({ agent: Agent }));
238
+ var AgentUpdated = event("agent.updated", AgentSubject, z.object({ agent: Agent }));
239
+ var AgentStatusChanged = event(
240
+ "agent.status_changed",
241
+ AgentSubject,
242
+ z.object({ agent: Agent, previousStatus: AgentStatus })
243
+ );
244
+ var AgentRemoved = event(
245
+ "agent.removed",
246
+ AgentSubject,
247
+ z.object({ agentId: AgentId, organizationId: OrganizationId, nodeId: NodeId })
248
+ );
249
+ var MeshAgentAgentRegistered = event("mesh_agent.agent_registered", AgentSubject, AgentRegistration);
250
+ var MeshAgentAgentDeregistered = event("mesh_agent.agent_deregistered", AgentSubject, AgentRegistration);
251
+ var LinkRequested = event("link.requested", LinkSubject, z.object({ link: Link }));
252
+ var LinkUp = event("link.up", LinkSubject, z.object({ link: Link }));
253
+ var LinkUpdated = event("link.updated", LinkSubject, z.object({ link: Link }));
254
+ var LinkDown = event("link.down", LinkSubject, z.object({ link: Link }));
255
+ var LinkRemoved = event("link.removed", LinkSubject, z.object({ linkId: LinkId }));
256
+ var RoleGranted = event("role.granted", RoleBindingSubject, z.object({ binding: RoleBinding }));
257
+ var RoleRevoked = event("role.revoked", RoleBindingSubject, z.object({ binding: RoleBinding }));
258
+ var TaskRequested = event("task.requested", TaskSubject, z.object({ task: Task }));
259
+ var TaskAccepted = event("task.accepted", TaskSubject, z.object({ task: Task }));
260
+ var TaskCompleted = event("task.completed", TaskSubject, z.object({ task: Task }));
261
+ var TaskFailed = event("task.failed", TaskSubject, z.object({ task: Task }));
262
+ var DomainEvent = z.discriminatedUnion("type", [
263
+ NodeCreated,
264
+ NodeUpdated,
265
+ NodeRemoved,
266
+ NodeStatusChanged,
267
+ NodeHeartbeat,
268
+ OrganizationCreated,
269
+ OrganizationUpdated,
270
+ OrganizationRemoved,
271
+ AgentCreated,
272
+ AgentUpdated,
273
+ AgentStatusChanged,
274
+ AgentRemoved,
275
+ MeshAgentAgentRegistered,
276
+ MeshAgentAgentDeregistered,
277
+ LinkRequested,
278
+ LinkUp,
279
+ LinkUpdated,
280
+ LinkDown,
281
+ LinkRemoved,
282
+ RoleGranted,
283
+ RoleRevoked,
284
+ TaskRequested,
285
+ TaskAccepted,
286
+ TaskCompleted,
287
+ TaskFailed
288
+ ]).meta({ id: "DomainEvent" });
289
+ var DOMAIN_EVENT_TYPES = DomainEvent.options.map((o) => o.shape.type.value);
290
+ var ENVELOPE_VERSION = 1;
291
+ var EnvelopeMeta = z.object({
292
+ v: z.literal(ENVELOPE_VERSION),
293
+ id: EventId,
294
+ /** Monotonic per origin node; `(origin.nodeId, seq)` is the replication cursor. */
295
+ seq: z.int().min(1),
296
+ origin: z.object({ nodeId: NodeId, principalId: PrincipalId.nullable() }),
297
+ /** Groups the events produced by one command, e.g. a cascade (ADR-0005). */
298
+ causationId: CommandId,
299
+ timestamp: Timestamp,
300
+ /** Ed25519 signature over the canonical encoding; attached by the protocol layer (Phase 5). */
301
+ sig: z.string().nullable()
302
+ });
303
+ var MeshEvent = z.intersection(EnvelopeMeta, DomainEvent).meta({ id: "MeshEvent" });
304
+ var HealthResponse = z.object({
305
+ status: z.enum(["ok", "degraded"]),
306
+ service: z.literal("node-server"),
307
+ /** The node this server runs as — clients use it to know where their writes are accepted (ADR-0004). */
308
+ nodeId: NodeId,
309
+ version: z.string(),
310
+ uptimeSeconds: z.number().nonnegative(),
311
+ timestamp: z.iso.datetime()
312
+ }).meta({ id: "HealthResponse", description: "Liveness and version information for a Node Server." });
313
+ var Me = z.object({ principal: Principal, roles: z.array(RoleBinding) }).meta({ id: "Me", description: "The authenticated principal and its role bindings." });
314
+ var CreatePrincipalRequest = z.object({ name: DisplayName, kind: PrincipalKind.default("user") }).meta({ id: "CreatePrincipalRequest" });
315
+ var Credential = z.discriminatedUnion("type", [
316
+ z.object({ type: z.literal("token"), token: z.string(), expiresAt: Timestamp }),
317
+ z.object({ type: z.literal("apiKey"), apiKey: z.string() })
318
+ ]).meta({ id: "Credential" });
319
+ var CreatePrincipalResponse = z.object({ principal: Principal, credential: Credential }).meta({ id: "CreatePrincipalResponse" });
320
+ var MeshCursor = z.record(NodeId, z.int().min(0)).meta({ id: "MeshCursor" });
321
+ var MeshSnapshot = z.object({
322
+ nodes: z.array(Node),
323
+ organizations: z.array(Organization),
324
+ agents: z.array(Agent),
325
+ links: z.array(Link),
326
+ /** The most recent tasks, newest first (ADR-0020). */
327
+ tasks: z.array(Task),
328
+ cursor: MeshCursor
329
+ }).meta({ id: "MeshSnapshot", description: "Full mesh state plus the cursor to resume the event stream from." });
330
+ var MeshStats = z.object({
331
+ nodes: z.int().min(0),
332
+ online: z.int().min(0),
333
+ degraded: z.int().min(0),
334
+ offline: z.int().min(0),
335
+ organizations: z.int().min(0),
336
+ agents: z.int().min(0)
337
+ }).meta({ id: "MeshStats", description: "Counters shown in the Monitor's mesh summary." });
338
+ var NodeDetail = z.object({
339
+ node: Node,
340
+ organizations: z.array(Organization),
341
+ agents: z.array(Agent),
342
+ /** Distinct capabilities offered by the node's agents. */
343
+ capabilities: z.array(Capability)
344
+ }).meta({ id: "NodeDetail", description: "Everything the Monitor's node detail panel shows (ui.md)." });
345
+ function encodeCursor(cursor) {
346
+ const bytes = new TextEncoder().encode(JSON.stringify(cursor));
347
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
348
+ }
349
+ function decodeCursor(encoded) {
350
+ const base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
351
+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
352
+ return MeshCursor.parse(JSON.parse(new TextDecoder().decode(bytes)));
353
+ }
354
+
355
+ // src/projection.ts
356
+ function project(event2) {
357
+ switch (event2.type) {
358
+ case "node.created":
359
+ case "node.updated":
360
+ return { op: "upsert", kind: "node", entity: event2.payload.node };
361
+ case "node.removed":
362
+ return { op: "delete", kind: "node", id: event2.payload.nodeId };
363
+ case "node.status_changed":
364
+ return {
365
+ op: "presence",
366
+ nodeId: event2.payload.nodeId,
367
+ status: event2.payload.status,
368
+ lastSeenAt: event2.payload.lastSeenAt
369
+ };
370
+ case "organization.created":
371
+ case "organization.updated":
372
+ return { op: "upsert", kind: "organization", entity: event2.payload.organization };
373
+ case "organization.removed":
374
+ return { op: "delete", kind: "organization", id: event2.payload.organizationId };
375
+ case "agent.created":
376
+ case "agent.updated":
377
+ case "agent.status_changed":
378
+ return { op: "upsert", kind: "agent", entity: event2.payload.agent };
379
+ case "agent.removed":
380
+ return { op: "delete", kind: "agent", id: event2.payload.agentId };
381
+ case "link.requested":
382
+ case "link.up":
383
+ case "link.updated":
384
+ case "link.down":
385
+ return { op: "upsert", kind: "link", entity: event2.payload.link };
386
+ case "link.removed":
387
+ return { op: "delete", kind: "link", id: event2.payload.linkId };
388
+ case "role.granted":
389
+ return { op: "upsert", kind: "roleBinding", entity: event2.payload.binding };
390
+ case "role.revoked":
391
+ return { op: "delete", kind: "roleBinding", id: event2.payload.binding.id };
392
+ case "task.requested":
393
+ case "task.accepted":
394
+ case "task.completed":
395
+ case "task.failed":
396
+ return { op: "upsert", kind: "task", entity: event2.payload.task };
397
+ // Registration is implied by organization membership; heartbeats are handled by the presence detector.
398
+ case "mesh_agent.agent_registered":
399
+ case "mesh_agent.agent_deregistered":
400
+ case "node.heartbeat":
401
+ return { op: "none" };
402
+ }
403
+ }
404
+
405
+ // src/mesh-state.ts
406
+ var byId = (items) => Object.fromEntries(items.map((item) => [item.id, item]));
407
+ function meshStateFromSnapshot(snapshot) {
408
+ return {
409
+ nodes: byId(snapshot.nodes),
410
+ organizations: byId(snapshot.organizations),
411
+ agents: byId(snapshot.agents),
412
+ links: byId(snapshot.links),
413
+ // Nodes from before Phase 6 send no tasks; tolerate them during rolling upgrades.
414
+ tasks: byId(snapshot.tasks ?? []),
415
+ cursor: { ...snapshot.cursor }
416
+ };
417
+ }
418
+ function applyMeshEvent(state, event2) {
419
+ const seen = state.cursor[event2.origin.nodeId] ?? 0;
420
+ if (event2.seq <= seen) return state;
421
+ const cursor = { ...state.cursor, [event2.origin.nodeId]: event2.seq };
422
+ const op = project(event2);
423
+ switch (op.op) {
424
+ case "upsert":
425
+ switch (op.kind) {
426
+ case "node":
427
+ return { ...state, cursor, nodes: { ...state.nodes, [op.entity.id]: op.entity } };
428
+ case "organization":
429
+ return { ...state, cursor, organizations: { ...state.organizations, [op.entity.id]: op.entity } };
430
+ case "agent":
431
+ return { ...state, cursor, agents: { ...state.agents, [op.entity.id]: op.entity } };
432
+ case "link":
433
+ return { ...state, cursor, links: { ...state.links, [op.entity.id]: op.entity } };
434
+ case "roleBinding":
435
+ return { ...state, cursor };
436
+ case "task": {
437
+ const current = state.tasks[op.entity.id];
438
+ if (current && current.version >= op.entity.version) return { ...state, cursor };
439
+ return { ...state, cursor, tasks: { ...state.tasks, [op.entity.id]: op.entity } };
440
+ }
441
+ }
442
+ break;
443
+ case "delete": {
444
+ if (op.kind === "roleBinding") return { ...state, cursor };
445
+ const table = { node: "nodes", organization: "organizations", agent: "agents", link: "links" };
446
+ const key = table[op.kind];
447
+ const { [op.id]: _removed, ...rest } = state[key];
448
+ return { ...state, cursor, [key]: rest };
449
+ }
450
+ case "presence": {
451
+ const node = state.nodes[op.nodeId];
452
+ if (!node) return { ...state, cursor };
453
+ return {
454
+ ...state,
455
+ cursor,
456
+ nodes: { ...state.nodes, [node.id]: { ...node, status: op.status, lastSeenAt: op.lastSeenAt } }
457
+ };
458
+ }
459
+ case "none":
460
+ return { ...state, cursor };
461
+ }
462
+ }
463
+ var PageQuery = z.object({
464
+ limit: z.coerce.number().int().min(1).max(200).default(50),
465
+ cursor: z.string().min(1).optional()
466
+ });
467
+ var Page = (item, id) => z.object({ items: z.array(item), nextCursor: z.string().nullable() }).meta({ id });
468
+ var ProblemDetails = z.object({
469
+ type: z.string().meta({ example: "/problems/forbidden" }),
470
+ title: z.string(),
471
+ status: z.int().min(400).max(599),
472
+ detail: z.string().optional(),
473
+ instance: z.string().optional(),
474
+ code: z.string().meta({ description: "Stable machine-readable error code" }),
475
+ errors: z.array(z.object({ path: z.string(), message: z.string() })).optional()
476
+ }).meta({ id: "ProblemDetails" });
477
+ var Topic = z.enum(["node", "organization", "agent", "link", "roleBinding", "task"]);
478
+ var ClientMessage = z.discriminatedUnion("type", [
479
+ z.object({
480
+ type: z.literal("hello"),
481
+ /** Bearer token or API key — sent in the first frame because browsers cannot set WebSocket headers. */
482
+ token: z.string().min(1),
483
+ /** Resume point, usually the cursor of the snapshot the client just loaded. */
484
+ cursor: MeshCursor.optional(),
485
+ topics: z.array(Topic).optional()
486
+ }),
487
+ z.object({ type: z.literal("subscribe"), topics: z.array(Topic) })
488
+ ]);
489
+ var ServerMessage = z.discriminatedUnion("type", [
490
+ z.object({ type: z.literal("welcome"), principalId: PrincipalId, cursor: MeshCursor }),
491
+ z.object({ type: z.literal("event"), event: MeshEvent }),
492
+ z.object({ type: z.literal("resync.required"), reason: z.string() }),
493
+ z.object({ type: z.literal("error"), code: z.string(), message: z.string() })
494
+ ]);
495
+ var RealtimeCloseCode = {
496
+ normal: 1e3,
497
+ goingAway: 1001,
498
+ badMessage: 4400,
499
+ unauthenticated: 4401,
500
+ helloTimeout: 4408,
501
+ resyncRequired: 4409
502
+ };
503
+
504
+ export { Agent, AgentCreated, AgentId, AgentKind, AgentRemoved, AgentStatus, AgentStatusChanged, AgentUpdated, Capability, CapabilityName, CapabilityProvider, ClientMessage, CommandId, CreateAgentRequest, CreateLinkRequest, CreateOrganizationRequest, CreatePrincipalRequest, CreatePrincipalResponse, Credential, DOMAIN_EVENT_TYPES, DisplayName, DomainEvent, ENVELOPE_VERSION, EntityAudit, EnvelopeMeta, EventId, GrantOwnerRequest, HealthResponse, ID_PREFIX, Link, LinkDown, LinkId, LinkQuality, LinkRemoved, LinkRequested, LinkState, LinkUp, LinkUpdated, Me, MeshAgentAgentDeregistered, MeshAgentAgentRegistered, MeshCursor, MeshEvent, MeshSnapshot, MeshStats, Metadata, Node, NodeCreated, NodeDetail, NodeHeartbeat, NodeId, NodeRemoved, NodeStatus, NodeStatusChanged, NodeUpdated, Organization, OrganizationCreated, OrganizationId, OrganizationRemoved, OrganizationUpdated, Page, PageQuery, Principal, PrincipalId, PrincipalKind, ProblemDetails, RealtimeCloseCode, RequestTaskRequest, Role, RoleBinding, RoleBindingId, RoleGranted, RoleRevoked, RoleScope, ServerMessage, Slug, TERMINAL_TASK_STATUSES, Task, TaskAccepted, TaskAssignee, TaskCompleted, TaskError, TaskFailed, TaskId, TaskParty, TaskRequested, TaskStatus, TaskStep, Timestamp, Topic, TransportKind, ULID_PATTERN, UpdateAgentRequest, UpdateNodeRequest, UpdateOrganizationRequest, Version, applyMeshEvent, decodeCursor, encodeCursor, meshStateFromSnapshot, prefixedId, project };
505
+ //# sourceMappingURL=index.js.map
506
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/capability.ts","../src/common.ts","../src/ids.ts","../src/agent.ts","../src/auth.ts","../src/link.ts","../src/node.ts","../src/organization.ts","../src/task.ts","../src/events.ts","../src/health.ts","../src/identity.ts","../src/mesh.ts","../src/projection.ts","../src/mesh-state.ts","../src/page.ts","../src/problem.ts","../src/realtime.ts"],"names":["z","event"],"mappings":";;;AAGO,IAAM,cAAA,GAAiB,EAC3B,MAAA,EAAO,CACP,MAAM,yCAAA,EAA2C,8CAA8C,CAAA,CAC/F,GAAA,CAAI,GAAG;AAGH,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CAAA;AAAA,EACnEA,EAAE,MAAA,CAAO,EAAE,IAAA,EAAMA,CAAAA,CAAE,QAAQ,OAAO,CAAA,EAAG,IAAA,EAAMA,CAAAA,CAAE,QAAO,EAAG,OAAA,EAASA,CAAAA,CAAE,MAAA,IAAU;AAC9E,CAAC;AAIM,IAAM,iBAAA,GAAoB;AAAA,EAC/B,MAAA,EAAQ,GAAA;AAAA,EACR,SAAA,EAAW,IAAA;AAAA,EACX,UAAA,EAAY,IAAA;AAAA,EACZ,eAAA,EAAiB,IAAA;AAAA,EACjB,YAAA,EAAc,IAAA;AAAA,EACd,cAAA,EAAgB;AAClB","file":"index.js","sourcesContent":["import { z } from \"zod\";\n\n/** Dotted, lowercase capability name, e.g. `vision` or `terrain.analysis` (deck slide 07). */\nexport const CapabilityName = z\n .string()\n .regex(/^[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*$/, \"Dotted lowercase name, e.g. terrain.analysis\")\n .max(100);\nexport type CapabilityName = z.infer<typeof CapabilityName>;\n\nexport const Capability = z\n .object({\n name: CapabilityName,\n version: z.string().max(32).default(\"1.0.0\"),\n description: z.string().max(500).optional(),\n })\n .meta({ id: \"Capability\", description: \"A machine-discoverable description of what an agent can perform.\" });\nexport type Capability = z.infer<typeof Capability>;\n","import { z } from \"zod\";\n\n/** ISO-8601 UTC timestamp with milliseconds, e.g. `2026-09-28T09:28:12.123Z`. */\nexport const Timestamp = z.iso.datetime().meta({ example: \"2026-09-28T09:28:12.123Z\" });\nexport type Timestamp = z.infer<typeof Timestamp>;\n\n/** Monotonic per-entity version used for replication and optimistic concurrency (ADR-0004). */\nexport const Version = z.int().min(1).meta({ description: \"Monotonic per-entity version\" });\nexport type Version = z.infer<typeof Version>;\n\n/** Human-readable display name. */\nexport const DisplayName = z.string().trim().min(1).max(120);\n\n/** URL-safe identifier, unique within its parent (e.g. an organization within a node). */\nexport const Slug = z\n .string()\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, \"Lowercase letters, digits and single hyphens\")\n .max(63);\nexport type Slug = z.infer<typeof Slug>;\n\n/** Free-form, JSON-serialisable metadata. */\nexport const Metadata = z.record(z.string(), z.unknown());\nexport type Metadata = z.infer<typeof Metadata>;\n\n/** Fields every replicated entity carries. */\nexport const EntityAudit = {\n version: Version,\n createdAt: Timestamp,\n updatedAt: Timestamp,\n};\n","import { z } from \"zod\";\n\n/** Prefixes for time-sortable ULID identifiers (ROADMAP §2.3). */\nexport const ID_PREFIX = {\n node: \"node\",\n organization: \"org\",\n agent: \"agt\",\n link: \"lnk\",\n event: \"evt\",\n command: \"cmd\",\n principal: \"prn\",\n roleBinding: \"rol\",\n apiKey: \"key\",\n task: \"tsk\",\n} as const;\n\nexport type IdKind = keyof typeof ID_PREFIX;\n\n/** Crockford base32 ULID body (26 chars, no I, L, O, U). */\nexport const ULID_PATTERN = \"[0-9A-HJKMNP-TV-Z]{26}\";\n\n/** Builds a Zod schema that validates `<prefix>_<ULID>` identifiers. */\nexport const prefixedId = <K extends IdKind>(kind: K) =>\n z\n .string()\n .regex(new RegExp(`^${ID_PREFIX[kind]}_${ULID_PATTERN}$`), `Expected a ${kind} id (${ID_PREFIX[kind]}_<ULID>)`)\n .meta({ description: `${kind} identifier`, example: `${ID_PREFIX[kind]}_01J9Z3K7Q8R5T2V4W6X8Y0A1B2` });\n\nexport const NodeId = prefixedId(\"node\");\nexport const OrganizationId = prefixedId(\"organization\");\nexport const AgentId = prefixedId(\"agent\");\nexport const LinkId = prefixedId(\"link\");\nexport const EventId = prefixedId(\"event\");\nexport const CommandId = prefixedId(\"command\");\nexport const PrincipalId = prefixedId(\"principal\");\nexport const RoleBindingId = prefixedId(\"roleBinding\");\nexport const TaskId = prefixedId(\"task\");\n\nexport type NodeId = z.infer<typeof NodeId>;\nexport type OrganizationId = z.infer<typeof OrganizationId>;\nexport type AgentId = z.infer<typeof AgentId>;\nexport type LinkId = z.infer<typeof LinkId>;\nexport type EventId = z.infer<typeof EventId>;\nexport type CommandId = z.infer<typeof CommandId>;\nexport type PrincipalId = z.infer<typeof PrincipalId>;\nexport type RoleBindingId = z.infer<typeof RoleBindingId>;\nexport type TaskId = z.infer<typeof TaskId>;\n","import { z } from \"zod\";\nimport { Capability } from \"./capability.ts\";\nimport { DisplayName, EntityAudit, Metadata } from \"./common.ts\";\nimport { AgentId, NodeId, OrganizationId } from \"./ids.ts\";\n\n/** `mesh` marks the organization's Mesh Agent — exactly one per organization (ADR-0003). */\nexport const AgentKind = z.enum([\"standard\", \"mesh\"]);\nexport type AgentKind = z.infer<typeof AgentKind>;\n\nexport const AgentStatus = z.enum([\"created\", \"starting\", \"running\", \"stopped\", \"error\"]);\nexport type AgentStatus = z.infer<typeof AgentStatus>;\n\nconst capabilityList = z\n .array(Capability)\n .max(64)\n .refine((caps) => new Set(caps.map((c) => c.name)).size === caps.length, \"Capability names must be unique\");\n\nexport const Agent = z\n .object({\n id: AgentId,\n organizationId: OrganizationId,\n nodeId: NodeId,\n name: DisplayName,\n kind: AgentKind,\n status: AgentStatus,\n capabilities: capabilityList,\n /** Model backing the agent, e.g. `claude-sonnet-5`; null for rule-based agents. */\n model: z.string().max(100).nullable(),\n metadata: Metadata,\n ...EntityAudit,\n })\n .meta({ id: \"Agent\", description: \"An autonomous software entity with identity, capabilities and policies.\" });\nexport type Agent = z.infer<typeof Agent>;\n\nexport const CreateAgentRequest = z\n .object({\n name: DisplayName,\n capabilities: capabilityList.default([]),\n model: z.string().max(100).nullable().default(null),\n metadata: Metadata.optional(),\n })\n .meta({ id: \"CreateAgentRequest\" });\n/** Parsed request (defaults applied) — what use cases receive. */\nexport type CreateAgentRequest = z.infer<typeof CreateAgentRequest>;\n/** What callers may send — capabilities and model are optional. */\nexport type CreateAgentRequestInput = z.input<typeof CreateAgentRequest>;\n\nexport const UpdateAgentRequest = z\n .object({\n name: DisplayName.optional(),\n capabilities: capabilityList.optional(),\n model: z.string().max(100).nullable().optional(),\n metadata: Metadata.optional(),\n })\n .refine((body) => Object.keys(body).length > 0, \"At least one field must be provided\")\n .meta({ id: \"UpdateAgentRequest\" });\nexport type UpdateAgentRequest = z.infer<typeof UpdateAgentRequest>;\n","import { z } from \"zod\";\nimport { DisplayName, Timestamp } from \"./common.ts\";\nimport { NodeId, OrganizationId, PrincipalId, RoleBindingId } from \"./ids.ts\";\n\nexport const PrincipalKind = z.enum([\"user\", \"service\"]);\nexport type PrincipalKind = z.infer<typeof PrincipalKind>;\n\nexport const Principal = z\n .object({\n id: PrincipalId,\n kind: PrincipalKind,\n name: DisplayName,\n publicKey: z.string().nullable(),\n createdAt: Timestamp,\n })\n .meta({ id: \"Principal\", description: \"A user or service that can be authenticated and granted roles.\" });\nexport type Principal = z.infer<typeof Principal>;\n\n/** Ownership roles (ADR-0010). */\nexport const Role = z.enum([\"node_owner\", \"org_owner\"]);\nexport type Role = z.infer<typeof Role>;\n\nexport const RoleScope = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"node\"), nodeId: NodeId }),\n z.object({ type: z.literal(\"organization\"), organizationId: OrganizationId, nodeId: NodeId }),\n]);\nexport type RoleScope = z.infer<typeof RoleScope>;\n\nexport const RoleBinding = z\n .object({\n id: RoleBindingId,\n principalId: PrincipalId,\n role: Role,\n scope: RoleScope,\n createdAt: Timestamp,\n })\n .refine(\n (b) => (b.role === \"node_owner\" ? b.scope.type === \"node\" : b.scope.type === \"organization\"),\n \"node_owner must be node-scoped and org_owner organization-scoped\",\n )\n .meta({ id: \"RoleBinding\" });\nexport type RoleBinding = z.infer<typeof RoleBinding>;\n\nexport const GrantOwnerRequest = z.object({ principalId: PrincipalId }).meta({ id: \"GrantOwnerRequest\" });\nexport type GrantOwnerRequest = z.infer<typeof GrantOwnerRequest>;\n","import { z } from \"zod\";\nimport { EntityAudit, Timestamp } from \"./common.ts\";\nimport { LinkId, NodeId } from \"./ids.ts\";\n\nexport const TransportKind = z.enum([\"memory\", \"ws-peer\", \"tcp\", \"mqtt\", \"meshtastic\", \"meshcore\"]);\nexport type TransportKind = z.infer<typeof TransportKind>;\n\n/** `requested` = an owner drew the edge in the Monitor and the peer has not accepted yet (ADR-0008). */\nexport const LinkState = z.enum([\"requested\", \"up\", \"down\"]);\nexport type LinkState = z.infer<typeof LinkState>;\n\nexport const LinkQuality = z.object({\n latencyMs: z.number().nonnegative().optional(),\n rssi: z.number().optional(),\n});\nexport type LinkQuality = z.infer<typeof LinkQuality>;\n\nexport const Link = z\n .object({\n id: LinkId,\n aNodeId: NodeId,\n bNodeId: NodeId,\n transport: TransportKind,\n state: LinkState,\n quality: LinkQuality,\n lastSeenAt: Timestamp.nullable(),\n ...EntityAudit,\n })\n .refine((link) => link.aNodeId !== link.bNodeId, \"A link must connect two different nodes\")\n .meta({ id: \"Link\", description: \"Transport-level adjacency between two nodes — the edges of the topology.\" });\nexport type Link = z.infer<typeof Link>;\n\nexport const CreateLinkRequest = z\n .object({ aNodeId: NodeId, bNodeId: NodeId, transport: TransportKind })\n .refine((body) => body.aNodeId !== body.bNodeId, \"A link must connect two different nodes\")\n .meta({ id: \"CreateLinkRequest\" });\nexport type CreateLinkRequest = z.infer<typeof CreateLinkRequest>;\n","import { z } from \"zod\";\nimport { DisplayName, EntityAudit, Metadata, Timestamp } from \"./common.ts\";\nimport { NodeId } from \"./ids.ts\";\n\nexport const NodeStatus = z.enum([\"online\", \"degraded\", \"offline\"]);\nexport type NodeStatus = z.infer<typeof NodeStatus>;\n\nexport const Node = z\n .object({\n id: NodeId,\n name: DisplayName,\n publicKey: z.string().min(1),\n /** Base URL where other nodes and clients reach this node, e.g. `https://node-a.example:7700` (ADR-0017). */\n endpoint: z.url().nullable(),\n status: NodeStatus,\n metadata: Metadata,\n lastSeenAt: Timestamp.nullable(),\n ...EntityAudit,\n })\n .meta({ id: \"Node\", description: \"A physical or virtual endpoint connected to the mesh.\" });\nexport type Node = z.infer<typeof Node>;\n\nexport const UpdateNodeRequest = z\n .object({\n name: DisplayName.optional(),\n endpoint: z.url().nullable().optional(),\n metadata: Metadata.optional(),\n })\n .refine((body) => Object.keys(body).length > 0, \"At least one field must be provided\")\n .meta({ id: \"UpdateNodeRequest\" });\nexport type UpdateNodeRequest = z.infer<typeof UpdateNodeRequest>;\n","import { z } from \"zod\";\nimport { DisplayName, EntityAudit, Metadata, Slug } from \"./common.ts\";\nimport { NodeId, OrganizationId, PrincipalId } from \"./ids.ts\";\n\nexport const Organization = z\n .object({\n id: OrganizationId,\n nodeId: NodeId,\n name: DisplayName,\n slug: Slug,\n metadata: Metadata,\n ...EntityAudit,\n })\n .meta({ id: \"Organization\", description: \"A logical boundary on a node that owns policies, identities and agents.\" });\nexport type Organization = z.infer<typeof Organization>;\n\nexport const CreateOrganizationRequest = z\n .object({\n name: DisplayName,\n /** Derived from `name` when omitted. */\n slug: Slug.optional(),\n metadata: Metadata.optional(),\n /** Principal to make the first org owner; defaults to the caller. */\n ownerPrincipalId: PrincipalId.optional(),\n })\n .meta({ id: \"CreateOrganizationRequest\" });\nexport type CreateOrganizationRequest = z.infer<typeof CreateOrganizationRequest>;\n\nexport const UpdateOrganizationRequest = z\n .object({\n name: DisplayName.optional(),\n metadata: Metadata.optional(),\n })\n .refine((body) => Object.keys(body).length > 0, \"At least one field must be provided\")\n .meta({ id: \"UpdateOrganizationRequest\" });\nexport type UpdateOrganizationRequest = z.infer<typeof UpdateOrganizationRequest>;\n","import { z } from \"zod\";\nimport { CapabilityName } from \"./capability.ts\";\nimport { Metadata, Timestamp, Version } from \"./common.ts\";\nimport { AgentId, NodeId, OrganizationId, TaskId } from \"./ids.ts\";\n\n/**\n * A capability request between agents (ADR-0020, deck slides 06/07). Created by the requester's node; every later\n * change is written by the assignee's node only.\n */\nexport const TaskStatus = z.enum([\"requested\", \"accepted\", \"completed\", \"failed\"]);\nexport type TaskStatus = z.infer<typeof TaskStatus>;\n\nexport const TERMINAL_TASK_STATUSES: readonly TaskStatus[] = [\"completed\", \"failed\"];\n\n/** An agent taking part in a task, with where it lives. */\nexport const TaskParty = z.object({ agentId: AgentId, organizationId: OrganizationId, nodeId: NodeId });\nexport type TaskParty = z.infer<typeof TaskParty>;\n\n/** The organization a task was routed to, through its Mesh Agent. */\nexport const TaskAssignee = z.object({ organizationId: OrganizationId, nodeId: NodeId, meshAgentId: AgentId });\nexport type TaskAssignee = z.infer<typeof TaskAssignee>;\n\n/** One stage of the observe → reason → act → verify pipeline (deck slide 05). */\nexport const TaskStep = z.object({\n name: z.enum([\"observe\", \"reason\", \"act\", \"verify\"]),\n at: Timestamp,\n summary: z.string().max(1000),\n});\nexport type TaskStep = z.infer<typeof TaskStep>;\n\nexport const TaskError = z.object({ code: z.string().max(64), message: z.string().max(1000) });\nexport type TaskError = z.infer<typeof TaskError>;\n\nexport const Task = z\n .object({\n id: TaskId,\n capability: CapabilityName,\n input: Metadata,\n status: TaskStatus,\n requester: TaskParty,\n /** The requester organization's Mesh Agent, the first hop of the route. */\n requesterMeshAgentId: AgentId,\n assignee: TaskAssignee,\n /** The agent that does the work, chosen by the assignee's Mesh Agent on acceptance. */\n provider: TaskParty.nullable(),\n output: Metadata.nullable(),\n error: TaskError.nullable(),\n steps: z.array(TaskStep).max(32),\n /** Model that produced the result; null when a rule-based model did. */\n model: z.string().max(100).nullable(),\n version: Version,\n createdAt: Timestamp,\n updatedAt: Timestamp,\n })\n .meta({\n id: \"Task\",\n description: \"A capability request routed through Mesh Agents, with its result and provenance (ADR-0020).\",\n });\nexport type Task = z.infer<typeof Task>;\n\nexport const RequestTaskRequest = z\n .object({\n capability: CapabilityName,\n input: Metadata.default({}),\n })\n .meta({ id: \"RequestTaskRequest\" });\nexport type RequestTaskRequest = z.infer<typeof RequestTaskRequest>;\nexport type RequestTaskRequestInput = z.input<typeof RequestTaskRequest>;\n\n/** An agent offering a capability, as listed by the capability directory. */\nexport const CapabilityProvider = z\n .object({\n agentId: AgentId,\n agentName: z.string(),\n organizationId: OrganizationId,\n organizationName: z.string(),\n nodeId: NodeId,\n /** Running, on a node that is not offline — i.e. a task could be routed to it now. */\n available: z.boolean(),\n })\n .meta({ id: \"CapabilityProvider\" });\nexport type CapabilityProvider = z.infer<typeof CapabilityProvider>;\n","import { z } from \"zod\";\nimport { Agent, AgentStatus } from \"./agent.ts\";\nimport { RoleBinding } from \"./auth.ts\";\nimport { Timestamp, Version } from \"./common.ts\";\nimport {\n AgentId,\n CommandId,\n EventId,\n LinkId,\n NodeId,\n OrganizationId,\n PrincipalId,\n RoleBindingId,\n TaskId,\n} from \"./ids.ts\";\nimport { Link } from \"./link.ts\";\nimport { Node, NodeStatus } from \"./node.ts\";\nimport { Organization } from \"./organization.ts\";\nimport { Task } from \"./task.ts\";\n\n/**\n * Event catalog (ROADMAP §2.4). Every state change in the mesh is one of these events.\n *\n * A *domain event* is what the domain produces: `type`, `subject` and `payload`.\n * A *mesh event* wraps it in the envelope (id, seq, origin, causation, timestamp, signature)\n * when it is committed, replicated and pushed to clients.\n */\n\nconst subject = <K extends string, S extends z.ZodType<string>>(kind: K, id: S) =>\n z.object({ kind: z.literal(kind), id, version: Version });\n\nconst NodeSubject = subject(\"node\", NodeId);\nconst OrganizationSubject = subject(\"organization\", OrganizationId);\nconst AgentSubject = subject(\"agent\", AgentId);\nconst LinkSubject = subject(\"link\", LinkId);\nconst RoleBindingSubject = subject(\"roleBinding\", RoleBindingId);\nconst TaskSubject = subject(\"task\", TaskId);\n\nconst event = <T extends string, S extends z.ZodType, P extends z.ZodType>(type: T, subjectSchema: S, payload: P) =>\n z.object({ type: z.literal(type), subject: subjectSchema, payload });\n\nconst AgentRegistration = z.object({\n meshAgentId: AgentId,\n agentId: AgentId,\n organizationId: OrganizationId,\n nodeId: NodeId,\n});\n\nexport const NodeCreated = event(\"node.created\", NodeSubject, z.object({ node: Node }));\nexport const NodeUpdated = event(\"node.updated\", NodeSubject, z.object({ node: Node }));\nexport const NodeRemoved = event(\"node.removed\", NodeSubject, z.object({ nodeId: NodeId }));\n/** Derived locally by each node's presence detector; does not bump the owned entity version. */\nexport const NodeStatusChanged = event(\n \"node.status_changed\",\n NodeSubject,\n z.object({ nodeId: NodeId, status: NodeStatus, previousStatus: NodeStatus, lastSeenAt: Timestamp.nullable() }),\n);\n/** Mesh-only liveness signal; aggregated into `lastSeenAt`, never forwarded to UI clients. */\nexport const NodeHeartbeat = event(\"node.heartbeat\", NodeSubject, z.object({ nodeId: NodeId, at: Timestamp }));\n\nexport const OrganizationCreated = event(\n \"organization.created\",\n OrganizationSubject,\n z.object({ organization: Organization }),\n);\nexport const OrganizationUpdated = event(\n \"organization.updated\",\n OrganizationSubject,\n z.object({ organization: Organization }),\n);\nexport const OrganizationRemoved = event(\n \"organization.removed\",\n OrganizationSubject,\n z.object({ organizationId: OrganizationId, nodeId: NodeId }),\n);\n\nexport const AgentCreated = event(\"agent.created\", AgentSubject, z.object({ agent: Agent }));\nexport const AgentUpdated = event(\"agent.updated\", AgentSubject, z.object({ agent: Agent }));\nexport const AgentStatusChanged = event(\n \"agent.status_changed\",\n AgentSubject,\n z.object({ agent: Agent, previousStatus: AgentStatus }),\n);\nexport const AgentRemoved = event(\n \"agent.removed\",\n AgentSubject,\n z.object({ agentId: AgentId, organizationId: OrganizationId, nodeId: NodeId }),\n);\n\nexport const MeshAgentAgentRegistered = event(\"mesh_agent.agent_registered\", AgentSubject, AgentRegistration);\nexport const MeshAgentAgentDeregistered = event(\"mesh_agent.agent_deregistered\", AgentSubject, AgentRegistration);\n\nexport const LinkRequested = event(\"link.requested\", LinkSubject, z.object({ link: Link }));\nexport const LinkUp = event(\"link.up\", LinkSubject, z.object({ link: Link }));\nexport const LinkUpdated = event(\"link.updated\", LinkSubject, z.object({ link: Link }));\nexport const LinkDown = event(\"link.down\", LinkSubject, z.object({ link: Link }));\nexport const LinkRemoved = event(\"link.removed\", LinkSubject, z.object({ linkId: LinkId }));\n\nexport const RoleGranted = event(\"role.granted\", RoleBindingSubject, z.object({ binding: RoleBinding }));\nexport const RoleRevoked = event(\"role.revoked\", RoleBindingSubject, z.object({ binding: RoleBinding }));\n\n/** Committed by the requester's node; the task's later events come from the assignee's node only (ADR-0020). */\nexport const TaskRequested = event(\"task.requested\", TaskSubject, z.object({ task: Task }));\nexport const TaskAccepted = event(\"task.accepted\", TaskSubject, z.object({ task: Task }));\nexport const TaskCompleted = event(\"task.completed\", TaskSubject, z.object({ task: Task }));\nexport const TaskFailed = event(\"task.failed\", TaskSubject, z.object({ task: Task }));\n\nexport const DomainEvent = z\n .discriminatedUnion(\"type\", [\n NodeCreated,\n NodeUpdated,\n NodeRemoved,\n NodeStatusChanged,\n NodeHeartbeat,\n OrganizationCreated,\n OrganizationUpdated,\n OrganizationRemoved,\n AgentCreated,\n AgentUpdated,\n AgentStatusChanged,\n AgentRemoved,\n MeshAgentAgentRegistered,\n MeshAgentAgentDeregistered,\n LinkRequested,\n LinkUp,\n LinkUpdated,\n LinkDown,\n LinkRemoved,\n RoleGranted,\n RoleRevoked,\n TaskRequested,\n TaskAccepted,\n TaskCompleted,\n TaskFailed,\n ])\n .meta({ id: \"DomainEvent\" });\nexport type DomainEvent = z.infer<typeof DomainEvent>;\nexport type DomainEventType = DomainEvent[\"type\"];\nexport type DomainEventOf<T extends DomainEventType> = Extract<DomainEvent, { type: T }>;\n\nexport const DOMAIN_EVENT_TYPES = DomainEvent.options.map((o) => o.shape.type.value) as readonly DomainEventType[];\n\n/** Envelope schema version (ADR-0009). */\nexport const ENVELOPE_VERSION = 1 as const;\n\nexport const EnvelopeMeta = z.object({\n v: z.literal(ENVELOPE_VERSION),\n id: EventId,\n /** Monotonic per origin node; `(origin.nodeId, seq)` is the replication cursor. */\n seq: z.int().min(1),\n origin: z.object({ nodeId: NodeId, principalId: PrincipalId.nullable() }),\n /** Groups the events produced by one command, e.g. a cascade (ADR-0005). */\n causationId: CommandId,\n timestamp: Timestamp,\n /** Ed25519 signature over the canonical encoding; attached by the protocol layer (Phase 5). */\n sig: z.string().nullable(),\n});\nexport type EnvelopeMeta = z.infer<typeof EnvelopeMeta>;\n\nexport const MeshEvent = z.intersection(EnvelopeMeta, DomainEvent).meta({ id: \"MeshEvent\" });\nexport type MeshEvent = z.infer<typeof MeshEvent>;\n","import { z } from \"zod\";\nimport { NodeId } from \"./ids.ts\";\n\nexport const HealthResponse = z\n .object({\n status: z.enum([\"ok\", \"degraded\"]),\n service: z.literal(\"node-server\"),\n /** The node this server runs as — clients use it to know where their writes are accepted (ADR-0004). */\n nodeId: NodeId,\n version: z.string(),\n uptimeSeconds: z.number().nonnegative(),\n timestamp: z.iso.datetime(),\n })\n .meta({ id: \"HealthResponse\", description: \"Liveness and version information for a Node Server.\" });\n\nexport type HealthResponse = z.infer<typeof HealthResponse>;\n","import { z } from \"zod\";\nimport { Principal, PrincipalKind, RoleBinding } from \"./auth.ts\";\nimport { DisplayName, Timestamp } from \"./common.ts\";\n\n/** Who the caller is and which ownership roles they hold — drives the Monitor's controls (ADR-0010). */\nexport const Me = z\n .object({ principal: Principal, roles: z.array(RoleBinding) })\n .meta({ id: \"Me\", description: \"The authenticated principal and its role bindings.\" });\nexport type Me = z.infer<typeof Me>;\n\nexport const CreatePrincipalRequest = z\n .object({ name: DisplayName, kind: PrincipalKind.default(\"user\") })\n .meta({ id: \"CreatePrincipalRequest\" });\nexport type CreatePrincipalRequest = z.infer<typeof CreatePrincipalRequest>;\n\n/** Shown exactly once. Users get a bearer token; services get a long-lived API key. */\nexport const Credential = z\n .discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"token\"), token: z.string(), expiresAt: Timestamp }),\n z.object({ type: z.literal(\"apiKey\"), apiKey: z.string() }),\n ])\n .meta({ id: \"Credential\" });\nexport type Credential = z.infer<typeof Credential>;\n\nexport const CreatePrincipalResponse = z\n .object({ principal: Principal, credential: Credential })\n .meta({ id: \"CreatePrincipalResponse\" });\nexport type CreatePrincipalResponse = z.infer<typeof CreatePrincipalResponse>;\n","import { z } from \"zod\";\nimport { Agent } from \"./agent.ts\";\nimport { Capability } from \"./capability.ts\";\nimport { NodeId } from \"./ids.ts\";\nimport { Link } from \"./link.ts\";\nimport { Node } from \"./node.ts\";\nimport { Organization } from \"./organization.ts\";\nimport { Task } from \"./task.ts\";\n\n/** Per-origin-node sequence reached by a replica: `{ [nodeId]: seq }`. */\nexport const MeshCursor = z.record(NodeId, z.int().min(0)).meta({ id: \"MeshCursor\" });\nexport type MeshCursor = z.infer<typeof MeshCursor>;\n\nexport const MeshSnapshot = z\n .object({\n nodes: z.array(Node),\n organizations: z.array(Organization),\n agents: z.array(Agent),\n links: z.array(Link),\n /** The most recent tasks, newest first (ADR-0020). */\n tasks: z.array(Task),\n cursor: MeshCursor,\n })\n .meta({ id: \"MeshSnapshot\", description: \"Full mesh state plus the cursor to resume the event stream from.\" });\nexport type MeshSnapshot = z.infer<typeof MeshSnapshot>;\n\nexport const MeshStats = z\n .object({\n nodes: z.int().min(0),\n online: z.int().min(0),\n degraded: z.int().min(0),\n offline: z.int().min(0),\n organizations: z.int().min(0),\n agents: z.int().min(0),\n })\n .meta({ id: \"MeshStats\", description: \"Counters shown in the Monitor's mesh summary.\" });\nexport type MeshStats = z.infer<typeof MeshStats>;\n\nexport const NodeDetail = z\n .object({\n node: Node,\n organizations: z.array(Organization),\n agents: z.array(Agent),\n /** Distinct capabilities offered by the node's agents. */\n capabilities: z.array(Capability),\n })\n .meta({ id: \"NodeDetail\", description: \"Everything the Monitor's node detail panel shows (ui.md).\" });\nexport type NodeDetail = z.infer<typeof NodeDetail>;\n\n/** Encodes a cursor for URLs (`?cursor=`): base64url of its JSON. */\nexport function encodeCursor(cursor: MeshCursor): string {\n const bytes = new TextEncoder().encode(JSON.stringify(cursor));\n return btoa(String.fromCharCode(...bytes))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n\n/** Decodes a cursor produced by `encodeCursor`. Throws on malformed input. */\nexport function decodeCursor(encoded: string): MeshCursor {\n const base64 = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n return MeshCursor.parse(JSON.parse(new TextDecoder().decode(bytes)));\n}\n","import type { Agent } from \"./agent.ts\";\nimport type { RoleBinding } from \"./auth.ts\";\nimport type { DomainEvent } from \"./events.ts\";\nimport type { Link } from \"./link.ts\";\nimport type { Node, NodeStatus } from \"./node.ts\";\nimport type { Organization } from \"./organization.ts\";\nimport type { Task } from \"./task.ts\";\n\n/**\n * Translates an event into the state change it implies. The node server's persistence applies these operations\n * atomically with the event append, replication (Phase 5) applies them for remote events, and clients (the SDK's\n * mesh mirror, the Monitor) apply them to their local copy — so nobody can disagree about what an event means.\n */\nexport type ProjectionOp =\n | { readonly op: \"upsert\"; readonly kind: \"node\"; readonly entity: Node }\n | { readonly op: \"upsert\"; readonly kind: \"organization\"; readonly entity: Organization }\n | { readonly op: \"upsert\"; readonly kind: \"agent\"; readonly entity: Agent }\n | { readonly op: \"upsert\"; readonly kind: \"link\"; readonly entity: Link }\n | { readonly op: \"upsert\"; readonly kind: \"roleBinding\"; readonly entity: RoleBinding }\n /** Tasks have two writers in turn (ADR-0020), so replicas apply only newer versions. */\n | { readonly op: \"upsert\"; readonly kind: \"task\"; readonly entity: Task }\n | {\n readonly op: \"delete\";\n readonly kind: \"node\" | \"organization\" | \"agent\" | \"link\" | \"roleBinding\";\n readonly id: string;\n }\n | {\n readonly op: \"presence\";\n readonly nodeId: string;\n readonly status: NodeStatus;\n readonly lastSeenAt: string | null;\n }\n | { readonly op: \"none\" };\n\nexport function project(event: DomainEvent): ProjectionOp {\n switch (event.type) {\n case \"node.created\":\n case \"node.updated\":\n return { op: \"upsert\", kind: \"node\", entity: event.payload.node };\n case \"node.removed\":\n return { op: \"delete\", kind: \"node\", id: event.payload.nodeId };\n case \"node.status_changed\":\n return {\n op: \"presence\",\n nodeId: event.payload.nodeId,\n status: event.payload.status,\n lastSeenAt: event.payload.lastSeenAt,\n };\n case \"organization.created\":\n case \"organization.updated\":\n return { op: \"upsert\", kind: \"organization\", entity: event.payload.organization };\n case \"organization.removed\":\n return { op: \"delete\", kind: \"organization\", id: event.payload.organizationId };\n case \"agent.created\":\n case \"agent.updated\":\n case \"agent.status_changed\":\n return { op: \"upsert\", kind: \"agent\", entity: event.payload.agent };\n case \"agent.removed\":\n return { op: \"delete\", kind: \"agent\", id: event.payload.agentId };\n case \"link.requested\":\n case \"link.up\":\n case \"link.updated\":\n case \"link.down\":\n return { op: \"upsert\", kind: \"link\", entity: event.payload.link };\n case \"link.removed\":\n return { op: \"delete\", kind: \"link\", id: event.payload.linkId };\n case \"role.granted\":\n return { op: \"upsert\", kind: \"roleBinding\", entity: event.payload.binding };\n case \"role.revoked\":\n return { op: \"delete\", kind: \"roleBinding\", id: event.payload.binding.id };\n case \"task.requested\":\n case \"task.accepted\":\n case \"task.completed\":\n case \"task.failed\":\n return { op: \"upsert\", kind: \"task\", entity: event.payload.task };\n // Registration is implied by organization membership; heartbeats are handled by the presence detector.\n case \"mesh_agent.agent_registered\":\n case \"mesh_agent.agent_deregistered\":\n case \"node.heartbeat\":\n return { op: \"none\" };\n }\n}\n","import type { Agent } from \"./agent.ts\";\nimport type { MeshEvent } from \"./events.ts\";\nimport type { Link } from \"./link.ts\";\nimport type { MeshCursor, MeshSnapshot } from \"./mesh.ts\";\nimport type { Node } from \"./node.ts\";\nimport type { Organization } from \"./organization.ts\";\nimport { project } from \"./projection.ts\";\nimport type { Task } from \"./task.ts\";\n\n/** A client-side mirror of the mesh, kept current by applying events to a snapshot. */\nexport interface MeshState {\n readonly nodes: Readonly<Record<string, Node>>;\n readonly organizations: Readonly<Record<string, Organization>>;\n readonly agents: Readonly<Record<string, Agent>>;\n readonly links: Readonly<Record<string, Link>>;\n readonly tasks: Readonly<Record<string, Task>>;\n readonly cursor: MeshCursor;\n}\n\nconst byId = <T extends { id: string }>(items: readonly T[]): Record<string, T> =>\n Object.fromEntries(items.map((item) => [item.id, item]));\n\nexport function meshStateFromSnapshot(snapshot: MeshSnapshot): MeshState {\n return {\n nodes: byId(snapshot.nodes),\n organizations: byId(snapshot.organizations),\n agents: byId(snapshot.agents),\n links: byId(snapshot.links),\n // Nodes from before Phase 6 send no tasks; tolerate them during rolling upgrades.\n tasks: byId(snapshot.tasks ?? []),\n cursor: { ...snapshot.cursor },\n };\n}\n\n/**\n * Applies one event immutably. Events at or below the cursor for their origin are ignored, so replays\n * and duplicates are harmless. Role bindings are not mirrored (they are not part of the snapshot).\n */\nexport function applyMeshEvent(state: MeshState, event: MeshEvent): MeshState {\n const seen = state.cursor[event.origin.nodeId] ?? 0;\n if (event.seq <= seen) return state;\n const cursor = { ...state.cursor, [event.origin.nodeId]: event.seq };\n const op = project(event);\n\n switch (op.op) {\n case \"upsert\":\n switch (op.kind) {\n case \"node\":\n return { ...state, cursor, nodes: { ...state.nodes, [op.entity.id]: op.entity } };\n case \"organization\":\n return { ...state, cursor, organizations: { ...state.organizations, [op.entity.id]: op.entity } };\n case \"agent\":\n return { ...state, cursor, agents: { ...state.agents, [op.entity.id]: op.entity } };\n case \"link\":\n return { ...state, cursor, links: { ...state.links, [op.entity.id]: op.entity } };\n case \"roleBinding\":\n return { ...state, cursor };\n case \"task\": {\n // Two writers in turn (ADR-0020): an older version arriving late must not win.\n const current = state.tasks[op.entity.id];\n if (current && current.version >= op.entity.version) return { ...state, cursor };\n return { ...state, cursor, tasks: { ...state.tasks, [op.entity.id]: op.entity } };\n }\n }\n break;\n case \"delete\": {\n if (op.kind === \"roleBinding\") return { ...state, cursor };\n const table = { node: \"nodes\", organization: \"organizations\", agent: \"agents\", link: \"links\" } as const;\n const key = table[op.kind];\n const { [op.id]: _removed, ...rest } = state[key];\n return { ...state, cursor, [key]: rest };\n }\n case \"presence\": {\n const node = state.nodes[op.nodeId];\n if (!node) return { ...state, cursor };\n return {\n ...state,\n cursor,\n nodes: { ...state.nodes, [node.id]: { ...node, status: op.status, lastSeenAt: op.lastSeenAt } },\n };\n }\n case \"none\":\n return { ...state, cursor };\n }\n}\n","import { z } from \"zod\";\n\n/** Cursor pagination query (ROADMAP §2.6). `cursor` is opaque to clients. */\nexport const PageQuery = z.object({\n limit: z.coerce.number().int().min(1).max(200).default(50),\n cursor: z.string().min(1).optional(),\n});\nexport type PageQuery = z.infer<typeof PageQuery>;\n\n/** A page of results; `nextCursor` is null on the last page. */\nexport const Page = <T extends z.ZodType>(item: T, id: string) =>\n z.object({ items: z.array(item), nextCursor: z.string().nullable() }).meta({ id });\n\nexport interface PageOf<T> {\n readonly items: T[];\n readonly nextCursor: string | null;\n}\n","import { z } from \"zod\";\n\n/** RFC 9457 problem details — every API error uses this shape. */\nexport const ProblemDetails = z\n .object({\n type: z.string().meta({ example: \"/problems/forbidden\" }),\n title: z.string(),\n status: z.int().min(400).max(599),\n detail: z.string().optional(),\n instance: z.string().optional(),\n code: z.string().meta({ description: \"Stable machine-readable error code\" }),\n errors: z.array(z.object({ path: z.string(), message: z.string() })).optional(),\n })\n .meta({ id: \"ProblemDetails\" });\nexport type ProblemDetails = z.infer<typeof ProblemDetails>;\n","import { z } from \"zod\";\nimport { MeshEvent } from \"./events.ts\";\nimport { PrincipalId } from \"./ids.ts\";\nimport { MeshCursor } from \"./mesh.ts\";\n\n/**\n * Realtime protocol over `WS /v1/realtime` (ADR-0014). JSON text frames.\n *\n * client → hello { token, cursor?, topics? } first frame, within 5 s\n * server → event { event }* replay of everything after `cursor`\n * server → welcome { principalId, cursor } replay done; live events follow\n * server → event { event }* live\n * server → resync.required { reason } the client must fetch a fresh snapshot and reconnect\n */\n\n/** Subject kinds a client can subscribe to. Default: everything. */\nexport const Topic = z.enum([\"node\", \"organization\", \"agent\", \"link\", \"roleBinding\", \"task\"]);\nexport type Topic = z.infer<typeof Topic>;\n\nexport const ClientMessage = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"hello\"),\n /** Bearer token or API key — sent in the first frame because browsers cannot set WebSocket headers. */\n token: z.string().min(1),\n /** Resume point, usually the cursor of the snapshot the client just loaded. */\n cursor: MeshCursor.optional(),\n topics: z.array(Topic).optional(),\n }),\n z.object({ type: z.literal(\"subscribe\"), topics: z.array(Topic) }),\n]);\nexport type ClientMessage = z.infer<typeof ClientMessage>;\n\nexport const ServerMessage = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"welcome\"), principalId: PrincipalId, cursor: MeshCursor }),\n z.object({ type: z.literal(\"event\"), event: MeshEvent }),\n z.object({ type: z.literal(\"resync.required\"), reason: z.string() }),\n z.object({ type: z.literal(\"error\"), code: z.string(), message: z.string() }),\n]);\nexport type ServerMessage = z.infer<typeof ServerMessage>;\n\n/** WebSocket close codes used by the node server. */\nexport const RealtimeCloseCode = {\n normal: 1000,\n goingAway: 1001,\n badMessage: 4400,\n unauthenticated: 4401,\n helloTimeout: 4408,\n resyncRequired: 4409,\n} as const;\n"]}