@multi-agent-protocol/sdk 0.0.2

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,3052 @@
1
+ /**
2
+ * Multi-Agent Protocol (MAP) Type Definitions - v2
3
+ *
4
+ * Core type definitions matching the MAP JSON Schema.
5
+ * These types are the foundation for the TypeScript SDK.
6
+ *
7
+ * v2 Changes:
8
+ * - Fixed ERROR_CODES collision (FEDERATION_AUTH_FAILED)
9
+ * - Added Agent.ownerId for ownership tracking
10
+ * - Reorganized method constants by capability domain
11
+ * - Added EventInput type and createEvent() helper
12
+ * - Added disconnect policy and lifecycle events
13
+ * - Expanded subscription filters
14
+ * - Standardized response shapes (always return entities)
15
+ * - Added hierarchy expansion to agents/get
16
+ * - Added CAPABILITY_REQUIREMENTS mapping
17
+ * - Clarified message event data (no payloads)
18
+ */
19
+ /** Unique identifier for any participant (agent, client, system, gateway) */
20
+ type ParticipantId = string;
21
+ /** Unique identifier for an agent */
22
+ type AgentId = string;
23
+ /** Unique identifier for a scope */
24
+ type ScopeId = string;
25
+ /** Unique identifier for a session */
26
+ type SessionId = string;
27
+ /** Unique identifier for a message */
28
+ type MessageId = string;
29
+ /** Unique identifier for a subscription */
30
+ type SubscriptionId = string;
31
+ /** Identifier for correlating related messages */
32
+ type CorrelationId = string;
33
+ /** JSON-RPC request ID */
34
+ type RequestId = string | number;
35
+ /** MAP protocol version */
36
+ type ProtocolVersion = 1;
37
+ /** Unix timestamp in milliseconds */
38
+ type Timestamp = number;
39
+ /** Vendor extension metadata */
40
+ type Meta = Record<string, unknown>;
41
+ /** Type of participant in the protocol */
42
+ type ParticipantType = 'agent' | 'client' | 'system' | 'gateway';
43
+ /** Transport binding type */
44
+ type TransportType = 'websocket' | 'stdio' | 'inprocess' | 'http-sse';
45
+ /**
46
+ * Streaming capabilities for backpressure and flow control.
47
+ * Servers advertise these to indicate what features they support.
48
+ */
49
+ interface StreamingCapabilities {
50
+ /** Server can receive and process ack notifications */
51
+ supportsAck?: boolean;
52
+ /** Server will pause sending when client falls behind */
53
+ supportsFlowControl?: boolean;
54
+ /** Server supports pause/resume subscription state */
55
+ supportsPause?: boolean;
56
+ }
57
+ /** Capabilities of a participant, grouped by category */
58
+ interface ParticipantCapabilities {
59
+ observation?: {
60
+ /** Can subscribe to event streams */
61
+ canObserve?: boolean;
62
+ /** Can query agents and structure */
63
+ canQuery?: boolean;
64
+ };
65
+ messaging?: {
66
+ /** Can send messages */
67
+ canSend?: boolean;
68
+ /** Can receive messages addressed to it */
69
+ canReceive?: boolean;
70
+ /** Can send to scopes/roles */
71
+ canBroadcast?: boolean;
72
+ };
73
+ lifecycle?: {
74
+ /** Can create child agents */
75
+ canSpawn?: boolean;
76
+ /** Can register agents (not as children) */
77
+ canRegister?: boolean;
78
+ /** Can remove agents */
79
+ canUnregister?: boolean;
80
+ /** Can inject context/control agents */
81
+ canSteer?: boolean;
82
+ /** Can request agent termination */
83
+ canStop?: boolean;
84
+ };
85
+ scopes?: {
86
+ /** Can create new scopes */
87
+ canCreateScopes?: boolean;
88
+ /** Can modify and delete scopes */
89
+ canManageScopes?: boolean;
90
+ };
91
+ federation?: {
92
+ /** Can connect to and route to federated systems */
93
+ canFederate?: boolean;
94
+ };
95
+ /** Streaming/backpressure capabilities */
96
+ streaming?: StreamingCapabilities;
97
+ _meta?: Meta;
98
+ }
99
+ /** A participant in the MAP protocol */
100
+ interface Participant {
101
+ id: ParticipantId;
102
+ type: ParticipantType;
103
+ name?: string;
104
+ capabilities?: ParticipantCapabilities;
105
+ transport?: TransportType;
106
+ sessionId?: SessionId;
107
+ metadata?: Record<string, unknown>;
108
+ _meta?: Meta;
109
+ }
110
+ /**
111
+ * State of an agent.
112
+ * Standard states are enumerated; custom states use 'x-' prefix.
113
+ */
114
+ type AgentState = 'registered' | 'active' | 'busy' | 'idle' | 'suspended' | 'stopping' | 'stopped' | 'failed' | 'orphaned' | `x-${string}`;
115
+ /** Type of relationship between agents */
116
+ type AgentRelationshipType = 'peer' | 'supervisor' | 'supervised' | 'collaborator';
117
+ /** A relationship between agents */
118
+ interface AgentRelationship {
119
+ type: AgentRelationshipType;
120
+ agentId: AgentId;
121
+ metadata?: Record<string, unknown>;
122
+ _meta?: Meta;
123
+ }
124
+ /** Lifecycle metadata for an agent */
125
+ interface AgentLifecycle {
126
+ createdAt?: Timestamp;
127
+ startedAt?: Timestamp;
128
+ stoppedAt?: Timestamp;
129
+ lastActiveAt?: Timestamp;
130
+ orphanedAt?: Timestamp;
131
+ exitCode?: number;
132
+ exitReason?: string;
133
+ _meta?: Meta;
134
+ }
135
+ /** Who can see this agent */
136
+ type AgentVisibility = 'public' | 'parent-only' | 'scope' | 'system';
137
+ /** An agent in the multi-agent system */
138
+ interface Agent {
139
+ id: AgentId;
140
+ /**
141
+ * The participant that owns/controls this agent's connection.
142
+ * Used for message routing and cleanup on disconnect.
143
+ *
144
+ * - Non-null: Agent is owned by the specified participant
145
+ * - null: Agent is orphaned (owner disconnected with 'orphan' policy)
146
+ */
147
+ ownerId: ParticipantId | null;
148
+ name?: string;
149
+ description?: string;
150
+ /** Parent agent ID (for spawned agents) */
151
+ parent?: AgentId;
152
+ /** Child agent IDs (populated when queried with include.children) */
153
+ children?: AgentId[];
154
+ relationships?: AgentRelationship[];
155
+ state: AgentState;
156
+ role?: string;
157
+ scopes?: ScopeId[];
158
+ /**
159
+ * Simple visibility setting (legacy).
160
+ * @deprecated Use permissionOverrides.canSee.agents for more granular control
161
+ */
162
+ visibility?: AgentVisibility;
163
+ /**
164
+ * Per-agent permission overrides.
165
+ * Merged on top of role-based defaults from system configuration.
166
+ * Only include fields that differ from the role default.
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * // Agent that accepts messages from clients (unlike role default)
171
+ * permissionOverrides: {
172
+ * acceptsFrom: { clients: 'all' }
173
+ * }
174
+ * ```
175
+ */
176
+ permissionOverrides?: Partial<AgentPermissions>;
177
+ lifecycle?: AgentLifecycle;
178
+ capabilities?: ParticipantCapabilities;
179
+ metadata?: Record<string, unknown>;
180
+ _meta?: Meta;
181
+ }
182
+ /**
183
+ * Check if an agent is orphaned (owner disconnected).
184
+ * Orphaned agents have `ownerId === null`.
185
+ */
186
+ declare function isOrphanedAgent(agent: Agent): boolean;
187
+ /**
188
+ * Rule for which agents this agent can see.
189
+ * - 'all': Can see any agent in the system
190
+ * - 'hierarchy': Can see parent, children, ancestors, descendants
191
+ * - 'scoped': Can see agents in the same scopes
192
+ * - 'direct': Can only see explicitly included agents
193
+ * - { include: [...] }: Explicit allowlist of agent IDs
194
+ */
195
+ type AgentVisibilityRule = 'all' | 'hierarchy' | 'scoped' | 'direct' | {
196
+ include: AgentId[];
197
+ };
198
+ /**
199
+ * Rule for which scopes this agent can see.
200
+ * - 'all': Can see any scope
201
+ * - 'member': Can only see scopes they're a member of
202
+ * - { include: [...] }: Explicit allowlist of scope IDs
203
+ */
204
+ type ScopeVisibilityRule = 'all' | 'member' | {
205
+ include: ScopeId[];
206
+ };
207
+ /**
208
+ * Rule for how much agent hierarchy structure this agent can see.
209
+ * - 'full': Can see the full agent hierarchy tree
210
+ * - 'local': Can see immediate parent and children only
211
+ * - 'none': Cannot see hierarchy relationships
212
+ */
213
+ type StructureVisibilityRule = 'full' | 'local' | 'none';
214
+ /**
215
+ * Rule for which agents this agent can send messages to.
216
+ * - 'all': Can message any agent
217
+ * - 'hierarchy': Can message parent, children, ancestors, descendants
218
+ * - 'scoped': Can message agents in the same scopes
219
+ * - { include: [...] }: Explicit allowlist of agent IDs
220
+ */
221
+ type AgentMessagingRule = 'all' | 'hierarchy' | 'scoped' | {
222
+ include: AgentId[];
223
+ };
224
+ /**
225
+ * Rule for which scopes this agent can send messages to.
226
+ * - 'all': Can send to any scope
227
+ * - 'member': Can only send to scopes they're a member of
228
+ * - { include: [...] }: Explicit allowlist of scope IDs
229
+ */
230
+ type ScopeMessagingRule = 'all' | 'member' | {
231
+ include: ScopeId[];
232
+ };
233
+ /**
234
+ * Rule for which agents this agent accepts messages from.
235
+ * - 'all': Accepts from any agent
236
+ * - 'hierarchy': Accepts from parent, children, ancestors, descendants
237
+ * - 'scoped': Accepts from agents in the same scopes
238
+ * - { include: [...] }: Explicit allowlist of agent IDs
239
+ */
240
+ type AgentAcceptanceRule = 'all' | 'hierarchy' | 'scoped' | {
241
+ include: AgentId[];
242
+ };
243
+ /**
244
+ * Rule for which clients this agent accepts messages from.
245
+ * - 'all': Accepts from any client
246
+ * - 'none': Does not accept from any client
247
+ * - { include: [...] }: Explicit allowlist of participant IDs
248
+ */
249
+ type ClientAcceptanceRule = 'all' | 'none' | {
250
+ include: ParticipantId[];
251
+ };
252
+ /**
253
+ * Rule for which federated systems this agent accepts messages from.
254
+ * - 'all': Accepts from any federated system
255
+ * - 'none': Does not accept from any federated system
256
+ * - { include: [...] }: Explicit allowlist of system IDs
257
+ */
258
+ type SystemAcceptanceRule = 'all' | 'none' | {
259
+ include: string[];
260
+ };
261
+ /**
262
+ * Permission configuration for an agent.
263
+ * Defines what the agent can see, who it can message, and who it accepts messages from.
264
+ *
265
+ * Used in two ways:
266
+ * 1. As role-based defaults in system configuration
267
+ * 2. As per-agent overrides via Agent.permissionOverrides
268
+ *
269
+ * @example
270
+ * ```typescript
271
+ * const workerPermissions: AgentPermissions = {
272
+ * canSee: {
273
+ * agents: 'hierarchy',
274
+ * scopes: 'member',
275
+ * structure: 'local',
276
+ * },
277
+ * canMessage: {
278
+ * agents: 'hierarchy',
279
+ * scopes: 'member',
280
+ * },
281
+ * acceptsFrom: {
282
+ * agents: 'hierarchy',
283
+ * clients: 'none',
284
+ * systems: 'none',
285
+ * },
286
+ * };
287
+ * ```
288
+ */
289
+ interface AgentPermissions {
290
+ /** Rules for what this agent can see */
291
+ canSee?: {
292
+ /** Which agents this agent can see */
293
+ agents?: AgentVisibilityRule;
294
+ /** Which scopes this agent can see */
295
+ scopes?: ScopeVisibilityRule;
296
+ /** How much hierarchy structure this agent can see */
297
+ structure?: StructureVisibilityRule;
298
+ };
299
+ /** Rules for who this agent can send messages to */
300
+ canMessage?: {
301
+ /** Which agents this agent can message */
302
+ agents?: AgentMessagingRule;
303
+ /** Which scopes this agent can send to */
304
+ scopes?: ScopeMessagingRule;
305
+ };
306
+ /** Rules for who this agent accepts messages from */
307
+ acceptsFrom?: {
308
+ /** Which agents this agent accepts messages from */
309
+ agents?: AgentAcceptanceRule;
310
+ /** Which clients this agent accepts messages from */
311
+ clients?: ClientAcceptanceRule;
312
+ /** Which federated systems this agent accepts messages from */
313
+ systems?: SystemAcceptanceRule;
314
+ };
315
+ }
316
+ /**
317
+ * System-level configuration for agent permissions.
318
+ * Defines default permissions and role-based permission templates.
319
+ *
320
+ * Resolution order:
321
+ * 1. Start with defaultPermissions
322
+ * 2. If agent has a role, deep merge rolePermissions[role]
323
+ * 3. Deep merge agent.permissionOverrides
324
+ *
325
+ * @example
326
+ * ```typescript
327
+ * const config: AgentPermissionConfig = {
328
+ * defaultPermissions: {
329
+ * canSee: { agents: 'hierarchy', scopes: 'member', structure: 'local' },
330
+ * canMessage: { agents: 'hierarchy', scopes: 'member' },
331
+ * acceptsFrom: { agents: 'hierarchy', clients: 'none', systems: 'none' },
332
+ * },
333
+ * rolePermissions: {
334
+ * coordinator: {
335
+ * canSee: { agents: 'all', scopes: 'all', structure: 'full' },
336
+ * canMessage: { agents: 'all', scopes: 'all' },
337
+ * acceptsFrom: { agents: 'all', clients: 'all', systems: 'none' },
338
+ * },
339
+ * },
340
+ * };
341
+ * ```
342
+ */
343
+ interface AgentPermissionConfig {
344
+ /** Default permissions for agents without a role or role-specific config */
345
+ defaultPermissions: AgentPermissions;
346
+ /** Role-based permission templates */
347
+ rolePermissions: Record<string, AgentPermissions>;
348
+ }
349
+ /** Address a single agent directly */
350
+ interface DirectAddress {
351
+ agent: AgentId;
352
+ }
353
+ /** Address multiple agents */
354
+ interface MultiAddress {
355
+ agents: AgentId[];
356
+ }
357
+ /** Address all agents in a scope */
358
+ interface ScopeAddress {
359
+ scope: ScopeId;
360
+ }
361
+ /** Address agents by role, optionally within a scope */
362
+ interface RoleAddress {
363
+ role: string;
364
+ within?: ScopeId;
365
+ }
366
+ /** Address relative to sender in hierarchy */
367
+ interface HierarchicalAddress {
368
+ parent?: true;
369
+ children?: true;
370
+ ancestors?: true;
371
+ descendants?: true;
372
+ siblings?: true;
373
+ depth?: number;
374
+ }
375
+ /** Address all agents in the system */
376
+ interface BroadcastAddress {
377
+ broadcast: true;
378
+ }
379
+ /** Address the system/router itself */
380
+ interface SystemAddress {
381
+ system: true;
382
+ }
383
+ /** Address any participant by ID or category */
384
+ interface ParticipantAddress {
385
+ participant?: ParticipantId;
386
+ participants?: 'all' | 'agents' | 'clients';
387
+ }
388
+ /** Address an agent in a federated system */
389
+ interface FederatedAddress {
390
+ system: string;
391
+ agent: AgentId;
392
+ }
393
+ /** Flexible addressing for any topology */
394
+ type Address = string | DirectAddress | MultiAddress | ScopeAddress | RoleAddress | HierarchicalAddress | BroadcastAddress | SystemAddress | ParticipantAddress | FederatedAddress;
395
+ /** Message priority */
396
+ type MessagePriority = 'urgent' | 'high' | 'normal' | 'low';
397
+ /** Message delivery guarantees */
398
+ type DeliverySemantics = 'fire-and-forget' | 'acknowledged' | 'guaranteed';
399
+ /** Relationship context for the message */
400
+ type MessageRelationship = 'parent-to-child' | 'child-to-parent' | 'peer' | 'broadcast';
401
+ /** Metadata for a message */
402
+ interface MessageMeta {
403
+ timestamp?: Timestamp;
404
+ relationship?: MessageRelationship;
405
+ expectsResponse?: boolean;
406
+ correlationId?: CorrelationId;
407
+ isResult?: boolean;
408
+ priority?: MessagePriority;
409
+ delivery?: DeliverySemantics;
410
+ ttlMs?: number;
411
+ _meta?: Meta;
412
+ }
413
+ /** A message in the multi-agent system */
414
+ interface Message<T = unknown> {
415
+ id: MessageId;
416
+ from: ParticipantId;
417
+ to: Address;
418
+ timestamp: Timestamp;
419
+ payload?: T;
420
+ meta?: MessageMeta;
421
+ _meta?: Meta;
422
+ }
423
+ /** Policy for joining a scope */
424
+ type JoinPolicy = 'open' | 'invite' | 'role' | 'system';
425
+ /** Who can see the scope exists and its members */
426
+ type ScopeVisibility = 'public' | 'members' | 'system';
427
+ /** Who can see messages sent to this scope */
428
+ type MessageVisibility = 'public' | 'members' | 'system';
429
+ /** Who can send messages to this scope */
430
+ type SendPolicy = 'members' | 'any';
431
+ /** A scope for grouping agents */
432
+ interface Scope {
433
+ id: ScopeId;
434
+ name?: string;
435
+ description?: string;
436
+ parent?: ScopeId;
437
+ joinPolicy?: JoinPolicy;
438
+ autoJoinRoles?: string[];
439
+ visibility?: ScopeVisibility;
440
+ messageVisibility?: MessageVisibility;
441
+ sendPolicy?: SendPolicy;
442
+ persistent?: boolean;
443
+ autoDelete?: boolean;
444
+ metadata?: Record<string, unknown>;
445
+ _meta?: Meta;
446
+ }
447
+ /**
448
+ * Event type constants.
449
+ * Use these instead of string literals for type safety and autocomplete.
450
+ */
451
+ declare const EVENT_TYPES: {
452
+ readonly AGENT_REGISTERED: "agent_registered";
453
+ readonly AGENT_UNREGISTERED: "agent_unregistered";
454
+ readonly AGENT_STATE_CHANGED: "agent_state_changed";
455
+ readonly AGENT_ORPHANED: "agent_orphaned";
456
+ readonly PARTICIPANT_CONNECTED: "participant_connected";
457
+ readonly PARTICIPANT_DISCONNECTED: "participant_disconnected";
458
+ readonly MESSAGE_SENT: "message_sent";
459
+ readonly MESSAGE_DELIVERED: "message_delivered";
460
+ readonly MESSAGE_FAILED: "message_failed";
461
+ readonly SCOPE_CREATED: "scope_created";
462
+ readonly SCOPE_DELETED: "scope_deleted";
463
+ readonly SCOPE_MEMBER_JOINED: "scope_member_joined";
464
+ readonly SCOPE_MEMBER_LEFT: "scope_member_left";
465
+ readonly PERMISSIONS_CLIENT_UPDATED: "permissions_client_updated";
466
+ readonly PERMISSIONS_AGENT_UPDATED: "permissions_agent_updated";
467
+ readonly SYSTEM_ERROR: "system_error";
468
+ readonly FEDERATION_CONNECTED: "federation_connected";
469
+ readonly FEDERATION_DISCONNECTED: "federation_disconnected";
470
+ };
471
+ /** Type of system event (derived from EVENT_TYPES) */
472
+ type EventType = (typeof EVENT_TYPES)[keyof typeof EVENT_TYPES];
473
+ /**
474
+ * Input for creating events.
475
+ * id and timestamp are optional - server generates them.
476
+ */
477
+ interface EventInput {
478
+ type: EventType;
479
+ timestamp?: Timestamp;
480
+ source?: ParticipantId;
481
+ data?: Record<string, unknown>;
482
+ causedBy?: string[];
483
+ _meta?: Meta;
484
+ }
485
+ /**
486
+ * Wire event as sent to clients.
487
+ * id and timestamp are always present.
488
+ */
489
+ interface Event {
490
+ id: string;
491
+ type: EventType;
492
+ timestamp: Timestamp;
493
+ source?: ParticipantId;
494
+ data?: Record<string, unknown>;
495
+ causedBy?: string[];
496
+ _meta?: Meta;
497
+ }
498
+ /** Helper to create events with auto-generated id and timestamp */
499
+ declare function createEvent(input: EventInput): Event;
500
+ /**
501
+ * Filter for event subscriptions.
502
+ *
503
+ * ## Combination Logic
504
+ *
505
+ * All specified fields are combined with **AND** logic:
506
+ * - An event must match ALL specified criteria to be delivered
507
+ * - Within array fields, values are combined with **OR** logic
508
+ * - Empty arrays (`[]`) are treated as "no filter" (matches any)
509
+ * - Undefined/omitted fields are treated as "no filter" (matches any)
510
+ *
511
+ * ## Examples
512
+ *
513
+ * ```typescript
514
+ * // Match agent_registered OR agent_unregistered events from agent-1 OR agent-2
515
+ * {
516
+ * eventTypes: ['agent_registered', 'agent_unregistered'],
517
+ * fromAgents: ['agent-1', 'agent-2']
518
+ * }
519
+ *
520
+ * // Match any event from agents with role 'worker' OR 'supervisor'
521
+ * { fromRoles: ['worker', 'supervisor'] }
522
+ *
523
+ * // Match scope events in scope-1 with metadata containing priority='high'
524
+ * {
525
+ * scopes: ['scope-1'],
526
+ * metadataMatch: { priority: 'high' }
527
+ * }
528
+ * ```
529
+ *
530
+ * ## Field Semantics
531
+ *
532
+ * | Field | Within-field | Cross-field | Description |
533
+ * |-------|--------------|-------------|-------------|
534
+ * | `eventTypes` | OR | AND | Event type is one of the listed types |
535
+ * | `agents` | OR | AND | Event relates to one of the listed agents (legacy) |
536
+ * | `fromAgents` | OR | AND | Event source is one of the listed agents |
537
+ * | `fromRoles` | OR | AND | Event source agent has one of the listed roles |
538
+ * | `roles` | OR | AND | Event relates to agents with one of the listed roles |
539
+ * | `scopes` | OR | AND | Event relates to one of the listed scopes |
540
+ * | `priorities` | OR | AND | Message priority is one of the listed levels |
541
+ * | `correlationIds` | OR | AND | Event has one of the listed correlation IDs |
542
+ * | `metadataMatch` | AND | AND | Event metadata contains ALL specified key-value pairs |
543
+ */
544
+ interface SubscriptionFilter {
545
+ /**
546
+ * Filter by agents the event relates to.
547
+ * @deprecated Use `fromAgents` for clearer semantics
548
+ */
549
+ agents?: AgentId[];
550
+ /**
551
+ * Filter by roles the event relates to.
552
+ * Matches events where the related agent has one of these roles.
553
+ */
554
+ roles?: string[];
555
+ /**
556
+ * Filter by scopes the event relates to.
557
+ * Matches events with scopeId in event.data matching one of these.
558
+ */
559
+ scopes?: ScopeId[];
560
+ /**
561
+ * Filter by event type.
562
+ * Use EVENT_TYPES constants: `eventTypes: [EVENT_TYPES.AGENT_REGISTERED]`
563
+ */
564
+ eventTypes?: EventType[];
565
+ /**
566
+ * Filter by message priority (for message events).
567
+ */
568
+ priorities?: MessagePriority[];
569
+ /**
570
+ * Filter by correlation ID.
571
+ * Matches events with correlationId in event.data matching one of these.
572
+ */
573
+ correlationIds?: CorrelationId[];
574
+ /**
575
+ * Filter by source agent ID.
576
+ * Matches events where event.source is one of these agent IDs.
577
+ */
578
+ fromAgents?: AgentId[];
579
+ /**
580
+ * Filter by source agent role.
581
+ * Matches events where the source agent has one of these roles.
582
+ */
583
+ fromRoles?: string[];
584
+ /**
585
+ * Filter by metadata key-value pairs.
586
+ * All specified pairs must match (AND logic within this field).
587
+ * Checks event.data.metadata for matching values.
588
+ */
589
+ metadataMatch?: Record<string, unknown>;
590
+ _meta?: Meta;
591
+ }
592
+ /** Options for subscriptions */
593
+ interface SubscriptionOptions$1 {
594
+ /** Include full payloads in message events (default: false) */
595
+ includeMessagePayloads?: boolean;
596
+ /** Exclude events from own actions (default: false) */
597
+ excludeOwnEvents?: boolean;
598
+ }
599
+ /**
600
+ * State of a subscription's event delivery.
601
+ * - 'active': Events are being delivered normally
602
+ * - 'paused': Events are buffered but not delivered to the iterator
603
+ * - 'closed': Subscription is terminated
604
+ */
605
+ type SubscriptionState = 'active' | 'paused' | 'closed';
606
+ /**
607
+ * Information about events dropped due to buffer overflow.
608
+ * Passed to overflow handlers when events cannot be buffered.
609
+ */
610
+ interface OverflowInfo {
611
+ /** Number of events dropped in this overflow batch */
612
+ eventsDropped: number;
613
+ /** Event ID of oldest dropped event (if available) */
614
+ oldestDroppedId?: string;
615
+ /** Event ID of newest dropped event (if available) */
616
+ newestDroppedId?: string;
617
+ /** Timestamp when overflow occurred */
618
+ timestamp: Timestamp;
619
+ /** Total events dropped since subscription started */
620
+ totalDropped: number;
621
+ }
622
+ /** Handler called when subscription buffer overflows */
623
+ type OverflowHandler = (info: OverflowInfo) => void;
624
+ /**
625
+ * Parameters for acknowledging received events.
626
+ * Sent as a notification to inform the server of client progress.
627
+ * Enables optional server-side flow control.
628
+ */
629
+ interface SubscriptionAckParams {
630
+ /** Subscription being acknowledged */
631
+ subscriptionId: SubscriptionId;
632
+ /** Acknowledge all events up to and including this sequence number */
633
+ upToSequence: number;
634
+ _meta?: Meta;
635
+ }
636
+ /** Notification for subscription acknowledgment */
637
+ interface SubscriptionAckNotification extends MAPNotificationBase<SubscriptionAckParams> {
638
+ method: 'map/subscribe.ack';
639
+ params: SubscriptionAckParams;
640
+ }
641
+ /** Data for message_sent events (no payload for privacy) */
642
+ interface MessageSentEventData {
643
+ messageId: MessageId;
644
+ from: ParticipantId;
645
+ to: Address;
646
+ timestamp: Timestamp;
647
+ correlationId?: CorrelationId;
648
+ priority?: MessagePriority;
649
+ }
650
+ /** Data for message_delivered events (no payload for privacy) */
651
+ interface MessageDeliveredEventData {
652
+ messageId: MessageId;
653
+ from: ParticipantId;
654
+ deliveredTo: ParticipantId[];
655
+ timestamp: Timestamp;
656
+ correlationId?: CorrelationId;
657
+ }
658
+ /** Data for message_failed events */
659
+ interface MessageFailedEventData {
660
+ messageId: MessageId;
661
+ from: ParticipantId;
662
+ to: Address;
663
+ reason: string;
664
+ code?: number;
665
+ }
666
+ /** Category of error for handling decisions */
667
+ type ErrorCategory = 'protocol' | 'auth' | 'routing' | 'agent' | 'resource' | 'federation' | 'internal';
668
+ /** Structured error data */
669
+ interface MAPErrorData {
670
+ category?: ErrorCategory;
671
+ retryable?: boolean;
672
+ retryAfterMs?: number;
673
+ details?: Record<string, unknown>;
674
+ _meta?: Meta;
675
+ }
676
+ /** JSON-RPC 2.0 error object */
677
+ interface MAPError {
678
+ code: number;
679
+ message: string;
680
+ data?: MAPErrorData;
681
+ }
682
+ /** JSON-RPC version constant */
683
+ declare const JSONRPC_VERSION: "2.0";
684
+ /** Base JSON-RPC request */
685
+ interface MAPRequestBase<TParams = unknown> {
686
+ jsonrpc: '2.0';
687
+ id: RequestId;
688
+ method: string;
689
+ params?: TParams;
690
+ }
691
+ /** Base JSON-RPC response (success) */
692
+ interface MAPResponseSuccess<T = unknown> {
693
+ jsonrpc: '2.0';
694
+ id: RequestId;
695
+ result: T;
696
+ }
697
+ /** Base JSON-RPC response (error) */
698
+ interface MAPResponseError {
699
+ jsonrpc: '2.0';
700
+ id: RequestId;
701
+ error: MAPError;
702
+ }
703
+ /** JSON-RPC response (success or error) */
704
+ type MAPResponse<T = unknown> = MAPResponseSuccess<T> | MAPResponseError;
705
+ /** Base JSON-RPC notification */
706
+ interface MAPNotificationBase<TParams = unknown> {
707
+ jsonrpc: '2.0';
708
+ method: string;
709
+ params?: TParams;
710
+ }
711
+ interface SessionInfo {
712
+ id: SessionId;
713
+ createdAt: Timestamp;
714
+ lastActiveAt?: Timestamp;
715
+ closedAt?: Timestamp;
716
+ }
717
+ type AuthMethod = 'bearer' | 'api-key' | 'mtls' | 'none';
718
+ interface AuthParams {
719
+ method: AuthMethod;
720
+ token?: string;
721
+ }
722
+ interface FederationAuth {
723
+ method: 'bearer' | 'api-key' | 'mtls';
724
+ credentials?: string;
725
+ }
726
+ /** Policy for handling unexpected disconnection */
727
+ interface DisconnectPolicy {
728
+ /** What happens to agents on disconnect */
729
+ agentBehavior: 'unregister' | 'orphan' | 'grace-period';
730
+ /** Grace period before unregistering (ms) */
731
+ gracePeriodMs?: number;
732
+ /** Emit events to subscribers */
733
+ notifySubscribers?: boolean;
734
+ }
735
+ interface ConnectRequestParams {
736
+ protocolVersion: ProtocolVersion;
737
+ participantType: ParticipantType;
738
+ participantId?: ParticipantId;
739
+ name?: string;
740
+ capabilities?: ParticipantCapabilities;
741
+ sessionId?: SessionId;
742
+ /** Reclaim orphaned agents from previous connection */
743
+ reclaimAgents?: AgentId[];
744
+ /** Policy for unexpected disconnect */
745
+ disconnectPolicy?: DisconnectPolicy;
746
+ auth?: AuthParams;
747
+ _meta?: Meta;
748
+ }
749
+ interface ConnectRequest extends MAPRequestBase<ConnectRequestParams> {
750
+ method: 'map/connect';
751
+ params: ConnectRequestParams;
752
+ }
753
+ interface ConnectResponseResult {
754
+ protocolVersion: ProtocolVersion;
755
+ sessionId: SessionId;
756
+ participantId: ParticipantId;
757
+ capabilities: ParticipantCapabilities;
758
+ systemInfo?: {
759
+ name?: string;
760
+ version?: string;
761
+ };
762
+ /** Is this a reconnection? */
763
+ reconnected?: boolean;
764
+ /** Reclaimed agents */
765
+ reclaimedAgents?: Agent[];
766
+ /** Currently owned agents */
767
+ ownedAgents?: AgentId[];
768
+ _meta?: Meta;
769
+ }
770
+ interface DisconnectRequestParams {
771
+ reason?: string;
772
+ _meta?: Meta;
773
+ }
774
+ interface DisconnectRequest extends MAPRequestBase<DisconnectRequestParams> {
775
+ method: 'map/disconnect';
776
+ params?: DisconnectRequestParams;
777
+ }
778
+ interface DisconnectResponseResult {
779
+ session: SessionInfo;
780
+ _meta?: Meta;
781
+ }
782
+ interface SessionListRequestParams {
783
+ _meta?: Meta;
784
+ }
785
+ interface SessionListRequest extends MAPRequestBase<SessionListRequestParams> {
786
+ method: 'map/session/list';
787
+ params?: SessionListRequestParams;
788
+ }
789
+ interface SessionListResponseResult {
790
+ sessions: SessionInfo[];
791
+ _meta?: Meta;
792
+ }
793
+ interface SessionLoadRequestParams {
794
+ sessionId: SessionId;
795
+ _meta?: Meta;
796
+ }
797
+ interface SessionLoadRequest extends MAPRequestBase<SessionLoadRequestParams> {
798
+ method: 'map/session/load';
799
+ params: SessionLoadRequestParams;
800
+ }
801
+ interface SessionLoadResponseResult {
802
+ sessionId: SessionId;
803
+ restored: boolean;
804
+ _meta?: Meta;
805
+ }
806
+ interface SessionCloseRequestParams {
807
+ sessionId?: SessionId;
808
+ _meta?: Meta;
809
+ }
810
+ interface SessionCloseRequest extends MAPRequestBase<SessionCloseRequestParams> {
811
+ method: 'map/session/close';
812
+ params?: SessionCloseRequestParams;
813
+ }
814
+ interface SessionCloseResponseResult {
815
+ session: SessionInfo;
816
+ _meta?: Meta;
817
+ }
818
+ interface AgentsListFilter {
819
+ states?: AgentState[];
820
+ roles?: string[];
821
+ scopes?: ScopeId[];
822
+ parent?: AgentId;
823
+ hasChildren?: boolean;
824
+ ownerId?: ParticipantId;
825
+ }
826
+ interface AgentsListRequestParams {
827
+ filter?: AgentsListFilter;
828
+ limit?: number;
829
+ cursor?: string;
830
+ _meta?: Meta;
831
+ }
832
+ interface AgentsListRequest extends MAPRequestBase<AgentsListRequestParams> {
833
+ method: 'map/agents/list';
834
+ params?: AgentsListRequestParams;
835
+ }
836
+ interface AgentsListResponseResult {
837
+ agents: Agent[];
838
+ nextCursor?: string;
839
+ _meta?: Meta;
840
+ }
841
+ /** Options for expanding related agents */
842
+ interface AgentIncludeOptions {
843
+ parent?: boolean;
844
+ children?: boolean;
845
+ siblings?: boolean;
846
+ ancestors?: boolean;
847
+ descendants?: boolean;
848
+ maxDepth?: number;
849
+ }
850
+ interface AgentsGetRequestParams {
851
+ agentId: AgentId;
852
+ include?: AgentIncludeOptions;
853
+ _meta?: Meta;
854
+ }
855
+ interface AgentsGetRequest extends MAPRequestBase<AgentsGetRequestParams> {
856
+ method: 'map/agents/get';
857
+ params: AgentsGetRequestParams;
858
+ }
859
+ interface AgentsGetResponseResult {
860
+ agent: Agent;
861
+ parent?: Agent;
862
+ children?: Agent[];
863
+ siblings?: Agent[];
864
+ ancestors?: Agent[];
865
+ descendants?: Agent[];
866
+ _meta?: Meta;
867
+ }
868
+ interface AgentsRegisterRequestParams {
869
+ agentId?: AgentId;
870
+ name?: string;
871
+ description?: string;
872
+ role?: string;
873
+ parent?: AgentId;
874
+ scopes?: ScopeId[];
875
+ visibility?: AgentVisibility;
876
+ capabilities?: ParticipantCapabilities;
877
+ metadata?: Record<string, unknown>;
878
+ /** Permission overrides merged on top of role-based defaults */
879
+ permissionOverrides?: Partial<AgentPermissions>;
880
+ _meta?: Meta;
881
+ }
882
+ interface AgentsRegisterRequest extends MAPRequestBase<AgentsRegisterRequestParams> {
883
+ method: 'map/agents/register';
884
+ params?: AgentsRegisterRequestParams;
885
+ }
886
+ interface AgentsRegisterResponseResult {
887
+ agent: Agent;
888
+ _meta?: Meta;
889
+ }
890
+ interface AgentsUnregisterRequestParams {
891
+ agentId: AgentId;
892
+ reason?: string;
893
+ _meta?: Meta;
894
+ }
895
+ interface AgentsUnregisterRequest extends MAPRequestBase<AgentsUnregisterRequestParams> {
896
+ method: 'map/agents/unregister';
897
+ params: AgentsUnregisterRequestParams;
898
+ }
899
+ interface AgentsUnregisterResponseResult {
900
+ agent: Agent;
901
+ _meta?: Meta;
902
+ }
903
+ interface AgentsUpdateRequestParams {
904
+ agentId: AgentId;
905
+ state?: AgentState;
906
+ metadata?: Record<string, unknown>;
907
+ /**
908
+ * Permission overrides to apply to the agent.
909
+ * Merged on top of role-based defaults.
910
+ */
911
+ permissionOverrides?: Partial<AgentPermissions>;
912
+ _meta?: Meta;
913
+ }
914
+ interface AgentsUpdateRequest extends MAPRequestBase<AgentsUpdateRequestParams> {
915
+ method: 'map/agents/update';
916
+ params: AgentsUpdateRequestParams;
917
+ }
918
+ interface AgentsUpdateResponseResult {
919
+ agent: Agent;
920
+ _meta?: Meta;
921
+ }
922
+ interface AgentsSpawnRequestParams {
923
+ agentId?: AgentId;
924
+ name?: string;
925
+ description?: string;
926
+ role?: string;
927
+ parent?: AgentId;
928
+ scopes?: ScopeId[];
929
+ visibility?: AgentVisibility;
930
+ capabilities?: ParticipantCapabilities;
931
+ initialMessage?: Message;
932
+ metadata?: Record<string, unknown>;
933
+ _meta?: Meta;
934
+ }
935
+ interface AgentsSpawnRequest extends MAPRequestBase<AgentsSpawnRequestParams> {
936
+ method: 'map/agents/spawn';
937
+ params?: AgentsSpawnRequestParams;
938
+ }
939
+ interface AgentsSpawnResponseResult {
940
+ agent: Agent;
941
+ messageId?: MessageId;
942
+ _meta?: Meta;
943
+ }
944
+ interface AgentsStopRequestParams {
945
+ agentId: AgentId;
946
+ reason?: string;
947
+ force?: boolean;
948
+ _meta?: Meta;
949
+ }
950
+ interface AgentsStopRequest extends MAPRequestBase<AgentsStopRequestParams> {
951
+ method: 'map/agents/stop';
952
+ params: AgentsStopRequestParams;
953
+ }
954
+ interface AgentsStopResponseResult {
955
+ agent: Agent;
956
+ _meta?: Meta;
957
+ }
958
+ interface AgentsSuspendRequestParams {
959
+ agentId: AgentId;
960
+ reason?: string;
961
+ _meta?: Meta;
962
+ }
963
+ interface AgentsSuspendRequest extends MAPRequestBase<AgentsSuspendRequestParams> {
964
+ method: 'map/agents/suspend';
965
+ params: AgentsSuspendRequestParams;
966
+ }
967
+ interface AgentsSuspendResponseResult {
968
+ agent: Agent;
969
+ _meta?: Meta;
970
+ }
971
+ interface AgentsResumeRequestParams {
972
+ agentId: AgentId;
973
+ _meta?: Meta;
974
+ }
975
+ interface AgentsResumeRequest extends MAPRequestBase<AgentsResumeRequestParams> {
976
+ method: 'map/agents/resume';
977
+ params: AgentsResumeRequestParams;
978
+ }
979
+ interface AgentsResumeResponseResult {
980
+ agent: Agent;
981
+ _meta?: Meta;
982
+ }
983
+ interface SendRequestParams {
984
+ to: Address;
985
+ payload?: unknown;
986
+ meta?: MessageMeta;
987
+ _meta?: Meta;
988
+ }
989
+ interface SendRequest extends MAPRequestBase<SendRequestParams> {
990
+ method: 'map/send';
991
+ params: SendRequestParams;
992
+ }
993
+ interface SendResponseResult {
994
+ messageId: MessageId;
995
+ delivered?: ParticipantId[];
996
+ _meta?: Meta;
997
+ }
998
+ interface SubscribeRequestParams {
999
+ filter?: SubscriptionFilter;
1000
+ options?: SubscriptionOptions$1;
1001
+ replayFrom?: Timestamp | string;
1002
+ _meta?: Meta;
1003
+ }
1004
+ interface SubscribeRequest extends MAPRequestBase<SubscribeRequestParams> {
1005
+ method: 'map/subscribe';
1006
+ params?: SubscribeRequestParams;
1007
+ }
1008
+ interface SubscribeResponseResult {
1009
+ subscriptionId: SubscriptionId;
1010
+ _meta?: Meta;
1011
+ }
1012
+ interface UnsubscribeRequestParams {
1013
+ subscriptionId: SubscriptionId;
1014
+ _meta?: Meta;
1015
+ }
1016
+ interface UnsubscribeRequest extends MAPRequestBase<UnsubscribeRequestParams> {
1017
+ method: 'map/unsubscribe';
1018
+ params: UnsubscribeRequestParams;
1019
+ }
1020
+ interface UnsubscribeResponseResult {
1021
+ subscription: {
1022
+ id: SubscriptionId;
1023
+ closedAt: Timestamp;
1024
+ };
1025
+ _meta?: Meta;
1026
+ }
1027
+ /**
1028
+ * A replayed event with its envelope metadata.
1029
+ */
1030
+ interface ReplayedEvent {
1031
+ /** Globally unique event ID (ULID format) */
1032
+ eventId: string;
1033
+ /** Server timestamp when event was originally processed */
1034
+ timestamp: Timestamp;
1035
+ /** Event IDs that causally precede this event */
1036
+ causedBy?: string[];
1037
+ /** The event payload */
1038
+ event: Event;
1039
+ }
1040
+ /**
1041
+ * Parameters for replaying historical events.
1042
+ *
1043
+ * Uses keyset pagination with `afterEventId` - pass the last eventId
1044
+ * from the previous response to get the next page of results.
1045
+ *
1046
+ * @example
1047
+ * ```typescript
1048
+ * // Replay from a specific point
1049
+ * const page1 = await client.replay({ limit: 100 });
1050
+ * const page2 = await client.replay({
1051
+ * afterEventId: page1.events.at(-1)?.eventId,
1052
+ * limit: 100
1053
+ * });
1054
+ * ```
1055
+ */
1056
+ interface ReplayRequestParams {
1057
+ /**
1058
+ * Start after this eventId (exclusive).
1059
+ * Used for keyset pagination - pass the last eventId from previous response.
1060
+ */
1061
+ afterEventId?: string;
1062
+ /**
1063
+ * Alternative: start from this timestamp (inclusive).
1064
+ * If both afterEventId and fromTimestamp are provided, afterEventId takes precedence.
1065
+ */
1066
+ fromTimestamp?: Timestamp;
1067
+ /**
1068
+ * End at this timestamp (inclusive).
1069
+ * If not provided, replays up to the most recent event.
1070
+ */
1071
+ toTimestamp?: Timestamp;
1072
+ /**
1073
+ * Filter events (same as subscription filter).
1074
+ */
1075
+ filter?: SubscriptionFilter;
1076
+ /**
1077
+ * Maximum number of events to return.
1078
+ * Default: 100, Maximum: 1000
1079
+ */
1080
+ limit?: number;
1081
+ _meta?: Meta;
1082
+ }
1083
+ interface ReplayRequest extends MAPRequestBase<ReplayRequestParams> {
1084
+ method: 'map/replay';
1085
+ params?: ReplayRequestParams;
1086
+ }
1087
+ interface ReplayResponseResult {
1088
+ /** Replayed events in chronological order */
1089
+ events: ReplayedEvent[];
1090
+ /** Whether more events exist after the last returned event */
1091
+ hasMore: boolean;
1092
+ /**
1093
+ * Total count of matching events (if known).
1094
+ * May be omitted for performance reasons on large result sets.
1095
+ */
1096
+ totalCount?: number;
1097
+ _meta?: Meta;
1098
+ }
1099
+ interface AuthRefreshRequestParams {
1100
+ refreshToken: string;
1101
+ _meta?: Meta;
1102
+ }
1103
+ interface AuthRefreshRequest extends MAPRequestBase<AuthRefreshRequestParams> {
1104
+ method: 'map/auth/refresh';
1105
+ params: AuthRefreshRequestParams;
1106
+ }
1107
+ interface AuthRefreshResponseResult {
1108
+ accessToken: string;
1109
+ expiresAt: Timestamp;
1110
+ refreshToken?: string;
1111
+ _meta?: Meta;
1112
+ }
1113
+ interface ScopesListRequestParams {
1114
+ parent?: ScopeId;
1115
+ _meta?: Meta;
1116
+ }
1117
+ interface ScopesListRequest extends MAPRequestBase<ScopesListRequestParams> {
1118
+ method: 'map/scopes/list';
1119
+ params?: ScopesListRequestParams;
1120
+ }
1121
+ interface ScopesListResponseResult {
1122
+ scopes: Scope[];
1123
+ _meta?: Meta;
1124
+ }
1125
+ interface ScopesGetRequestParams {
1126
+ scopeId: ScopeId;
1127
+ _meta?: Meta;
1128
+ }
1129
+ interface ScopesGetRequest extends MAPRequestBase<ScopesGetRequestParams> {
1130
+ method: 'map/scopes/get';
1131
+ params: ScopesGetRequestParams;
1132
+ }
1133
+ interface ScopesGetResponseResult {
1134
+ scope: Scope;
1135
+ _meta?: Meta;
1136
+ }
1137
+ interface ScopesCreateRequestParams {
1138
+ scopeId?: ScopeId;
1139
+ name?: string;
1140
+ description?: string;
1141
+ parent?: ScopeId;
1142
+ joinPolicy?: JoinPolicy;
1143
+ autoJoinRoles?: string[];
1144
+ visibility?: ScopeVisibility;
1145
+ messageVisibility?: MessageVisibility;
1146
+ sendPolicy?: SendPolicy;
1147
+ persistent?: boolean;
1148
+ autoDelete?: boolean;
1149
+ metadata?: Record<string, unknown>;
1150
+ _meta?: Meta;
1151
+ }
1152
+ interface ScopesCreateRequest extends MAPRequestBase<ScopesCreateRequestParams> {
1153
+ method: 'map/scopes/create';
1154
+ params?: ScopesCreateRequestParams;
1155
+ }
1156
+ interface ScopesCreateResponseResult {
1157
+ scope: Scope;
1158
+ _meta?: Meta;
1159
+ }
1160
+ interface ScopesDeleteRequestParams {
1161
+ scopeId: ScopeId;
1162
+ _meta?: Meta;
1163
+ }
1164
+ interface ScopesDeleteRequest extends MAPRequestBase<ScopesDeleteRequestParams> {
1165
+ method: 'map/scopes/delete';
1166
+ params: ScopesDeleteRequestParams;
1167
+ }
1168
+ interface ScopesDeleteResponseResult {
1169
+ scope: Scope;
1170
+ _meta?: Meta;
1171
+ }
1172
+ interface ScopesJoinRequestParams {
1173
+ scopeId: ScopeId;
1174
+ agentId: AgentId;
1175
+ _meta?: Meta;
1176
+ }
1177
+ interface ScopesJoinRequest extends MAPRequestBase<ScopesJoinRequestParams> {
1178
+ method: 'map/scopes/join';
1179
+ params: ScopesJoinRequestParams;
1180
+ }
1181
+ interface ScopesJoinResponseResult {
1182
+ scope: Scope;
1183
+ agent: Agent;
1184
+ _meta?: Meta;
1185
+ }
1186
+ interface ScopesLeaveRequestParams {
1187
+ scopeId: ScopeId;
1188
+ agentId: AgentId;
1189
+ _meta?: Meta;
1190
+ }
1191
+ interface ScopesLeaveRequest extends MAPRequestBase<ScopesLeaveRequestParams> {
1192
+ method: 'map/scopes/leave';
1193
+ params: ScopesLeaveRequestParams;
1194
+ }
1195
+ interface ScopesLeaveResponseResult {
1196
+ scope: Scope;
1197
+ agent: Agent;
1198
+ _meta?: Meta;
1199
+ }
1200
+ interface ScopesMembersRequestParams {
1201
+ scopeId: ScopeId;
1202
+ limit?: number;
1203
+ cursor?: string;
1204
+ _meta?: Meta;
1205
+ }
1206
+ interface ScopesMembersRequest extends MAPRequestBase<ScopesMembersRequestParams> {
1207
+ method: 'map/scopes/members';
1208
+ params: ScopesMembersRequestParams;
1209
+ }
1210
+ interface ScopesMembersResponseResult {
1211
+ members: AgentId[];
1212
+ nextCursor?: string;
1213
+ _meta?: Meta;
1214
+ }
1215
+ interface StructureGraphRequestParams {
1216
+ rootAgentId?: AgentId;
1217
+ depth?: number;
1218
+ includeRelationships?: boolean;
1219
+ _meta?: Meta;
1220
+ }
1221
+ interface StructureGraphRequest extends MAPRequestBase<StructureGraphRequestParams> {
1222
+ method: 'map/structure/graph';
1223
+ params?: StructureGraphRequestParams;
1224
+ }
1225
+ interface GraphEdge {
1226
+ from: AgentId;
1227
+ to: AgentId;
1228
+ type: 'parent-child' | 'peer' | 'supervisor' | 'collaborator';
1229
+ }
1230
+ interface StructureGraphResponseResult {
1231
+ nodes: Agent[];
1232
+ edges: GraphEdge[];
1233
+ _meta?: Meta;
1234
+ }
1235
+ type InjectDelivery = 'interrupt' | 'queue' | 'best-effort';
1236
+ type InjectDeliveryResult = 'interrupt' | 'queue' | 'message';
1237
+ interface InjectRequestParams {
1238
+ agentId: AgentId;
1239
+ content: unknown;
1240
+ delivery?: InjectDelivery;
1241
+ _meta?: Meta;
1242
+ }
1243
+ interface InjectRequest extends MAPRequestBase<InjectRequestParams> {
1244
+ method: 'map/inject';
1245
+ params: InjectRequestParams;
1246
+ }
1247
+ interface InjectResponseResult {
1248
+ injected: boolean;
1249
+ delivery?: InjectDeliveryResult;
1250
+ _meta?: Meta;
1251
+ }
1252
+ /**
1253
+ * Parameters for updating client permissions.
1254
+ * Only system/admin participants can update client permissions.
1255
+ */
1256
+ interface PermissionsUpdateRequestParams {
1257
+ /** Client to update permissions for */
1258
+ clientId: ParticipantId;
1259
+ /** Partial permissions to merge with existing */
1260
+ permissions: Partial<ParticipantCapabilities>;
1261
+ _meta?: Meta;
1262
+ }
1263
+ interface PermissionsUpdateRequest extends MAPRequestBase<PermissionsUpdateRequestParams> {
1264
+ method: 'map/permissions/update';
1265
+ params: PermissionsUpdateRequestParams;
1266
+ }
1267
+ interface PermissionsUpdateResponseResult {
1268
+ /** Whether update was applied */
1269
+ success: boolean;
1270
+ /** Effective permissions after update */
1271
+ effectivePermissions: ParticipantCapabilities;
1272
+ _meta?: Meta;
1273
+ }
1274
+ /**
1275
+ * Event data for permissions_client_updated events.
1276
+ * Emitted when a client's permissions are changed.
1277
+ */
1278
+ interface PermissionsClientUpdatedEventData {
1279
+ /** Client whose permissions changed */
1280
+ clientId: ParticipantId;
1281
+ /** The permission changes that were applied */
1282
+ changes: Partial<ParticipantCapabilities>;
1283
+ /** Effective permissions after the update */
1284
+ effectivePermissions: ParticipantCapabilities;
1285
+ /** Participant who made the change */
1286
+ updatedBy: ParticipantId;
1287
+ }
1288
+ /**
1289
+ * Event data for permissions_agent_updated events.
1290
+ * Emitted when an agent's permission overrides are changed.
1291
+ */
1292
+ interface PermissionsAgentUpdatedEventData {
1293
+ /** Agent whose permissions changed */
1294
+ agentId: AgentId;
1295
+ /** The permission changes that were applied */
1296
+ changes: Partial<AgentPermissions>;
1297
+ /** Effective permissions after the update */
1298
+ effectivePermissions: AgentPermissions;
1299
+ /** Participant who made the change */
1300
+ updatedBy: ParticipantId;
1301
+ }
1302
+ /**
1303
+ * Metadata for federation routing and tracking.
1304
+ * Included in every message routed between federated systems.
1305
+ */
1306
+ interface FederationMetadata {
1307
+ /** System that originated this message */
1308
+ sourceSystem: string;
1309
+ /** Intended final destination system */
1310
+ targetSystem: string;
1311
+ /** Number of systems this message has traversed */
1312
+ hopCount: number;
1313
+ /** Maximum hops before rejection (prevents infinite loops) */
1314
+ maxHops?: number;
1315
+ /** Systems this message has traversed (for debugging/loop detection) */
1316
+ path?: string[];
1317
+ /** Timestamp when message was first sent (ms since epoch) */
1318
+ originTimestamp: Timestamp;
1319
+ /** Correlation ID for cross-system tracing */
1320
+ correlationId?: string;
1321
+ /**
1322
+ * Signature for integrity verification.
1323
+ * @todo Define signing algorithm and key management
1324
+ */
1325
+ signature?: string;
1326
+ }
1327
+ /**
1328
+ * Envelope for messages routed between federated systems.
1329
+ * Wraps the payload with routing metadata for tracking and loop prevention.
1330
+ *
1331
+ * @typeParam T - The payload type (typically Message)
1332
+ *
1333
+ * @example
1334
+ * ```typescript
1335
+ * const envelope: FederationEnvelope<Message> = {
1336
+ * payload: message,
1337
+ * federation: {
1338
+ * sourceSystem: 'alpha',
1339
+ * targetSystem: 'beta',
1340
+ * hopCount: 0,
1341
+ * originTimestamp: Date.now(),
1342
+ * },
1343
+ * };
1344
+ * ```
1345
+ */
1346
+ interface FederationEnvelope<T = unknown> {
1347
+ /** The payload being routed */
1348
+ payload: T;
1349
+ /** Federation routing metadata */
1350
+ federation: FederationMetadata;
1351
+ }
1352
+ /**
1353
+ * Configuration for federation routing behavior.
1354
+ * Used by gateways to control message routing policies.
1355
+ */
1356
+ interface FederationRoutingConfig {
1357
+ /** This system's identifier */
1358
+ systemId: string;
1359
+ /** Maximum hops to accept (default: 10) */
1360
+ maxHops?: number;
1361
+ /** Whether to track full path for debugging (default: false) */
1362
+ trackPath?: boolean;
1363
+ /** Systems we're willing to route to (undefined = all) */
1364
+ allowedTargets?: string[];
1365
+ /** Systems we accept routes from (undefined = all) */
1366
+ allowedSources?: string[];
1367
+ }
1368
+ /**
1369
+ * Configuration for buffering messages during federation outages.
1370
+ * Messages are stored locally until the peer reconnects.
1371
+ */
1372
+ interface FederationBufferConfig {
1373
+ /** Enable buffering of messages during disconnection (default: true) */
1374
+ enabled?: boolean;
1375
+ /** Maximum number of messages to buffer per peer (default: 1000) */
1376
+ maxMessages?: number;
1377
+ /** Maximum buffer size in bytes per peer (default: 10MB) */
1378
+ maxBytes?: number;
1379
+ /** Time to retain buffered messages in ms (default: 1 hour) */
1380
+ retentionMs?: number;
1381
+ /** Strategy when buffer is full */
1382
+ overflowStrategy?: 'drop-oldest' | 'drop-newest' | 'reject';
1383
+ }
1384
+ /**
1385
+ * Configuration for replaying events from event store on reconnection.
1386
+ * Supplements buffer with persisted events.
1387
+ */
1388
+ interface FederationReplayConfig {
1389
+ /** Enable replay from event store on reconnection (default: true) */
1390
+ enabled?: boolean;
1391
+ /** Maximum time window for replay in ms (default: 1 hour) */
1392
+ maxReplayWindowMs?: number;
1393
+ /** Maximum number of events to replay (default: 10000) */
1394
+ maxReplayEvents?: number;
1395
+ /** Filter for events to replay (optional) */
1396
+ filter?: SubscriptionFilter;
1397
+ }
1398
+ /**
1399
+ * Type of gateway reconnection event.
1400
+ */
1401
+ type GatewayReconnectionEventType = 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'reconnect_failed' | 'buffer_overflow' | 'replay_started' | 'replay_completed';
1402
+ /**
1403
+ * Event emitted during gateway reconnection lifecycle.
1404
+ */
1405
+ interface GatewayReconnectionEvent {
1406
+ /** Type of reconnection event */
1407
+ type: GatewayReconnectionEventType;
1408
+ /** Target system ID */
1409
+ systemId: string;
1410
+ /** Timestamp of the event */
1411
+ timestamp: Timestamp;
1412
+ /** Current reconnection attempt (for reconnecting events) */
1413
+ attempt?: number;
1414
+ /** Error message (for disconnected/reconnect_failed) */
1415
+ error?: string;
1416
+ /** Number of buffered messages (for buffer_overflow) */
1417
+ bufferedCount?: number;
1418
+ /** Number of events being replayed (for replay_started/completed) */
1419
+ replayCount?: number;
1420
+ /** Duration of outage in ms (for connected after reconnect) */
1421
+ outageDurationMs?: number;
1422
+ }
1423
+ /** Handler for gateway reconnection events */
1424
+ type GatewayReconnectionEventHandler = (event: GatewayReconnectionEvent) => void;
1425
+ /**
1426
+ * Options for gateway connection with reconnection support.
1427
+ * Extends base connection options with federation-specific settings.
1428
+ */
1429
+ interface GatewayReconnectionOptions {
1430
+ /** Enable automatic reconnection (default: true) */
1431
+ autoReconnect?: boolean;
1432
+ /** Initial delay before first reconnection attempt in ms (default: 1000) */
1433
+ initialDelayMs?: number;
1434
+ /** Maximum delay between reconnection attempts in ms (default: 30000) */
1435
+ maxDelayMs?: number;
1436
+ /** Backoff multiplier for exponential backoff (default: 2) */
1437
+ backoffMultiplier?: number;
1438
+ /** Maximum number of reconnection attempts (default: Infinity) */
1439
+ maxRetries?: number;
1440
+ /** Add random jitter to delays (default: true) */
1441
+ jitter?: boolean;
1442
+ /** Buffer configuration for outages */
1443
+ buffer?: FederationBufferConfig;
1444
+ /** Replay configuration for event store recovery */
1445
+ replay?: FederationReplayConfig;
1446
+ /** Handler for reconnection lifecycle events */
1447
+ onReconnectionEvent?: GatewayReconnectionEventHandler;
1448
+ }
1449
+ interface FederationConnectRequestParams {
1450
+ systemId: string;
1451
+ endpoint: string;
1452
+ auth?: FederationAuth;
1453
+ _meta?: Meta;
1454
+ }
1455
+ interface FederationConnectRequest extends MAPRequestBase<FederationConnectRequestParams> {
1456
+ method: 'map/federation/connect';
1457
+ params: FederationConnectRequestParams;
1458
+ }
1459
+ interface FederationConnectResponseResult {
1460
+ connected: boolean;
1461
+ systemInfo?: {
1462
+ name?: string;
1463
+ version?: string;
1464
+ capabilities?: ParticipantCapabilities;
1465
+ };
1466
+ _meta?: Meta;
1467
+ }
1468
+ interface FederationRouteRequestParams {
1469
+ /** Target system ID (for immediate next hop) */
1470
+ systemId: string;
1471
+ /**
1472
+ * Wrapped message with federation metadata.
1473
+ * Use this for new implementations.
1474
+ */
1475
+ envelope?: FederationEnvelope<Message>;
1476
+ /**
1477
+ * Raw message (legacy format).
1478
+ * @deprecated Use envelope instead for proper routing metadata
1479
+ */
1480
+ message?: Message;
1481
+ _meta?: Meta;
1482
+ }
1483
+ interface FederationRouteRequest extends MAPRequestBase<FederationRouteRequestParams> {
1484
+ method: 'map/federation/route';
1485
+ params: FederationRouteRequestParams;
1486
+ }
1487
+ interface FederationRouteResponseResult {
1488
+ routed: boolean;
1489
+ messageId?: MessageId;
1490
+ _meta?: Meta;
1491
+ }
1492
+ /**
1493
+ * Parameters for event notifications delivered to subscribers.
1494
+ *
1495
+ * The envelope contains both delivery metadata (subscriptionId, sequence)
1496
+ * and optional fields for deduplication and causal ordering.
1497
+ */
1498
+ interface EventNotificationParams {
1499
+ /** The subscription this event is being delivered to */
1500
+ subscriptionId: SubscriptionId;
1501
+ /** Monotonically increasing sequence number within this subscription */
1502
+ sequenceNumber: number;
1503
+ /**
1504
+ * Globally unique event identifier (ULID format).
1505
+ *
1506
+ * Used for:
1507
+ * - Deduplication (same event delivered multiple times)
1508
+ * - Replay references (afterEventId in replay requests)
1509
+ * - Causal tracking (referenced in causedBy arrays)
1510
+ *
1511
+ * Format: 26-character ULID, e.g., "01HQJY3KCNP5VXWZ8M4R6T2G9B"
1512
+ *
1513
+ * @remarks
1514
+ * If not provided by the server, deduplication is skipped.
1515
+ * New routers should always provide this field.
1516
+ */
1517
+ eventId?: string;
1518
+ /**
1519
+ * Server timestamp when the event was processed (milliseconds since epoch).
1520
+ *
1521
+ * This is the envelope-level timestamp, which may differ from event.timestamp
1522
+ * if the event was queued or replayed.
1523
+ */
1524
+ timestamp?: Timestamp;
1525
+ /**
1526
+ * Event IDs of events that causally precede this event.
1527
+ *
1528
+ * Used for enforcing causal ordering - this event should not be
1529
+ * processed until all events in causedBy have been processed.
1530
+ *
1531
+ * @example
1532
+ * A message_delivered event would have causedBy: [messagesentEventId]
1533
+ */
1534
+ causedBy?: string[];
1535
+ /** The event payload */
1536
+ event: Event;
1537
+ _meta?: Meta;
1538
+ }
1539
+ interface EventNotification extends MAPNotificationBase<EventNotificationParams> {
1540
+ method: 'map/event';
1541
+ params: EventNotificationParams;
1542
+ }
1543
+ interface MessageNotificationParams {
1544
+ message: Message;
1545
+ _meta?: Meta;
1546
+ }
1547
+ interface MessageNotification extends MAPNotificationBase<MessageNotificationParams> {
1548
+ method: 'map/message';
1549
+ params: MessageNotificationParams;
1550
+ }
1551
+ /** All MAP request types */
1552
+ type MAPRequest = ConnectRequest | DisconnectRequest | SessionListRequest | SessionLoadRequest | SessionCloseRequest | AgentsListRequest | AgentsGetRequest | SendRequest | SubscribeRequest | UnsubscribeRequest | ReplayRequest | AuthRefreshRequest | AgentsRegisterRequest | AgentsSpawnRequest | AgentsUnregisterRequest | AgentsUpdateRequest | AgentsStopRequest | AgentsSuspendRequest | AgentsResumeRequest | StructureGraphRequest | ScopesListRequest | ScopesGetRequest | ScopesCreateRequest | ScopesDeleteRequest | ScopesJoinRequest | ScopesLeaveRequest | ScopesMembersRequest | PermissionsUpdateRequest | InjectRequest | FederationConnectRequest | FederationRouteRequest;
1553
+ /** All MAP notification types */
1554
+ type MAPNotification = EventNotification | MessageNotification | SubscriptionAckNotification;
1555
+ /** Core methods - All implementations must support */
1556
+ declare const CORE_METHODS: {
1557
+ readonly CONNECT: "map/connect";
1558
+ readonly DISCONNECT: "map/disconnect";
1559
+ readonly SEND: "map/send";
1560
+ readonly SUBSCRIBE: "map/subscribe";
1561
+ readonly UNSUBSCRIBE: "map/unsubscribe";
1562
+ readonly REPLAY: "map/replay";
1563
+ };
1564
+ /** Observation methods - Query/read operations */
1565
+ declare const OBSERVATION_METHODS: {
1566
+ readonly AGENTS_LIST: "map/agents/list";
1567
+ readonly AGENTS_GET: "map/agents/get";
1568
+ readonly SCOPES_LIST: "map/scopes/list";
1569
+ readonly SCOPES_GET: "map/scopes/get";
1570
+ readonly SCOPES_MEMBERS: "map/scopes/members";
1571
+ readonly STRUCTURE_GRAPH: "map/structure/graph";
1572
+ };
1573
+ /** Lifecycle methods - Agent creation/destruction */
1574
+ declare const LIFECYCLE_METHODS: {
1575
+ readonly AGENTS_REGISTER: "map/agents/register";
1576
+ readonly AGENTS_UNREGISTER: "map/agents/unregister";
1577
+ readonly AGENTS_SPAWN: "map/agents/spawn";
1578
+ };
1579
+ /** State methods - Agent state management */
1580
+ declare const STATE_METHODS: {
1581
+ readonly AGENTS_UPDATE: "map/agents/update";
1582
+ readonly AGENTS_SUSPEND: "map/agents/suspend";
1583
+ readonly AGENTS_RESUME: "map/agents/resume";
1584
+ readonly AGENTS_STOP: "map/agents/stop";
1585
+ };
1586
+ /** Steering methods - External control */
1587
+ declare const STEERING_METHODS: {
1588
+ readonly INJECT: "map/inject";
1589
+ };
1590
+ /** Scope methods - Scope management */
1591
+ declare const SCOPE_METHODS: {
1592
+ readonly SCOPES_CREATE: "map/scopes/create";
1593
+ readonly SCOPES_DELETE: "map/scopes/delete";
1594
+ readonly SCOPES_JOIN: "map/scopes/join";
1595
+ readonly SCOPES_LEAVE: "map/scopes/leave";
1596
+ };
1597
+ /** Session methods */
1598
+ declare const SESSION_METHODS: {
1599
+ readonly SESSION_LIST: "map/session/list";
1600
+ readonly SESSION_LOAD: "map/session/load";
1601
+ readonly SESSION_CLOSE: "map/session/close";
1602
+ };
1603
+ /** Auth methods */
1604
+ declare const AUTH_METHODS: {
1605
+ readonly AUTH_REFRESH: "map/auth/refresh";
1606
+ };
1607
+ /** Permission methods */
1608
+ declare const PERMISSION_METHODS: {
1609
+ readonly PERMISSIONS_UPDATE: "map/permissions/update";
1610
+ };
1611
+ /** Federation methods */
1612
+ declare const FEDERATION_METHODS: {
1613
+ readonly FEDERATION_CONNECT: "map/federation/connect";
1614
+ readonly FEDERATION_ROUTE: "map/federation/route";
1615
+ };
1616
+ /** Notification methods */
1617
+ declare const NOTIFICATION_METHODS: {
1618
+ readonly EVENT: "map/event";
1619
+ readonly MESSAGE: "map/message";
1620
+ /** Client acknowledges received events (for backpressure) */
1621
+ readonly SUBSCRIBE_ACK: "map/subscribe.ack";
1622
+ };
1623
+ /** All MAP methods */
1624
+ declare const MAP_METHODS: {
1625
+ readonly FEDERATION_CONNECT: "map/federation/connect";
1626
+ readonly FEDERATION_ROUTE: "map/federation/route";
1627
+ readonly PERMISSIONS_UPDATE: "map/permissions/update";
1628
+ readonly AUTH_REFRESH: "map/auth/refresh";
1629
+ readonly SESSION_LIST: "map/session/list";
1630
+ readonly SESSION_LOAD: "map/session/load";
1631
+ readonly SESSION_CLOSE: "map/session/close";
1632
+ readonly SCOPES_CREATE: "map/scopes/create";
1633
+ readonly SCOPES_DELETE: "map/scopes/delete";
1634
+ readonly SCOPES_JOIN: "map/scopes/join";
1635
+ readonly SCOPES_LEAVE: "map/scopes/leave";
1636
+ readonly INJECT: "map/inject";
1637
+ readonly AGENTS_UPDATE: "map/agents/update";
1638
+ readonly AGENTS_SUSPEND: "map/agents/suspend";
1639
+ readonly AGENTS_RESUME: "map/agents/resume";
1640
+ readonly AGENTS_STOP: "map/agents/stop";
1641
+ readonly AGENTS_REGISTER: "map/agents/register";
1642
+ readonly AGENTS_UNREGISTER: "map/agents/unregister";
1643
+ readonly AGENTS_SPAWN: "map/agents/spawn";
1644
+ readonly AGENTS_LIST: "map/agents/list";
1645
+ readonly AGENTS_GET: "map/agents/get";
1646
+ readonly SCOPES_LIST: "map/scopes/list";
1647
+ readonly SCOPES_GET: "map/scopes/get";
1648
+ readonly SCOPES_MEMBERS: "map/scopes/members";
1649
+ readonly STRUCTURE_GRAPH: "map/structure/graph";
1650
+ readonly CONNECT: "map/connect";
1651
+ readonly DISCONNECT: "map/disconnect";
1652
+ readonly SEND: "map/send";
1653
+ readonly SUBSCRIBE: "map/subscribe";
1654
+ readonly UNSUBSCRIBE: "map/unsubscribe";
1655
+ readonly REPLAY: "map/replay";
1656
+ };
1657
+ declare const STRUCTURE_METHODS: {
1658
+ readonly STRUCTURE_GRAPH: "map/structure/graph";
1659
+ readonly SCOPES_CREATE: "map/scopes/create";
1660
+ readonly SCOPES_DELETE: "map/scopes/delete";
1661
+ readonly SCOPES_JOIN: "map/scopes/join";
1662
+ readonly SCOPES_LEAVE: "map/scopes/leave";
1663
+ readonly AGENTS_UPDATE: "map/agents/update";
1664
+ readonly AGENTS_SUSPEND: "map/agents/suspend";
1665
+ readonly AGENTS_RESUME: "map/agents/resume";
1666
+ readonly AGENTS_STOP: "map/agents/stop";
1667
+ readonly AGENTS_REGISTER: "map/agents/register";
1668
+ readonly AGENTS_UNREGISTER: "map/agents/unregister";
1669
+ readonly AGENTS_SPAWN: "map/agents/spawn";
1670
+ };
1671
+ declare const EXTENSION_METHODS: {
1672
+ readonly FEDERATION_CONNECT: "map/federation/connect";
1673
+ readonly FEDERATION_ROUTE: "map/federation/route";
1674
+ readonly INJECT: "map/inject";
1675
+ };
1676
+ /** JSON-RPC standard error codes */
1677
+ declare const PROTOCOL_ERROR_CODES: {
1678
+ readonly PARSE_ERROR: -32700;
1679
+ readonly INVALID_REQUEST: -32600;
1680
+ readonly METHOD_NOT_FOUND: -32601;
1681
+ readonly INVALID_PARAMS: -32602;
1682
+ readonly INTERNAL_ERROR: -32603;
1683
+ };
1684
+ /** Authentication error codes */
1685
+ declare const AUTH_ERROR_CODES: {
1686
+ readonly AUTH_REQUIRED: 1000;
1687
+ readonly AUTH_FAILED: 1001;
1688
+ readonly TOKEN_EXPIRED: 1002;
1689
+ readonly PERMISSION_DENIED: 1003;
1690
+ };
1691
+ /** Routing error codes */
1692
+ declare const ROUTING_ERROR_CODES: {
1693
+ readonly ADDRESS_NOT_FOUND: 2000;
1694
+ readonly AGENT_NOT_FOUND: 2001;
1695
+ readonly SCOPE_NOT_FOUND: 2002;
1696
+ readonly DELIVERY_FAILED: 2003;
1697
+ readonly ADDRESS_AMBIGUOUS: 2004;
1698
+ };
1699
+ /** Agent error codes */
1700
+ declare const AGENT_ERROR_CODES: {
1701
+ readonly AGENT_EXISTS: 3000;
1702
+ readonly STATE_INVALID: 3001;
1703
+ readonly NOT_RESPONDING: 3002;
1704
+ readonly TERMINATED: 3003;
1705
+ readonly SPAWN_FAILED: 3004;
1706
+ };
1707
+ /** Resource error codes */
1708
+ declare const RESOURCE_ERROR_CODES: {
1709
+ readonly EXHAUSTED: 4000;
1710
+ readonly RATE_LIMITED: 4001;
1711
+ readonly QUOTA_EXCEEDED: 4002;
1712
+ };
1713
+ /** Federation error codes - prefixed to avoid collision with AUTH_FAILED */
1714
+ declare const FEDERATION_ERROR_CODES: {
1715
+ readonly FEDERATION_UNAVAILABLE: 5000;
1716
+ readonly FEDERATION_SYSTEM_NOT_FOUND: 5001;
1717
+ readonly FEDERATION_AUTH_FAILED: 5002;
1718
+ readonly FEDERATION_ROUTE_REJECTED: 5003;
1719
+ /** Message has already visited this system (loop detected) */
1720
+ readonly FEDERATION_LOOP_DETECTED: 5010;
1721
+ /** Message exceeded maximum hop count */
1722
+ readonly FEDERATION_MAX_HOPS_EXCEEDED: 5011;
1723
+ };
1724
+ /** All error codes */
1725
+ declare const ERROR_CODES: {
1726
+ readonly FEDERATION_UNAVAILABLE: 5000;
1727
+ readonly FEDERATION_SYSTEM_NOT_FOUND: 5001;
1728
+ readonly FEDERATION_AUTH_FAILED: 5002;
1729
+ readonly FEDERATION_ROUTE_REJECTED: 5003;
1730
+ /** Message has already visited this system (loop detected) */
1731
+ readonly FEDERATION_LOOP_DETECTED: 5010;
1732
+ /** Message exceeded maximum hop count */
1733
+ readonly FEDERATION_MAX_HOPS_EXCEEDED: 5011;
1734
+ readonly EXHAUSTED: 4000;
1735
+ readonly RATE_LIMITED: 4001;
1736
+ readonly QUOTA_EXCEEDED: 4002;
1737
+ readonly AGENT_EXISTS: 3000;
1738
+ readonly STATE_INVALID: 3001;
1739
+ readonly NOT_RESPONDING: 3002;
1740
+ readonly TERMINATED: 3003;
1741
+ readonly SPAWN_FAILED: 3004;
1742
+ readonly ADDRESS_NOT_FOUND: 2000;
1743
+ readonly AGENT_NOT_FOUND: 2001;
1744
+ readonly SCOPE_NOT_FOUND: 2002;
1745
+ readonly DELIVERY_FAILED: 2003;
1746
+ readonly ADDRESS_AMBIGUOUS: 2004;
1747
+ readonly AUTH_REQUIRED: 1000;
1748
+ readonly AUTH_FAILED: 1001;
1749
+ readonly TOKEN_EXPIRED: 1002;
1750
+ readonly PERMISSION_DENIED: 1003;
1751
+ readonly PARSE_ERROR: -32700;
1752
+ readonly INVALID_REQUEST: -32600;
1753
+ readonly METHOD_NOT_FOUND: -32601;
1754
+ readonly INVALID_PARAMS: -32602;
1755
+ readonly INTERNAL_ERROR: -32603;
1756
+ };
1757
+ /** Protocol version */
1758
+ declare const PROTOCOL_VERSION: ProtocolVersion;
1759
+ /**
1760
+ * Maps methods to required capabilities.
1761
+ * Empty array means no special capability required.
1762
+ */
1763
+ declare const CAPABILITY_REQUIREMENTS: Record<string, string[]>;
1764
+ /** Check if a response is a success response */
1765
+ declare function isSuccessResponse<T>(response: MAPResponse<T>): response is MAPResponseSuccess<T>;
1766
+ /** Check if an address is a direct address */
1767
+ declare function isDirectAddress(address: Address): address is DirectAddress;
1768
+ /** Check if an address is a federated address */
1769
+ declare function isFederatedAddress(address: Address): address is FederatedAddress;
1770
+ /** Check if an address is a scope address */
1771
+ declare function isScopeAddress(address: Address): address is ScopeAddress;
1772
+ /** Check if an address is a broadcast address */
1773
+ declare function isBroadcastAddress(address: Address): address is BroadcastAddress;
1774
+ /** Check if an address is a hierarchical address */
1775
+ declare function isHierarchicalAddress(address: Address): address is HierarchicalAddress;
1776
+
1777
+ /**
1778
+ * Stream utilities for MAP protocol transport
1779
+ *
1780
+ * Provides helpers for converting byte streams to/from MAP message streams.
1781
+ */
1782
+
1783
+ /** Any MAP message type */
1784
+ type AnyMessage = MAPRequest | MAPResponse | MAPNotification | Record<string, unknown>;
1785
+ /**
1786
+ * Bidirectional message stream interface.
1787
+ * This is the transport abstraction that connection classes use.
1788
+ */
1789
+ interface Stream {
1790
+ writable: WritableStream<AnyMessage>;
1791
+ readable: ReadableStream<AnyMessage>;
1792
+ }
1793
+ /**
1794
+ * Converts raw byte streams to newline-delimited JSON message streams.
1795
+ *
1796
+ * This is the primary transport adapter - works with any byte stream
1797
+ * (stdio, TCP socket, etc.)
1798
+ *
1799
+ * @param readable - Input byte stream
1800
+ * @param writable - Output byte stream
1801
+ * @returns Stream interface for MAP messages
1802
+ */
1803
+ declare function ndJsonStream(readable: ReadableStream<Uint8Array>, writable: WritableStream<Uint8Array>): Stream;
1804
+ /**
1805
+ * Wraps a WebSocket in a Stream interface.
1806
+ *
1807
+ * @param ws - WebSocket instance (must be open or will wait for open)
1808
+ * @returns Stream interface for MAP messages
1809
+ */
1810
+ declare function websocketStream(ws: WebSocket): Stream;
1811
+ /**
1812
+ * Creates a pair of connected in-memory streams for testing.
1813
+ *
1814
+ * Messages written to one stream's writable appear on the other's readable.
1815
+ *
1816
+ * @returns Tuple of [clientStream, serverStream]
1817
+ */
1818
+ declare function createStreamPair(): [Stream, Stream];
1819
+
1820
+ /**
1821
+ * Subscription class for MAP event streams
1822
+ *
1823
+ * Provides both AsyncIterable and event emitter patterns for consuming events.
1824
+ * Includes automatic deduplication based on eventId when provided by the server.
1825
+ */
1826
+
1827
+ /**
1828
+ * Event handler callback type
1829
+ */
1830
+ type EventHandler = (event: Event) => void;
1831
+ /**
1832
+ * Subscription options
1833
+ */
1834
+ interface SubscriptionOptions {
1835
+ /** Filter for events */
1836
+ filter?: SubscriptionFilter;
1837
+ /** Buffer size for events before backpressure */
1838
+ bufferSize?: number;
1839
+ /**
1840
+ * Maximum number of eventIds to track for deduplication.
1841
+ * Older eventIds are evicted when this limit is reached.
1842
+ * Default: 10000
1843
+ */
1844
+ maxSeenEventIds?: number;
1845
+ }
1846
+ /**
1847
+ * Subscription to MAP events.
1848
+ *
1849
+ * Supports both async iteration and event handler patterns:
1850
+ *
1851
+ * ```typescript
1852
+ * // Async iteration
1853
+ * for await (const event of subscription) {
1854
+ * console.log(event);
1855
+ * }
1856
+ *
1857
+ * // Event handler
1858
+ * subscription.on('event', (event) => console.log(event));
1859
+ * ```
1860
+ *
1861
+ * ## Deduplication
1862
+ *
1863
+ * When the server provides `eventId` in the notification params,
1864
+ * the subscription automatically deduplicates events. This handles
1865
+ * scenarios like:
1866
+ * - Network retries delivering the same event twice
1867
+ * - Reconnection replay overlapping with already-received events
1868
+ *
1869
+ * If `eventId` is not provided, deduplication is skipped.
1870
+ *
1871
+ * ## Pause/Resume
1872
+ *
1873
+ * You can pause event delivery from the async iterator while still
1874
+ * buffering events:
1875
+ *
1876
+ * ```typescript
1877
+ * subscription.pause();
1878
+ * // Events are buffered but not yielded
1879
+ * subscription.resume();
1880
+ * // Buffered events are now yielded
1881
+ * ```
1882
+ *
1883
+ * ## Overflow Handling
1884
+ *
1885
+ * When the buffer is full, events are dropped and overflow handlers
1886
+ * are notified:
1887
+ *
1888
+ * ```typescript
1889
+ * subscription.on('overflow', (info) => {
1890
+ * console.log(`Dropped ${info.eventsDropped} events`);
1891
+ * });
1892
+ * ```
1893
+ */
1894
+ declare class Subscription implements AsyncIterable<Event> {
1895
+ #private;
1896
+ readonly id: SubscriptionId;
1897
+ readonly filter?: SubscriptionFilter;
1898
+ constructor(id: SubscriptionId, unsubscribe: () => Promise<void>, options?: SubscriptionOptions, sendAck?: (params: SubscriptionAckParams) => void);
1899
+ /**
1900
+ * Current subscription state
1901
+ */
1902
+ get state(): SubscriptionState;
1903
+ /**
1904
+ * Whether the subscription is closed
1905
+ */
1906
+ get isClosed(): boolean;
1907
+ /**
1908
+ * Whether the subscription is paused
1909
+ */
1910
+ get isPaused(): boolean;
1911
+ /**
1912
+ * Last received sequence number (for ordering verification)
1913
+ */
1914
+ get lastSequenceNumber(): number;
1915
+ /**
1916
+ * Last received eventId (for replay positioning)
1917
+ */
1918
+ get lastEventId(): string | undefined;
1919
+ /**
1920
+ * Last received server timestamp
1921
+ */
1922
+ get lastTimestamp(): number | undefined;
1923
+ /**
1924
+ * Number of events currently buffered
1925
+ */
1926
+ get bufferedCount(): number;
1927
+ /**
1928
+ * Number of eventIds being tracked for deduplication
1929
+ */
1930
+ get trackedEventIdCount(): number;
1931
+ /**
1932
+ * Total number of events dropped due to buffer overflow
1933
+ */
1934
+ get totalDropped(): number;
1935
+ /**
1936
+ * Whether the server supports acknowledgments
1937
+ */
1938
+ get supportsAck(): boolean;
1939
+ /**
1940
+ * Pause event delivery from the async iterator.
1941
+ * Events are still buffered but not yielded until resume() is called.
1942
+ * Event handlers (on('event', ...)) still receive events while paused.
1943
+ */
1944
+ pause(): void;
1945
+ /**
1946
+ * Resume event delivery from the async iterator.
1947
+ * Any events buffered during pause will be yielded.
1948
+ */
1949
+ resume(): void;
1950
+ /**
1951
+ * Acknowledge events up to a sequence number.
1952
+ * No-op if server doesn't support acks.
1953
+ *
1954
+ * @param upToSequence - Acknowledge all events up to and including this sequence.
1955
+ * If omitted, acknowledges up to lastSequenceNumber.
1956
+ */
1957
+ ack(upToSequence?: number): void;
1958
+ /**
1959
+ * Register an event or overflow handler
1960
+ */
1961
+ on(type: 'event', handler: EventHandler): this;
1962
+ on(type: 'overflow', handler: OverflowHandler): this;
1963
+ /**
1964
+ * Remove an event or overflow handler
1965
+ */
1966
+ off(type: 'event', handler: EventHandler): this;
1967
+ off(type: 'overflow', handler: OverflowHandler): this;
1968
+ /**
1969
+ * Register a one-time event handler
1970
+ */
1971
+ once(type: 'event', handler: EventHandler): this;
1972
+ /**
1973
+ * Unsubscribe and close the subscription
1974
+ */
1975
+ unsubscribe(): Promise<void>;
1976
+ /**
1977
+ * Set whether server supports acknowledgments.
1978
+ * Called by connection after capability negotiation.
1979
+ * @internal
1980
+ */
1981
+ _setServerSupportsAck(supports: boolean): void;
1982
+ /**
1983
+ * Push an event to the subscription (called by connection)
1984
+ * @internal
1985
+ */
1986
+ _pushEvent(params: EventNotificationParams): void;
1987
+ /**
1988
+ * Mark the subscription as closed (called by connection)
1989
+ * @internal
1990
+ */
1991
+ _close(): void;
1992
+ /**
1993
+ * Async iterator implementation
1994
+ */
1995
+ [Symbol.asyncIterator](): AsyncIterator<Event>;
1996
+ }
1997
+ /**
1998
+ * Create a subscription instance
1999
+ * @internal
2000
+ */
2001
+ declare function createSubscription(id: SubscriptionId, unsubscribe: () => Promise<void>, options?: SubscriptionOptions, sendAck?: (params: SubscriptionAckParams) => void): Subscription;
2002
+
2003
+ /**
2004
+ * Base connection class for MAP protocol
2005
+ *
2006
+ * Handles JSON-RPC message correlation, request/response matching,
2007
+ * and connection lifecycle management.
2008
+ */
2009
+
2010
+ /**
2011
+ * Handler for incoming requests
2012
+ */
2013
+ type RequestHandler = (method: string, params: unknown) => Promise<unknown>;
2014
+ /**
2015
+ * Handler for incoming notifications
2016
+ */
2017
+ type NotificationHandler = (method: string, params: unknown) => Promise<void>;
2018
+ /**
2019
+ * Connection state for tracking lifecycle
2020
+ */
2021
+ type ConnectionState = 'initial' | 'connecting' | 'connected' | 'reconnecting' | 'closed';
2022
+ /**
2023
+ * Handler for connection state changes
2024
+ */
2025
+ type StateChangeHandler = (newState: ConnectionState, oldState: ConnectionState) => void;
2026
+ /**
2027
+ * Options for base connection
2028
+ */
2029
+ interface BaseConnectionOptions {
2030
+ /** Default timeout for requests in milliseconds */
2031
+ defaultTimeout?: number;
2032
+ }
2033
+ /**
2034
+ * Base connection class providing JSON-RPC message handling.
2035
+ *
2036
+ * This class is used internally by the role-specific connection classes
2037
+ * (ClientConnection, AgentConnection, etc.)
2038
+ */
2039
+ declare class BaseConnection {
2040
+ #private;
2041
+ constructor(stream: Stream, options?: BaseConnectionOptions);
2042
+ /**
2043
+ * AbortSignal that triggers when the connection closes.
2044
+ * Useful for cancelling operations tied to this connection.
2045
+ */
2046
+ get signal(): AbortSignal;
2047
+ /**
2048
+ * Promise that resolves when the connection is closed.
2049
+ */
2050
+ get closed(): Promise<void>;
2051
+ /**
2052
+ * Whether the connection is closed
2053
+ */
2054
+ get isClosed(): boolean;
2055
+ /**
2056
+ * Set the handler for incoming requests
2057
+ */
2058
+ setRequestHandler(handler: RequestHandler): void;
2059
+ /**
2060
+ * Set the handler for incoming notifications
2061
+ */
2062
+ setNotificationHandler(handler: NotificationHandler): void;
2063
+ /**
2064
+ * Current connection state
2065
+ */
2066
+ get state(): ConnectionState;
2067
+ /**
2068
+ * Register a handler for state changes.
2069
+ *
2070
+ * @param handler - Function called when state changes
2071
+ * @returns Unsubscribe function to remove the handler
2072
+ */
2073
+ onStateChange(handler: StateChangeHandler): () => void;
2074
+ /**
2075
+ * Transition to a new state and notify handlers.
2076
+ * @internal
2077
+ */
2078
+ _transitionTo(newState: ConnectionState): void;
2079
+ /**
2080
+ * Reconnect with a new stream.
2081
+ *
2082
+ * This method is used by role-specific connections to replace the
2083
+ * underlying transport after a disconnect.
2084
+ *
2085
+ * @param newStream - The new stream to use
2086
+ * @throws If the connection is permanently closed
2087
+ */
2088
+ reconnect(newStream: Stream): Promise<void>;
2089
+ /**
2090
+ * Send a request and wait for response
2091
+ */
2092
+ sendRequest<TParams, TResult>(method: string, params?: TParams, options?: {
2093
+ timeout?: number;
2094
+ }): Promise<TResult>;
2095
+ /**
2096
+ * Send a notification (no response expected)
2097
+ */
2098
+ sendNotification<TParams>(method: string, params?: TParams): Promise<void>;
2099
+ /**
2100
+ * Send a response to a request
2101
+ */
2102
+ sendResponse<TResult>(id: RequestId, result: TResult): Promise<void>;
2103
+ /**
2104
+ * Send an error response to a request
2105
+ */
2106
+ sendErrorResponse(id: RequestId, error: MAPError): Promise<void>;
2107
+ /**
2108
+ * Close the connection
2109
+ */
2110
+ close(): Promise<void>;
2111
+ }
2112
+
2113
+ /**
2114
+ * Client connection for MAP protocol
2115
+ *
2116
+ * Used by clients to connect to a MAP system, query agents,
2117
+ * subscribe to events, and send messages.
2118
+ */
2119
+
2120
+ /**
2121
+ * Options for automatic reconnection
2122
+ */
2123
+ interface ReconnectionOptions {
2124
+ /** Enable automatic reconnection (default: false) */
2125
+ enabled: boolean;
2126
+ /** Maximum number of retry attempts (default: 10) */
2127
+ maxRetries?: number;
2128
+ /** Initial delay in milliseconds (default: 1000) */
2129
+ baseDelayMs?: number;
2130
+ /** Maximum delay in milliseconds (default: 30000) */
2131
+ maxDelayMs?: number;
2132
+ /** Add jitter to delays (default: true) */
2133
+ jitter?: boolean;
2134
+ /** Restore subscriptions after reconnect (default: true) */
2135
+ restoreSubscriptions?: boolean;
2136
+ /** Replay missed events on restore (default: true) */
2137
+ replayOnRestore?: boolean;
2138
+ /** Maximum events to replay per subscription (default: 1000) */
2139
+ maxReplayEventsPerSubscription?: number;
2140
+ }
2141
+ /**
2142
+ * Reconnection event types
2143
+ */
2144
+ type ReconnectionEventType = 'disconnected' | 'reconnecting' | 'reconnected' | 'reconnectFailed' | 'subscriptionRestored' | 'subscriptionRestoreFailed';
2145
+ /**
2146
+ * Handler for reconnection events
2147
+ */
2148
+ type ReconnectionEventHandler = (event: {
2149
+ type: ReconnectionEventType;
2150
+ attempt?: number;
2151
+ delay?: number;
2152
+ error?: Error;
2153
+ subscriptionId?: SubscriptionId;
2154
+ newSubscriptionId?: SubscriptionId;
2155
+ }) => void;
2156
+ /**
2157
+ * Options for client connection
2158
+ */
2159
+ interface ClientConnectionOptions extends BaseConnectionOptions {
2160
+ /** Client name for identification */
2161
+ name?: string;
2162
+ /** Client capabilities */
2163
+ capabilities?: ParticipantCapabilities;
2164
+ /** Factory to create new stream for reconnection */
2165
+ createStream?: () => Promise<Stream>;
2166
+ /** Reconnection options */
2167
+ reconnection?: ReconnectionOptions;
2168
+ }
2169
+ /**
2170
+ * Client connection to a MAP system.
2171
+ *
2172
+ * Provides methods for:
2173
+ * - Querying agents and structure
2174
+ * - Subscribing to events
2175
+ * - Sending messages to agents
2176
+ * - (With permissions) Steering agents
2177
+ */
2178
+ declare class ClientConnection {
2179
+ #private;
2180
+ constructor(stream: Stream, options?: ClientConnectionOptions);
2181
+ /**
2182
+ * Connect to the MAP system
2183
+ */
2184
+ connect(options?: {
2185
+ sessionId?: SessionId;
2186
+ auth?: {
2187
+ method: 'bearer' | 'api-key' | 'mtls' | 'none';
2188
+ token?: string;
2189
+ };
2190
+ }): Promise<ConnectResponseResult>;
2191
+ /**
2192
+ * Disconnect from the MAP system
2193
+ */
2194
+ disconnect(reason?: string): Promise<void>;
2195
+ /**
2196
+ * Whether the client is connected
2197
+ */
2198
+ get isConnected(): boolean;
2199
+ /**
2200
+ * Current session ID
2201
+ */
2202
+ get sessionId(): SessionId | null;
2203
+ /**
2204
+ * Server capabilities
2205
+ */
2206
+ get serverCapabilities(): ParticipantCapabilities | null;
2207
+ /**
2208
+ * AbortSignal that triggers when the connection closes
2209
+ */
2210
+ get signal(): AbortSignal;
2211
+ /**
2212
+ * Promise that resolves when the connection closes
2213
+ */
2214
+ get closed(): Promise<void>;
2215
+ /**
2216
+ * List available sessions
2217
+ */
2218
+ listSessions(): Promise<SessionListResponseResult>;
2219
+ /**
2220
+ * Load an existing session
2221
+ */
2222
+ loadSession(sessionId: SessionId): Promise<SessionLoadResponseResult>;
2223
+ /**
2224
+ * Close the current session
2225
+ */
2226
+ closeSession(sessionId?: SessionId): Promise<SessionCloseResponseResult>;
2227
+ /**
2228
+ * List agents with optional filters
2229
+ */
2230
+ listAgents(options?: AgentsListRequestParams): Promise<AgentsListResponseResult>;
2231
+ /**
2232
+ * Get a single agent by ID
2233
+ */
2234
+ getAgent(agentId: AgentId, options?: {
2235
+ include?: {
2236
+ children?: boolean;
2237
+ descendants?: boolean;
2238
+ };
2239
+ }): Promise<AgentsGetResponseResult>;
2240
+ /**
2241
+ * Get the agent structure/hierarchy graph
2242
+ */
2243
+ getStructureGraph(options?: StructureGraphRequestParams): Promise<StructureGraphResponseResult>;
2244
+ /**
2245
+ * List scopes
2246
+ */
2247
+ listScopes(options?: ScopesListRequestParams): Promise<ScopesListResponseResult>;
2248
+ /**
2249
+ * Get a single scope by ID
2250
+ */
2251
+ getScope(scopeId: ScopeId): Promise<Scope>;
2252
+ /**
2253
+ * List members of a scope
2254
+ */
2255
+ getScopeMembers(scopeId: ScopeId, options?: Omit<ScopesMembersRequestParams, 'scopeId'>): Promise<ScopesMembersResponseResult>;
2256
+ /**
2257
+ * Send a message to an address
2258
+ */
2259
+ send(to: Address, payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2260
+ /**
2261
+ * Send a message to a specific agent
2262
+ */
2263
+ sendToAgent(agentId: AgentId, payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2264
+ /**
2265
+ * Send a message to all agents in a scope
2266
+ */
2267
+ sendToScope(scopeId: ScopeId, payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2268
+ /**
2269
+ * Send a message to agents with a specific role
2270
+ */
2271
+ sendToRole(role: string, payload?: unknown, meta?: MessageMeta, withinScope?: ScopeId): Promise<SendResponseResult>;
2272
+ /**
2273
+ * Broadcast a message to all agents
2274
+ */
2275
+ broadcast(payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2276
+ /**
2277
+ * Send a request and wait for a correlated response
2278
+ *
2279
+ * This is a higher-level pattern for request/response messaging.
2280
+ * A correlationId is automatically generated.
2281
+ */
2282
+ request<T = unknown>(to: Address, payload?: unknown, options?: {
2283
+ timeout?: number;
2284
+ meta?: MessageMeta;
2285
+ }): Promise<Message<T>>;
2286
+ /**
2287
+ * Subscribe to events
2288
+ */
2289
+ subscribe(filter?: SubscriptionFilter): Promise<Subscription>;
2290
+ /**
2291
+ * Unsubscribe from events
2292
+ */
2293
+ unsubscribe(subscriptionId: SubscriptionId): Promise<void>;
2294
+ /**
2295
+ * Replay historical events.
2296
+ *
2297
+ * Uses keyset pagination - pass the last eventId from the previous
2298
+ * response to get the next page.
2299
+ *
2300
+ * @example
2301
+ * ```typescript
2302
+ * // Replay all events from the last hour
2303
+ * const result = await client.replay({
2304
+ * fromTimestamp: Date.now() - 3600000,
2305
+ * filter: { eventTypes: ['agent.registered'] },
2306
+ * limit: 100
2307
+ * });
2308
+ *
2309
+ * // Paginate through results
2310
+ * let afterEventId: string | undefined;
2311
+ * do {
2312
+ * const page = await client.replay({ afterEventId, limit: 100 });
2313
+ * for (const item of page.events) {
2314
+ * console.log(item.eventId, item.event);
2315
+ * }
2316
+ * afterEventId = page.events.at(-1)?.eventId;
2317
+ * } while (page.hasMore);
2318
+ * ```
2319
+ */
2320
+ replay(params?: ReplayRequestParams): Promise<ReplayResponseResult>;
2321
+ /**
2322
+ * Replay all events matching filter, handling pagination automatically.
2323
+ *
2324
+ * Returns an async generator for streaming through all results.
2325
+ *
2326
+ * @example
2327
+ * ```typescript
2328
+ * for await (const item of client.replayAll({
2329
+ * filter: { eventTypes: ['agent.registered'] }
2330
+ * })) {
2331
+ * console.log(item.eventId, item.event);
2332
+ * }
2333
+ * ```
2334
+ */
2335
+ replayAll(params?: Omit<ReplayRequestParams, 'afterEventId'>): AsyncGenerator<ReplayedEvent>;
2336
+ /**
2337
+ * Inject context into a running agent
2338
+ */
2339
+ inject(agentId: AgentId, content: unknown, delivery?: 'interrupt' | 'queue' | 'best-effort'): Promise<InjectResponseResult>;
2340
+ /**
2341
+ * Request an agent to stop
2342
+ */
2343
+ stopAgent(agentId: AgentId, options?: {
2344
+ reason?: string;
2345
+ force?: boolean;
2346
+ }): Promise<{
2347
+ stopping: boolean;
2348
+ agent?: Agent;
2349
+ }>;
2350
+ /**
2351
+ * Suspend an agent
2352
+ */
2353
+ suspendAgent(agentId: AgentId, reason?: string): Promise<{
2354
+ suspended: boolean;
2355
+ agent?: Agent;
2356
+ }>;
2357
+ /**
2358
+ * Resume a suspended agent
2359
+ */
2360
+ resumeAgent(agentId: AgentId): Promise<{
2361
+ resumed: boolean;
2362
+ agent?: Agent;
2363
+ }>;
2364
+ /**
2365
+ * Current connection state
2366
+ */
2367
+ get state(): ConnectionState;
2368
+ /**
2369
+ * Whether the connection is currently reconnecting
2370
+ */
2371
+ get isReconnecting(): boolean;
2372
+ /**
2373
+ * Register a handler for reconnection events.
2374
+ *
2375
+ * @param handler - Function called when reconnection events occur
2376
+ * @returns Unsubscribe function to remove the handler
2377
+ *
2378
+ * @example
2379
+ * ```typescript
2380
+ * const unsubscribe = client.onReconnection((event) => {
2381
+ * switch (event.type) {
2382
+ * case 'disconnected':
2383
+ * console.log('Connection lost');
2384
+ * break;
2385
+ * case 'reconnecting':
2386
+ * console.log(`Reconnecting, attempt ${event.attempt}`);
2387
+ * break;
2388
+ * case 'reconnected':
2389
+ * console.log('Reconnected successfully');
2390
+ * break;
2391
+ * case 'reconnectFailed':
2392
+ * console.log('Failed to reconnect:', event.error);
2393
+ * break;
2394
+ * }
2395
+ * });
2396
+ * ```
2397
+ */
2398
+ onReconnection(handler: ReconnectionEventHandler): () => void;
2399
+ /**
2400
+ * Register a handler for connection state changes.
2401
+ *
2402
+ * @param handler - Function called when state changes
2403
+ * @returns Unsubscribe function to remove the handler
2404
+ */
2405
+ onStateChange(handler: (newState: ConnectionState, oldState: ConnectionState) => void): () => void;
2406
+ }
2407
+
2408
+ /**
2409
+ * Agent connection for MAP protocol
2410
+ *
2411
+ * Used by agents to connect to a MAP system, receive messages,
2412
+ * update state, spawn children, and communicate with peers.
2413
+ */
2414
+
2415
+ /**
2416
+ * Handler for incoming messages addressed to this agent
2417
+ */
2418
+ type MessageHandler = (message: Message) => void | Promise<void>;
2419
+ /**
2420
+ * Options for automatic reconnection
2421
+ */
2422
+ interface AgentReconnectionOptions {
2423
+ /** Enable automatic reconnection (default: false) */
2424
+ enabled: boolean;
2425
+ /** Maximum number of retry attempts (default: 10) */
2426
+ maxRetries?: number;
2427
+ /** Initial delay in milliseconds (default: 1000) */
2428
+ baseDelayMs?: number;
2429
+ /** Maximum delay in milliseconds (default: 30000) */
2430
+ maxDelayMs?: number;
2431
+ /** Add jitter to delays (default: true) */
2432
+ jitter?: boolean;
2433
+ /** Restore scope memberships after reconnect (default: true) */
2434
+ restoreScopeMemberships?: boolean;
2435
+ }
2436
+ /**
2437
+ * Agent reconnection event types
2438
+ */
2439
+ type AgentReconnectionEventType = 'disconnected' | 'reconnecting' | 'reconnected' | 'reconnectFailed';
2440
+ /**
2441
+ * Handler for reconnection events
2442
+ */
2443
+ type AgentReconnectionEventHandler = (event: {
2444
+ type: AgentReconnectionEventType;
2445
+ attempt?: number;
2446
+ delay?: number;
2447
+ error?: Error;
2448
+ }) => void;
2449
+ /**
2450
+ * Options for agent connection
2451
+ */
2452
+ interface AgentConnectionOptions extends BaseConnectionOptions {
2453
+ /** Agent name */
2454
+ name?: string;
2455
+ /** Agent role */
2456
+ role?: string;
2457
+ /** Agent capabilities */
2458
+ capabilities?: ParticipantCapabilities;
2459
+ /** Agent visibility */
2460
+ visibility?: AgentVisibility;
2461
+ /** Parent agent ID (if this is a child agent) */
2462
+ parent?: AgentId;
2463
+ /** Initial scopes to join */
2464
+ scopes?: ScopeId[];
2465
+ /** Factory to create new stream for reconnection */
2466
+ createStream?: () => Promise<Stream>;
2467
+ /** Reconnection options */
2468
+ reconnection?: AgentReconnectionOptions;
2469
+ }
2470
+ /**
2471
+ * Agent connection to a MAP system.
2472
+ *
2473
+ * Provides methods for:
2474
+ * - Registering self with the system
2475
+ * - Receiving and handling messages
2476
+ * - Sending messages to other agents
2477
+ * - Spawning child agents
2478
+ * - Updating own state
2479
+ * - Managing scope memberships
2480
+ */
2481
+ declare class AgentConnection {
2482
+ #private;
2483
+ constructor(stream: Stream, options?: AgentConnectionOptions);
2484
+ /**
2485
+ * Connect and register with the MAP system
2486
+ */
2487
+ connect(options?: {
2488
+ agentId?: AgentId;
2489
+ auth?: {
2490
+ method: 'bearer' | 'api-key' | 'mtls' | 'none';
2491
+ token?: string;
2492
+ };
2493
+ }): Promise<{
2494
+ connection: ConnectResponseResult;
2495
+ agent: Agent;
2496
+ }>;
2497
+ /**
2498
+ * Disconnect from the MAP system
2499
+ */
2500
+ disconnect(reason?: string): Promise<void>;
2501
+ /**
2502
+ * Whether the agent is connected
2503
+ */
2504
+ get isConnected(): boolean;
2505
+ /**
2506
+ * This agent's ID
2507
+ */
2508
+ get agentId(): AgentId | null;
2509
+ /**
2510
+ * Current session ID
2511
+ */
2512
+ get sessionId(): SessionId | null;
2513
+ /**
2514
+ * Server capabilities
2515
+ */
2516
+ get serverCapabilities(): ParticipantCapabilities | null;
2517
+ /**
2518
+ * Current agent state
2519
+ */
2520
+ get state(): AgentState;
2521
+ /**
2522
+ * AbortSignal that triggers when the connection closes
2523
+ */
2524
+ get signal(): AbortSignal;
2525
+ /**
2526
+ * Promise that resolves when the connection closes
2527
+ */
2528
+ get closed(): Promise<void>;
2529
+ /**
2530
+ * Register a handler for incoming messages
2531
+ */
2532
+ onMessage(handler: MessageHandler): this;
2533
+ /**
2534
+ * Remove a message handler
2535
+ */
2536
+ offMessage(handler: MessageHandler): this;
2537
+ /**
2538
+ * Update this agent's state
2539
+ */
2540
+ updateState(state: AgentState): Promise<Agent>;
2541
+ /**
2542
+ * Update this agent's metadata
2543
+ */
2544
+ updateMetadata(metadata: Record<string, unknown>): Promise<Agent>;
2545
+ /**
2546
+ * Mark this agent as busy
2547
+ */
2548
+ busy(): Promise<Agent>;
2549
+ /**
2550
+ * Mark this agent as idle
2551
+ */
2552
+ idle(): Promise<Agent>;
2553
+ /**
2554
+ * Mark this agent as done/stopped
2555
+ */
2556
+ done(result?: {
2557
+ exitCode?: number;
2558
+ exitReason?: string;
2559
+ }): Promise<void>;
2560
+ /**
2561
+ * Spawn a child agent
2562
+ */
2563
+ spawn(options: {
2564
+ agentId?: AgentId;
2565
+ name?: string;
2566
+ role?: string;
2567
+ visibility?: AgentVisibility;
2568
+ capabilities?: ParticipantCapabilities;
2569
+ scopes?: ScopeId[];
2570
+ initialMessage?: Message;
2571
+ metadata?: Record<string, unknown>;
2572
+ }): Promise<AgentsSpawnResponseResult>;
2573
+ /**
2574
+ * Send a message to an address
2575
+ */
2576
+ send(to: Address, payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2577
+ /**
2578
+ * Send a message to the parent agent
2579
+ */
2580
+ sendToParent(payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2581
+ /**
2582
+ * Send a message to child agents
2583
+ */
2584
+ sendToChildren(payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2585
+ /**
2586
+ * Send a message to a specific agent
2587
+ */
2588
+ sendToAgent(agentId: AgentId, payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2589
+ /**
2590
+ * Send a message to all agents in a scope
2591
+ */
2592
+ sendToScope(scopeId: ScopeId, payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2593
+ /**
2594
+ * Send a message to sibling agents
2595
+ */
2596
+ sendToSiblings(payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2597
+ /**
2598
+ * Reply to a message (uses correlationId from original)
2599
+ */
2600
+ reply(originalMessage: Message, payload?: unknown, meta?: MessageMeta): Promise<SendResponseResult>;
2601
+ /**
2602
+ * Create a new scope
2603
+ */
2604
+ createScope(options: ScopesCreateRequestParams): Promise<Scope>;
2605
+ /**
2606
+ * Join a scope
2607
+ */
2608
+ joinScope(scopeId: ScopeId): Promise<ScopesJoinResponseResult>;
2609
+ /**
2610
+ * Leave a scope
2611
+ */
2612
+ leaveScope(scopeId: ScopeId): Promise<ScopesLeaveResponseResult>;
2613
+ /**
2614
+ * Subscribe to events
2615
+ */
2616
+ subscribe(filter?: SubscriptionFilter): Promise<Subscription>;
2617
+ /**
2618
+ * Unsubscribe from events
2619
+ */
2620
+ unsubscribe(subscriptionId: SubscriptionId): Promise<void>;
2621
+ /**
2622
+ * Current connection state
2623
+ */
2624
+ get connectionState(): ConnectionState;
2625
+ /**
2626
+ * Whether the connection is currently reconnecting
2627
+ */
2628
+ get isReconnecting(): boolean;
2629
+ /**
2630
+ * Register a handler for reconnection events.
2631
+ *
2632
+ * @param handler - Function called when reconnection events occur
2633
+ * @returns Unsubscribe function to remove the handler
2634
+ */
2635
+ onReconnection(handler: AgentReconnectionEventHandler): () => void;
2636
+ /**
2637
+ * Register a handler for connection state changes.
2638
+ *
2639
+ * @param handler - Function called when state changes
2640
+ * @returns Unsubscribe function to remove the handler
2641
+ */
2642
+ onStateChange(handler: (newState: ConnectionState, oldState: ConnectionState) => void): () => void;
2643
+ }
2644
+
2645
+ /**
2646
+ * Permission utilities for MAP SDK
2647
+ *
2648
+ * Provides building blocks for implementing the 4-layer permission model:
2649
+ * - Layer 1: System configuration (what's exposed at all)
2650
+ * - Layer 2: Client permissions (what can this client do)
2651
+ * - Layer 3: Scope permissions (what's allowed in this scope)
2652
+ * - Layer 4: Agent permissions (what can this agent do)
2653
+ *
2654
+ * These utilities are opt-in building blocks for router implementations.
2655
+ * They provide the logic for permission checks but don't enforce them.
2656
+ */
2657
+
2658
+ /**
2659
+ * System-level exposure configuration.
2660
+ * Controls what entities are visible to participants at all.
2661
+ */
2662
+ interface SystemExposure {
2663
+ agents?: {
2664
+ /** Whether agents are public by default (default: true) */
2665
+ publicByDefault?: boolean;
2666
+ /** Glob patterns for agents that are always public */
2667
+ publicAgents?: string[];
2668
+ /** Glob patterns for agents that are always hidden (takes precedence) */
2669
+ hiddenAgents?: string[];
2670
+ };
2671
+ events?: {
2672
+ /** Event types that are exposed (whitelist, if provided) */
2673
+ exposedTypes?: EventType[];
2674
+ /** Event types that are always hidden (blacklist) */
2675
+ hiddenTypes?: EventType[];
2676
+ };
2677
+ scopes?: {
2678
+ /** Whether scopes are public by default (default: true) */
2679
+ publicByDefault?: boolean;
2680
+ /** Glob patterns for scopes that are always public */
2681
+ publicScopes?: string[];
2682
+ /** Glob patterns for scopes that are always hidden (takes precedence) */
2683
+ hiddenScopes?: string[];
2684
+ };
2685
+ }
2686
+ /**
2687
+ * Full system configuration for permissions
2688
+ */
2689
+ interface PermissionSystemConfig {
2690
+ /** What entities are exposed to participants */
2691
+ exposure?: SystemExposure;
2692
+ /** Resource limits */
2693
+ limits?: {
2694
+ maxConnections?: number;
2695
+ maxConnectionsPerClient?: number;
2696
+ maxSubscriptionsPerConnection?: number;
2697
+ maxAgentsPerClient?: number;
2698
+ };
2699
+ }
2700
+ /**
2701
+ * Represents a connected participant for permission checks
2702
+ */
2703
+ interface PermissionParticipant {
2704
+ /** Participant ID */
2705
+ id: string;
2706
+ /** Participant type */
2707
+ type: ParticipantType;
2708
+ /** Granted capabilities */
2709
+ capabilities: ParticipantCapabilities;
2710
+ }
2711
+ /**
2712
+ * Context for permission checks
2713
+ */
2714
+ interface PermissionContext {
2715
+ /** System-wide configuration */
2716
+ system: PermissionSystemConfig;
2717
+ /** The participant performing the action */
2718
+ participant: PermissionParticipant;
2719
+ /** Agent IDs owned by this participant */
2720
+ ownedAgentIds?: AgentId[];
2721
+ /** Scope membership: scopeId -> agent IDs that are members */
2722
+ scopeMembership?: Map<ScopeId, AgentId[]>;
2723
+ }
2724
+ /**
2725
+ * Action being performed for permission checking
2726
+ */
2727
+ interface PermissionAction {
2728
+ /** Action category */
2729
+ type: 'query' | 'message' | 'lifecycle' | 'scope' | 'subscribe';
2730
+ /** Wire method name (e.g., 'map/agents/list') */
2731
+ method: string;
2732
+ /** Target of the action */
2733
+ target?: {
2734
+ agentId?: AgentId;
2735
+ scopeId?: ScopeId;
2736
+ eventTypes?: EventType[];
2737
+ };
2738
+ }
2739
+ /**
2740
+ * Result of a permission check
2741
+ */
2742
+ interface PermissionResult {
2743
+ /** Whether the action is allowed */
2744
+ allowed: boolean;
2745
+ /** Reason for denial (if denied) */
2746
+ reason?: string;
2747
+ /** Which layer denied the action (if denied) */
2748
+ layer?: 1 | 2 | 3 | 4;
2749
+ }
2750
+ /**
2751
+ * Check if an agent is exposed by system configuration.
2752
+ *
2753
+ * Hidden patterns take precedence over public patterns.
2754
+ * If no configuration, agents are exposed by default.
2755
+ *
2756
+ * @param exposure - System exposure configuration
2757
+ * @param agentId - Agent ID to check
2758
+ * @returns true if the agent is exposed
2759
+ */
2760
+ declare function isAgentExposed(exposure: SystemExposure | undefined, agentId: AgentId): boolean;
2761
+ /**
2762
+ * Check if an event type is exposed by system configuration.
2763
+ *
2764
+ * Hidden types take precedence. If a whitelist is provided,
2765
+ * only those types are exposed.
2766
+ *
2767
+ * @param exposure - System exposure configuration
2768
+ * @param eventType - Event type to check
2769
+ * @returns true if the event type is exposed
2770
+ */
2771
+ declare function isEventTypeExposed(exposure: SystemExposure | undefined, eventType: EventType): boolean;
2772
+ /**
2773
+ * Check if a scope is exposed by system configuration.
2774
+ *
2775
+ * Hidden patterns take precedence over public patterns.
2776
+ *
2777
+ * @param exposure - System exposure configuration
2778
+ * @param scopeId - Scope ID to check
2779
+ * @returns true if the scope is exposed
2780
+ */
2781
+ declare function isScopeExposed(exposure: SystemExposure | undefined, scopeId: ScopeId): boolean;
2782
+ /**
2783
+ * Check if a participant has a specific capability.
2784
+ *
2785
+ * @param capabilities - Participant's capabilities
2786
+ * @param path - Capability path like 'observation.canQuery'
2787
+ * @returns true if the capability is granted
2788
+ *
2789
+ * @example
2790
+ * ```typescript
2791
+ * if (hasCapability(participant.capabilities, 'lifecycle.canSpawn')) {
2792
+ * // Can spawn agents
2793
+ * }
2794
+ * ```
2795
+ */
2796
+ declare function hasCapability(capabilities: ParticipantCapabilities, path: string): boolean;
2797
+ /**
2798
+ * Check if a participant can perform a method based on capabilities.
2799
+ *
2800
+ * @param method - Wire method name (e.g., 'map/agents/list')
2801
+ * @param capabilities - Participant's capabilities
2802
+ * @returns true if all required capabilities are present
2803
+ */
2804
+ declare function canPerformMethod(method: string, capabilities: ParticipantCapabilities): boolean;
2805
+
2806
+ /**
2807
+ * Check if a participant can see a scope.
2808
+ *
2809
+ * @param scope - The scope to check
2810
+ * @param participant - The participant
2811
+ * @param memberAgentIds - Agent IDs owned by participant that are scope members
2812
+ * @returns true if the participant can see the scope
2813
+ */
2814
+ declare function canSeeScope(scope: Scope, participant: PermissionParticipant, memberAgentIds?: AgentId[]): boolean;
2815
+ /**
2816
+ * Check if a participant can send messages to a scope.
2817
+ *
2818
+ * @param scope - The scope to check
2819
+ * @param participant - The participant
2820
+ * @param memberAgentIds - Agent IDs owned by participant that are scope members
2821
+ * @returns true if the participant can send to the scope
2822
+ */
2823
+ declare function canSendToScope(scope: Scope, participant: PermissionParticipant, memberAgentIds?: AgentId[]): boolean;
2824
+ /**
2825
+ * Check if a participant can join a scope.
2826
+ *
2827
+ * @param scope - The scope to check
2828
+ * @param participantType - Type of the participant
2829
+ * @param agentRole - Role of the agent trying to join (for role-based policies)
2830
+ * @returns true if the participant can join the scope
2831
+ */
2832
+ declare function canJoinScope(scope: Scope, participantType: ParticipantType, agentRole?: string): boolean;
2833
+ /**
2834
+ * Check if a participant can see an agent.
2835
+ *
2836
+ * @param agent - The agent to check
2837
+ * @param participant - The participant
2838
+ * @param ownedAgentIds - Agent IDs owned by this participant
2839
+ * @returns true if the participant can see the agent
2840
+ */
2841
+ declare function canSeeAgent(agent: Agent, participant: PermissionParticipant, ownedAgentIds?: AgentId[]): boolean;
2842
+ /**
2843
+ * Check if a participant can send messages to an agent.
2844
+ *
2845
+ * @param agent - Target agent
2846
+ * @param participant - The participant
2847
+ * @param ownedAgentIds - Agent IDs owned by this participant
2848
+ * @returns true if the participant can message the agent
2849
+ */
2850
+ declare function canMessageAgent(agent: Agent, participant: PermissionParticipant, ownedAgentIds?: AgentId[]): boolean;
2851
+ /**
2852
+ * Check if a participant can control an agent (stop, suspend, etc.).
2853
+ *
2854
+ * @param agent - Target agent
2855
+ * @param participant - The participant
2856
+ * @param ownedAgentIds - Agent IDs owned by this participant
2857
+ * @returns true if the participant can control the agent
2858
+ */
2859
+ declare function canControlAgent(agent: Agent, participant: PermissionParticipant, ownedAgentIds?: AgentId[]): boolean;
2860
+ /**
2861
+ * Check if an action is permitted across all 4 layers.
2862
+ *
2863
+ * This is the main entry point for comprehensive permission checking.
2864
+ * It evaluates each layer in order and returns the first denial or success.
2865
+ *
2866
+ * @param context - Permission context with system config and participant info
2867
+ * @param action - The action to check
2868
+ * @returns Permission result with allowed status, reason, and layer
2869
+ *
2870
+ * @example
2871
+ * ```typescript
2872
+ * const result = canPerformAction(
2873
+ * {
2874
+ * system: { exposure: { agents: { hiddenAgents: ['internal-*'] } } },
2875
+ * participant: { id: 'client-1', type: 'client', capabilities },
2876
+ * ownedAgentIds: ['agent-1'],
2877
+ * },
2878
+ * {
2879
+ * type: 'query',
2880
+ * method: 'map/agents/get',
2881
+ * target: { agentId: 'internal-worker' },
2882
+ * }
2883
+ * );
2884
+ *
2885
+ * if (!result.allowed) {
2886
+ * console.log(`Denied at layer ${result.layer}: ${result.reason}`);
2887
+ * }
2888
+ * ```
2889
+ */
2890
+ declare function canPerformAction(context: PermissionContext, action: PermissionAction): PermissionResult;
2891
+ /**
2892
+ * Filter agents to only those visible to the participant.
2893
+ *
2894
+ * Applies both Layer 1 (system exposure) and Layer 4 (agent visibility).
2895
+ *
2896
+ * @param agents - Agents to filter
2897
+ * @param context - Permission context
2898
+ * @returns Filtered list of visible agents
2899
+ */
2900
+ declare function filterVisibleAgents(agents: Agent[], context: PermissionContext): Agent[];
2901
+ /**
2902
+ * Filter scopes to only those visible to the participant.
2903
+ *
2904
+ * Applies both Layer 1 (system exposure) and Layer 3 (scope visibility).
2905
+ *
2906
+ * @param scopes - Scopes to filter
2907
+ * @param context - Permission context
2908
+ * @returns Filtered list of visible scopes
2909
+ */
2910
+ declare function filterVisibleScopes(scopes: Scope[], context: PermissionContext): Scope[];
2911
+ /**
2912
+ * Filter events to only those visible to the participant.
2913
+ *
2914
+ * Applies Layer 1 (system exposure) for event types.
2915
+ *
2916
+ * @param events - Events to filter
2917
+ * @param context - Permission context
2918
+ * @returns Filtered list of visible events
2919
+ */
2920
+ declare function filterVisibleEvents(events: Event[], context: PermissionContext): Event[];
2921
+ /**
2922
+ * Deep merge two permission objects.
2923
+ * Second object's fields override first at the leaf level.
2924
+ *
2925
+ * @param base - Base permissions
2926
+ * @param override - Override permissions (partial)
2927
+ * @returns Merged permissions
2928
+ */
2929
+ declare function deepMergePermissions(base: AgentPermissions, override: Partial<AgentPermissions>): AgentPermissions;
2930
+ /**
2931
+ * Map legacy AgentVisibility to AgentVisibilityRule.
2932
+ *
2933
+ * @param visibility - Legacy visibility value
2934
+ * @returns Equivalent visibility rule
2935
+ */
2936
+ declare function mapVisibilityToRule(visibility: AgentVisibility): AgentVisibilityRule;
2937
+ /**
2938
+ * Default agent permission configuration.
2939
+ * Used when no configuration is provided.
2940
+ */
2941
+ declare const DEFAULT_AGENT_PERMISSION_CONFIG: AgentPermissionConfig;
2942
+ /**
2943
+ * Resolve effective permissions for an agent.
2944
+ *
2945
+ * Resolution order:
2946
+ * 1. Start with system default permissions
2947
+ * 2. If agent has a role, deep merge role permissions
2948
+ * 3. Deep merge agent's permissionOverrides
2949
+ * 4. (Backwards compat) Map legacy visibility field if no override
2950
+ *
2951
+ * @param agent - The agent to resolve permissions for
2952
+ * @param config - System permission configuration
2953
+ * @returns Resolved effective permissions
2954
+ *
2955
+ * @example
2956
+ * ```typescript
2957
+ * const config: AgentPermissionConfig = {
2958
+ * defaultPermissions: { canSee: { agents: 'all' } },
2959
+ * rolePermissions: {
2960
+ * worker: { canSee: { agents: 'hierarchy' } },
2961
+ * },
2962
+ * };
2963
+ *
2964
+ * const agent = { id: 'a1', role: 'worker', ownerId: 'c1', state: 'active' };
2965
+ * const perms = resolveAgentPermissions(agent, config);
2966
+ * // perms.canSee.agents === 'hierarchy'
2967
+ * ```
2968
+ */
2969
+ declare function resolveAgentPermissions(agent: Agent, config?: AgentPermissionConfig): AgentPermissions;
2970
+ /**
2971
+ * Context for checking if an agent accepts messages from a sender.
2972
+ */
2973
+ interface AcceptanceContext {
2974
+ /** Type of the sender */
2975
+ senderType: ParticipantType;
2976
+ /** Participant ID of the sender */
2977
+ senderId: ParticipantId;
2978
+ /** If sender is an agent, its agent ID */
2979
+ senderAgentId?: AgentId;
2980
+ /** If sender is from a federated system, its system ID */
2981
+ senderSystemId?: string;
2982
+ /** Whether sender is the parent of target */
2983
+ isParent?: boolean;
2984
+ /** Whether sender is a child of target */
2985
+ isChild?: boolean;
2986
+ /** Whether sender is an ancestor of target */
2987
+ isAncestor?: boolean;
2988
+ /** Whether sender is a descendant of target */
2989
+ isDescendant?: boolean;
2990
+ /** Scope IDs that both sender and target are members of */
2991
+ sharedScopes?: ScopeId[];
2992
+ }
2993
+ /**
2994
+ * Check if an agent accepts messages from the given sender.
2995
+ *
2996
+ * Uses the agent's resolved permissions to determine if the sender
2997
+ * is allowed based on sender type and acceptance rules.
2998
+ *
2999
+ * @param targetAgent - The agent that would receive the message
3000
+ * @param context - Information about the sender
3001
+ * @param config - System permission configuration
3002
+ * @returns true if the agent accepts messages from this sender
3003
+ *
3004
+ * @example
3005
+ * ```typescript
3006
+ * const accepts = canAgentAcceptMessage(
3007
+ * targetAgent,
3008
+ * {
3009
+ * senderType: 'agent',
3010
+ * senderId: 'client-1',
3011
+ * senderAgentId: 'agent-2',
3012
+ * isParent: true,
3013
+ * },
3014
+ * config
3015
+ * );
3016
+ * ```
3017
+ */
3018
+ declare function canAgentAcceptMessage(targetAgent: Agent, context: AcceptanceContext, config?: AgentPermissionConfig): boolean;
3019
+ /**
3020
+ * Check if an agent can see another agent based on permissions.
3021
+ *
3022
+ * @param viewerAgent - The agent trying to see
3023
+ * @param targetAgentId - ID of the agent being viewed
3024
+ * @param context - Hierarchy and scope context
3025
+ * @param config - System permission configuration
3026
+ * @returns true if viewer can see target
3027
+ */
3028
+ declare function canAgentSeeAgent(viewerAgent: Agent, targetAgentId: AgentId, context: {
3029
+ isParent?: boolean;
3030
+ isChild?: boolean;
3031
+ isAncestor?: boolean;
3032
+ isDescendant?: boolean;
3033
+ sharedScopes?: ScopeId[];
3034
+ }, config?: AgentPermissionConfig): boolean;
3035
+ /**
3036
+ * Check if an agent can message another agent based on permissions.
3037
+ *
3038
+ * @param senderAgent - The agent sending the message
3039
+ * @param targetAgentId - ID of the target agent
3040
+ * @param context - Hierarchy and scope context
3041
+ * @param config - System permission configuration
3042
+ * @returns true if sender can message target
3043
+ */
3044
+ declare function canAgentMessageAgent(senderAgent: Agent, targetAgentId: AgentId, context: {
3045
+ isParent?: boolean;
3046
+ isChild?: boolean;
3047
+ isAncestor?: boolean;
3048
+ isDescendant?: boolean;
3049
+ sharedScopes?: ScopeId[];
3050
+ }, config?: AgentPermissionConfig): boolean;
3051
+
3052
+ export { type AgentMessagingRule as $, type AgentId as A, type BaseConnectionOptions as B, type ConnectResponseResult as C, type DisconnectResponseResult as D, type ErrorCategory as E, type FederationBufferConfig as F, type ScopesJoinResponseResult as G, type ScopesLeaveResponseResult as H, type ScopesListResponseResult as I, type MessageId as J, type SendResponseResult as K, type SubscriptionId as L, type MAPError as M, type SubscribeResponseResult as N, AGENT_ERROR_CODES as O, type ParticipantCapabilities as P, AUTH_ERROR_CODES as Q, type RequestId as R, type Stream as S, AUTH_METHODS as T, type UnsubscribeResponseResult as U, type AcceptanceContext as V, type AgentAcceptanceRule as W, AgentConnection as X, type AgentConnectionOptions as Y, type AgentIncludeOptions as Z, type AgentLifecycle as _, type MAPErrorData as a, type FederationAuth as a$, type AgentPermissionConfig as a0, type AgentPermissions as a1, type AgentReconnectionEventHandler as a2, type AgentReconnectionEventType as a3, type AgentReconnectionOptions as a4, type AgentRelationship as a5, type AgentRelationshipType as a6, type AgentState as a7, type AgentVisibility as a8, type AgentVisibilityRule as a9, type AuthRefreshRequestParams as aA, type AuthRefreshResponseResult as aB, BaseConnection as aC, type BroadcastAddress as aD, CAPABILITY_REQUIREMENTS as aE, CORE_METHODS as aF, type ClientAcceptanceRule as aG, ClientConnection as aH, type ClientConnectionOptions as aI, type ConnectRequest as aJ, type ConnectRequestParams as aK, type CorrelationId as aL, DEFAULT_AGENT_PERMISSION_CONFIG as aM, type DeliverySemantics as aN, type DirectAddress as aO, type DisconnectPolicy as aP, type DisconnectRequest as aQ, type DisconnectRequestParams as aR, ERROR_CODES as aS, EVENT_TYPES as aT, EXTENSION_METHODS as aU, type EventInput as aV, type EventNotification as aW, type EventNotificationParams as aX, FEDERATION_ERROR_CODES as aY, FEDERATION_METHODS as aZ, type FederatedAddress as a_, type AgentsGetRequest as aa, type AgentsGetRequestParams as ab, type AgentsListFilter as ac, type AgentsListRequest as ad, type AgentsListRequestParams as ae, type AgentsRegisterRequest as af, type AgentsRegisterRequestParams as ag, type AgentsResumeRequest as ah, type AgentsResumeRequestParams as ai, type AgentsResumeResponseResult as aj, type AgentsSpawnRequest as ak, type AgentsSpawnRequestParams as al, type AgentsStopRequest as am, type AgentsStopRequestParams as an, type AgentsStopResponseResult as ao, type AgentsSuspendRequest as ap, type AgentsSuspendRequestParams as aq, type AgentsSuspendResponseResult as ar, type AgentsUnregisterRequest as as, type AgentsUnregisterRequestParams as at, type AgentsUpdateRequest as au, type AgentsUpdateRequestParams as av, type AnyMessage as aw, type AuthMethod as ax, type AuthParams as ay, type AuthRefreshRequest as az, type FederationEnvelope as b, type ReconnectionEventType as b$, type FederationConnectRequest as b0, type FederationConnectRequestParams as b1, type FederationMetadata as b2, type FederationReplayConfig as b3, type FederationRouteRequest as b4, type FederationRouteRequestParams as b5, type GatewayReconnectionEvent as b6, type GatewayReconnectionEventHandler as b7, type GatewayReconnectionEventType as b8, type GatewayReconnectionOptions as b9, type MessageSentEventData as bA, type MessageVisibility as bB, type Meta as bC, type MultiAddress as bD, NOTIFICATION_METHODS as bE, type NotificationHandler as bF, OBSERVATION_METHODS as bG, type OverflowHandler as bH, type OverflowInfo as bI, PERMISSION_METHODS as bJ, PROTOCOL_ERROR_CODES as bK, PROTOCOL_VERSION as bL, type Participant as bM, type ParticipantAddress as bN, type PermissionAction as bO, type PermissionContext as bP, type PermissionParticipant as bQ, type PermissionResult as bR, type PermissionSystemConfig as bS, type PermissionsAgentUpdatedEventData as bT, type PermissionsClientUpdatedEventData as bU, type PermissionsUpdateRequest as bV, type PermissionsUpdateRequestParams as bW, type PermissionsUpdateResponseResult as bX, RESOURCE_ERROR_CODES as bY, ROUTING_ERROR_CODES as bZ, type ReconnectionEventHandler as b_, type GraphEdge as ba, type HierarchicalAddress as bb, type InjectDelivery as bc, type InjectDeliveryResult as bd, type InjectRequest as be, type InjectRequestParams as bf, type InjectResponseResult as bg, JSONRPC_VERSION as bh, type JoinPolicy as bi, LIFECYCLE_METHODS as bj, type MAPNotification as bk, type MAPNotificationBase as bl, type MAPRequest as bm, type MAPRequestBase as bn, type MAPResponse as bo, type MAPResponseError as bp, type MAPResponseSuccess as bq, MAP_METHODS as br, type MessageDeliveredEventData as bs, type MessageFailedEventData as bt, type MessageHandler as bu, type MessageMeta as bv, type MessageNotification as bw, type MessageNotificationParams as bx, type MessagePriority as by, type MessageRelationship as bz, type Message as c, type UnsubscribeRequestParams as c$, type ReconnectionOptions as c0, type ReplayRequest as c1, type ReplayRequestParams as c2, type ReplayResponseResult as c3, type ReplayedEvent as c4, type RequestHandler as c5, type RoleAddress as c6, SCOPE_METHODS as c7, SESSION_METHODS as c8, STATE_METHODS as c9, type SessionCloseRequest as cA, type SessionCloseRequestParams as cB, type SessionCloseResponseResult as cC, type SessionListRequest as cD, type SessionListRequestParams as cE, type SessionListResponseResult as cF, type SessionLoadRequest as cG, type SessionLoadRequestParams as cH, type SessionLoadResponseResult as cI, type StateChangeHandler as cJ, type StreamingCapabilities as cK, type StructureGraphRequest as cL, type StructureGraphRequestParams as cM, type StructureGraphResponseResult as cN, type StructureVisibilityRule as cO, type SubscribeRequest as cP, type SubscribeRequestParams as cQ, Subscription as cR, type SubscriptionAckNotification as cS, type SubscriptionAckParams as cT, type SubscriptionOptions$1 as cU, type SubscriptionState as cV, type SystemAcceptanceRule as cW, type SystemAddress as cX, type Timestamp as cY, type TransportType as cZ, type UnsubscribeRequest as c_, STEERING_METHODS as ca, STRUCTURE_METHODS as cb, type ScopeAddress as cc, type ScopeMessagingRule as cd, type ScopeVisibility as ce, type ScopeVisibilityRule as cf, type ScopesCreateRequest as cg, type ScopesCreateRequestParams as ch, type ScopesDeleteRequest as ci, type ScopesDeleteRequestParams as cj, type ScopesDeleteResponseResult as ck, type ScopesGetRequest as cl, type ScopesGetRequestParams as cm, type ScopesGetResponseResult as cn, type ScopesJoinRequest as co, type ScopesJoinRequestParams as cp, type ScopesLeaveRequest as cq, type ScopesLeaveRequestParams as cr, type ScopesListRequest as cs, type ScopesListRequestParams as ct, type ScopesMembersRequest as cu, type ScopesMembersRequestParams as cv, type ScopesMembersResponseResult as cw, type SendPolicy as cx, type SendRequest as cy, type SendRequestParams as cz, type FederationRoutingConfig as d, canAgentAcceptMessage as d0, canAgentMessageAgent as d1, canAgentSeeAgent as d2, canControlAgent as d3, canJoinScope as d4, canMessageAgent as d5, canPerformAction as d6, canPerformMethod as d7, canSeeAgent as d8, canSeeScope as d9, canSendToScope as da, createEvent as db, createStreamPair as dc, createSubscription as dd, deepMergePermissions as de, filterVisibleAgents as df, filterVisibleEvents as dg, filterVisibleScopes as dh, hasCapability as di, isAgentExposed as dj, isBroadcastAddress as dk, isDirectAddress as dl, isEventTypeExposed as dm, isFederatedAddress as dn, isHierarchicalAddress as dp, isOrphanedAgent as dq, isScopeAddress as dr, isScopeExposed as ds, isSuccessResponse as dt, mapVisibilityToRule as du, ndJsonStream as dv, resolveAgentPermissions as dw, websocketStream as dx, type SystemExposure as dy, type EventType as e, type SessionId as f, type FederationConnectResponseResult as g, type FederationRouteResponseResult as h, type ConnectionState as i, type ParticipantId as j, type ParticipantType as k, type ScopeId as l, type Agent as m, type Scope as n, type Address as o, type SubscriptionFilter as p, type Event as q, type AgentsGetResponseResult as r, type AgentsListResponseResult as s, type AgentsRegisterResponseResult as t, type AgentsSpawnResponseResult as u, type AgentsUnregisterResponseResult as v, type AgentsUpdateResponseResult as w, type ProtocolVersion as x, type SessionInfo as y, type ScopesCreateResponseResult as z };