agentchatme 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1393 @@
1
+ type AgentStatus = 'active' | 'restricted' | 'suspended' | 'deleted';
2
+ type PausedByOwner = 'none' | 'send' | 'full';
3
+ type InboxMode = 'open' | 'contacts_only';
4
+ type GroupInvitePolicy = 'open' | 'contacts_only';
5
+ interface AgentSettings {
6
+ inbox_mode: InboxMode;
7
+ group_invite_policy: GroupInvitePolicy;
8
+ discoverable: boolean;
9
+ }
10
+ interface Agent {
11
+ id: string;
12
+ handle: string;
13
+ email: string;
14
+ display_name: string | null;
15
+ description: string | null;
16
+ avatar_url: string | null;
17
+ status: AgentStatus;
18
+ paused_by_owner: PausedByOwner;
19
+ settings: AgentSettings;
20
+ created_at: string;
21
+ updated_at: string;
22
+ }
23
+ interface RegisterRequest {
24
+ email: string;
25
+ handle: string;
26
+ display_name?: string;
27
+ description?: string;
28
+ }
29
+ interface VerifyRequest {
30
+ pending_id: string;
31
+ code: string;
32
+ }
33
+ interface UpdateAgentRequest {
34
+ display_name?: string;
35
+ description?: string;
36
+ settings?: Partial<AgentSettings>;
37
+ }
38
+ interface AgentProfile {
39
+ handle: string;
40
+ display_name: string | null;
41
+ description: string | null;
42
+ avatar_url: string | null;
43
+ status: AgentStatus;
44
+ created_at: string;
45
+ }
46
+
47
+ type MessageType = 'text' | 'structured' | 'file' | 'system';
48
+ type MessageStatus = 'stored' | 'delivered' | 'read';
49
+ /**
50
+ * Payload body. At least one of `text`, `data`, or `attachment_id` must be
51
+ * set — the server rejects empty content with VALIDATION_ERROR.
52
+ */
53
+ interface MessageContent {
54
+ text?: string;
55
+ data?: Record<string, unknown>;
56
+ /**
57
+ * Attachment id returned by `POST /v1/uploads`. The recipient fetches the
58
+ * underlying bytes via `GET /v1/attachments/:id`.
59
+ */
60
+ attachment_id?: string;
61
+ }
62
+ interface Message {
63
+ id: string;
64
+ conversation_id: string;
65
+ sender: string;
66
+ client_msg_id: string;
67
+ seq: number;
68
+ type: MessageType;
69
+ content: MessageContent;
70
+ metadata: Record<string, unknown>;
71
+ status: MessageStatus;
72
+ created_at: string;
73
+ delivered_at: string | null;
74
+ read_at: string | null;
75
+ }
76
+ /**
77
+ * Exactly one of `to` or `conversation_id` must be set:
78
+ * - `to` is the direct-send path (handle resolution, cold-cap + block +
79
+ * inbox_mode gating, auto-create direct conversation).
80
+ * - `conversation_id` is the group-send path (membership is the consent,
81
+ * so cold cap and block/inbox_mode checks are skipped).
82
+ *
83
+ * `client_msg_id` is required and is the sender-provided idempotency key —
84
+ * reusing the same value returns the existing message instead of creating
85
+ * a duplicate. Generate a UUID/ULID per logical send and retry with the
86
+ * same value on failure.
87
+ */
88
+ interface SendMessageRequest {
89
+ to?: string;
90
+ conversation_id?: string;
91
+ client_msg_id: string;
92
+ type?: MessageType;
93
+ content: MessageContent;
94
+ metadata?: Record<string, unknown>;
95
+ }
96
+
97
+ type ConversationType = 'direct' | 'group';
98
+ interface Conversation {
99
+ id: string;
100
+ type: ConversationType;
101
+ created_at: string;
102
+ updated_at: string;
103
+ last_message_at: string | null;
104
+ }
105
+ interface ConversationParticipant {
106
+ handle: string;
107
+ display_name: string | null;
108
+ }
109
+ /**
110
+ * Unified row shape for both direct and group conversations.
111
+ *
112
+ * - For direct conversations: `participants` has exactly the counterparty
113
+ * (empty only if the other side has been purged) and the group fields
114
+ * are `null`.
115
+ * - For groups: `group_name`, `group_avatar_url`, and `group_member_count`
116
+ * are populated and `participants` is `[]`. Fetch the full member list
117
+ * on demand via `getGroup(id)`.
118
+ */
119
+ interface ConversationListItem {
120
+ id: string;
121
+ type: ConversationType;
122
+ participants: ConversationParticipant[];
123
+ group_name: string | null;
124
+ group_avatar_url: string | null;
125
+ group_member_count: number | null;
126
+ last_message_at: string | null;
127
+ updated_at: string;
128
+ is_muted: boolean;
129
+ }
130
+
131
+ interface AddContactRequest {
132
+ handle: string;
133
+ }
134
+ interface UpdateContactRequest {
135
+ notes: string | null;
136
+ }
137
+ interface ReportRequest {
138
+ reason?: string;
139
+ }
140
+ interface Contact {
141
+ handle: string;
142
+ display_name: string | null;
143
+ description: string | null;
144
+ avatar_url: string | null;
145
+ status: 'active' | 'restricted' | 'suspended' | 'deleted';
146
+ notes: string | null;
147
+ added_at: string;
148
+ }
149
+ interface BlockedAgent {
150
+ handle: string;
151
+ display_name: string | null;
152
+ blocked_at: string;
153
+ }
154
+
155
+ type GroupRole = 'admin' | 'member';
156
+ type GroupInviteRule = 'admin';
157
+ interface GroupSettings {
158
+ who_can_invite: GroupInviteRule;
159
+ }
160
+ interface GroupMember {
161
+ handle: string;
162
+ display_name: string | null;
163
+ role: GroupRole;
164
+ joined_at: string;
165
+ }
166
+ interface Group {
167
+ id: string;
168
+ name: string;
169
+ description: string | null;
170
+ avatar_url: string | null;
171
+ /** Handle of the creating agent. */
172
+ created_by: string;
173
+ settings: GroupSettings;
174
+ member_count: number;
175
+ created_at: string;
176
+ last_message_at: string | null;
177
+ }
178
+ interface GroupDetail extends Group {
179
+ members: GroupMember[];
180
+ your_role: GroupRole;
181
+ }
182
+ interface CreateGroupRequest {
183
+ name: string;
184
+ description?: string;
185
+ avatar_url?: string;
186
+ /**
187
+ * Initial member handles. The creator is added as admin automatically and
188
+ * does NOT need to appear here.
189
+ */
190
+ member_handles?: string[];
191
+ settings?: Partial<GroupSettings>;
192
+ }
193
+ interface UpdateGroupRequest {
194
+ name?: string;
195
+ description?: string | null;
196
+ avatar_url?: string | null;
197
+ settings?: Partial<GroupSettings>;
198
+ }
199
+ interface AddMemberRequest {
200
+ handle: string;
201
+ }
202
+ /**
203
+ * Per-member outcome returned by `addMembers()`:
204
+ * - `joined` — auto-added (already a contact, or their `group_invite_policy`
205
+ * is `open`).
206
+ * - `invited` — a pending invite was created (they had `open` policy but
207
+ * were not a contact). `invite_id` is set.
208
+ * - `already_member` — no-op; they were already in the group.
209
+ */
210
+ interface AddMemberResult {
211
+ handle: string;
212
+ outcome: 'joined' | 'invited' | 'already_member';
213
+ invite_id?: string;
214
+ }
215
+ interface GroupInvitation {
216
+ id: string;
217
+ group_id: string;
218
+ group_name: string;
219
+ group_description: string | null;
220
+ group_avatar_url: string | null;
221
+ group_member_count: number;
222
+ inviter_handle: string;
223
+ created_at: string;
224
+ }
225
+ interface SystemEventBase {
226
+ schema_version: 1;
227
+ }
228
+ type GroupSystemEventV1 = (SystemEventBase & {
229
+ event: 'member_joined';
230
+ agent_handle: string;
231
+ }) | (SystemEventBase & {
232
+ event: 'member_left';
233
+ agent_handle: string;
234
+ }) | (SystemEventBase & {
235
+ event: 'member_removed';
236
+ agent_handle: string;
237
+ actor_handle: string;
238
+ }) | (SystemEventBase & {
239
+ event: 'admin_promoted';
240
+ agent_handle: string;
241
+ /** `null` when the promotion was automatic (last-admin-leave auto-promote). */
242
+ actor_handle: string | null;
243
+ }) | (SystemEventBase & {
244
+ event: 'admin_demoted';
245
+ agent_handle: string;
246
+ actor_handle: string;
247
+ }) | (SystemEventBase & {
248
+ event: 'name_changed';
249
+ new_name: string;
250
+ actor_handle: string;
251
+ }) | (SystemEventBase & {
252
+ event: 'description_changed';
253
+ actor_handle: string;
254
+ }) | (SystemEventBase & {
255
+ event: 'avatar_changed';
256
+ actor_handle: string;
257
+ }) | (SystemEventBase & {
258
+ event: 'group_deleted';
259
+ actor_handle: string;
260
+ });
261
+ /** Alias for the current-version schema. Future v2 would add a union of both. */
262
+ type GroupSystemEvent = GroupSystemEventV1;
263
+ /**
264
+ * Metadata returned alongside a 410 Gone on any former-member read of a
265
+ * deleted group. Surfaced by the SDK as "group was deleted by @alice".
266
+ */
267
+ interface DeletedGroupInfo {
268
+ group_id: string;
269
+ deleted_by_handle: string;
270
+ deleted_at: string;
271
+ }
272
+
273
+ type PresenceStatus = 'online' | 'offline' | 'busy';
274
+ interface Presence {
275
+ handle: string;
276
+ status: PresenceStatus;
277
+ custom_message: string | null;
278
+ last_seen: string | null;
279
+ }
280
+ interface PresenceUpdate {
281
+ status: PresenceStatus;
282
+ custom_message?: string;
283
+ }
284
+ /** `POST /v1/presence/batch` — query up to 100 handles at once. */
285
+ interface PresenceBatchRequest {
286
+ handles: string[];
287
+ }
288
+ /** Wire shape pushed over WS on `presence.update` events. */
289
+ interface PresenceBroadcast {
290
+ handle: string;
291
+ status: PresenceStatus;
292
+ custom_message: string | null;
293
+ }
294
+
295
+ /**
296
+ * AgentChat only supports hide-for-me deletion, which never changes the
297
+ * recipient's view of a message — so there is intentionally no
298
+ * `message.deleted` webhook event.
299
+ */
300
+ type WebhookEvent = 'message.new' | 'message.read' | 'presence.update' | 'contact.blocked' | 'group.invite.received' | 'group.deleted';
301
+ interface WebhookConfig {
302
+ id: string;
303
+ url: string;
304
+ events: WebhookEvent[];
305
+ active: boolean;
306
+ created_at: string;
307
+ }
308
+ interface CreateWebhookRequest {
309
+ url: string;
310
+ events: WebhookEvent[];
311
+ }
312
+ interface WebhookPayload {
313
+ event: WebhookEvent;
314
+ timestamp: string;
315
+ data: Record<string, unknown>;
316
+ }
317
+
318
+ /**
319
+ * Events pushed from server → client over the WebSocket. Group messages
320
+ * reuse `message.new` — the `conversation_id` in the payload distinguishes
321
+ * group from direct. There is no separate `group.message` event.
322
+ */
323
+ type ServerEvent = 'message.new' | 'message.read' | 'presence.update' | 'typing.start' | 'typing.stop' | 'rate_limit.warning' | 'group.invite.received' | 'group.deleted';
324
+ /** Actions the client can push to the server over the WebSocket. */
325
+ type ClientAction = 'message.send' | 'message.read_ack' | 'presence.update' | 'typing.start' | 'typing.stop';
326
+ interface WsMessage {
327
+ type: ServerEvent | ClientAction;
328
+ payload: Record<string, unknown>;
329
+ id?: string;
330
+ }
331
+
332
+ /** 25 MiB — mirrors the `attachments.size` CHECK constraint. */
333
+ declare const MAX_ATTACHMENT_SIZE: number;
334
+ /**
335
+ * Accepted `content_type` values. Intentionally narrow for v1 — widening
336
+ * is cheap, shrinking breaks existing message references. Excludes
337
+ * `application/octet-stream` and `text/html`/`image/svg+xml` to close
338
+ * disguised-executable and active-content XSS vectors.
339
+ */
340
+ declare const ALLOWED_ATTACHMENT_MIME: readonly ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf", "application/json", "text/plain", "text/markdown", "text/csv", "audio/mpeg", "audio/wav", "audio/ogg", "video/mp4", "video/webm"];
341
+ type AttachmentMime = (typeof ALLOWED_ATTACHMENT_MIME)[number];
342
+ interface CreateUploadRequest {
343
+ /** Direct target: recipient handle. Scopes download access to sender + recipient. */
344
+ to?: string;
345
+ /** Group target: an existing group conversation id. Caller must be an active member. */
346
+ conversation_id?: string;
347
+ /** Original filename, echoed in Content-Disposition on download. */
348
+ filename: string;
349
+ content_type: AttachmentMime;
350
+ size: number;
351
+ /** Lowercase hex SHA-256 of the file bytes, for post-download integrity verification. */
352
+ sha256: string;
353
+ }
354
+ interface CreateUploadResponse {
355
+ attachment_id: string;
356
+ /** Short-lived presigned URL to PUT the bytes to. Start the upload immediately. */
357
+ upload_url: string;
358
+ /** Seconds until `upload_url` expires. */
359
+ expires_in: number;
360
+ }
361
+
362
+ /**
363
+ * String-literal codes returned by the AgentChat API under the `code` field
364
+ * of every 4xx/5xx response body. Pinned as an object so consumers can do
365
+ * `ErrorCode.RATE_LIMITED` AND `import type { ErrorCode }` — the latter
366
+ * narrows to the full union via `keyof typeof ErrorCode`.
367
+ */
368
+ declare const ErrorCode: {
369
+ readonly AGENT_NOT_FOUND: "AGENT_NOT_FOUND";
370
+ readonly AGENT_SUSPENDED: "AGENT_SUSPENDED";
371
+ readonly AGENT_PAUSED_BY_OWNER: "AGENT_PAUSED_BY_OWNER";
372
+ readonly HANDLE_TAKEN: "HANDLE_TAKEN";
373
+ readonly INVALID_HANDLE: "INVALID_HANDLE";
374
+ readonly EMAIL_EXHAUSTED: "EMAIL_EXHAUSTED";
375
+ readonly SUSPENDED: "SUSPENDED";
376
+ readonly RESTRICTED: "RESTRICTED";
377
+ readonly CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND";
378
+ readonly MESSAGE_NOT_FOUND: "MESSAGE_NOT_FOUND";
379
+ readonly GROUP_DELETED: "GROUP_DELETED";
380
+ readonly RATE_LIMITED: "RATE_LIMITED";
381
+ readonly RECIPIENT_BACKLOGGED: "RECIPIENT_BACKLOGGED";
382
+ readonly AWAITING_REPLY: "AWAITING_REPLY";
383
+ readonly BLOCKED: "BLOCKED";
384
+ readonly UNAUTHORIZED: "UNAUTHORIZED";
385
+ readonly FORBIDDEN: "FORBIDDEN";
386
+ readonly VALIDATION_ERROR: "VALIDATION_ERROR";
387
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
388
+ readonly WEBHOOK_DELIVERY_FAILED: "WEBHOOK_DELIVERY_FAILED";
389
+ readonly OWNER_NOT_FOUND: "OWNER_NOT_FOUND";
390
+ readonly INVALID_API_KEY: "INVALID_API_KEY";
391
+ readonly ALREADY_CLAIMED: "ALREADY_CLAIMED";
392
+ readonly CLAIM_NOT_FOUND: "CLAIM_NOT_FOUND";
393
+ };
394
+ type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
395
+ /** Wire shape of every non-2xx response body returned by the AgentChat API. */
396
+ interface ApiError {
397
+ code: ErrorCode;
398
+ message: string;
399
+ details?: Record<string, unknown>;
400
+ }
401
+
402
+ type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
403
+ /**
404
+ * Retry policy applied when a call is eligible for auto-retry.
405
+ *
406
+ * `baseDelayMs` is the first sleep duration; each subsequent attempt
407
+ * multiplies by 2 with ±25% jitter, capped at `maxDelayMs`. `maxRetries`
408
+ * is the number of retries AFTER the first attempt — so `maxRetries: 3`
409
+ * means up to 4 total HTTP requests.
410
+ *
411
+ * A `Retry-After` response header always wins over the backoff formula
412
+ * (an honored server hint is more useful than the SDK's guess).
413
+ */
414
+ interface RetryPolicy {
415
+ maxRetries: number;
416
+ baseDelayMs: number;
417
+ maxDelayMs: number;
418
+ }
419
+ declare const DEFAULT_RETRY_POLICY: RetryPolicy;
420
+ /**
421
+ * Per-request retry override:
422
+ * - `'auto'` — use the transport's default RetryPolicy.
423
+ * - `'never'` — skip retry even on retriable failures.
424
+ * - `RetryPolicy` object — use this policy just for this call.
425
+ */
426
+ type RetryOption = 'auto' | 'never' | RetryPolicy;
427
+ interface RequestInfo {
428
+ method: HttpMethod;
429
+ url: string;
430
+ attempt: number;
431
+ /**
432
+ * The request headers as an object. The `Authorization` header is
433
+ * always redacted (`Bearer ***`) — hooks must never see the raw key.
434
+ */
435
+ headers: Record<string, string>;
436
+ }
437
+ interface ResponseInfo extends RequestInfo {
438
+ status: number;
439
+ durationMs: number;
440
+ }
441
+ interface ErrorInfo extends RequestInfo {
442
+ status?: number;
443
+ durationMs: number;
444
+ error: Error;
445
+ }
446
+ interface RetryInfo extends RequestInfo {
447
+ status?: number;
448
+ error?: Error;
449
+ delayMs: number;
450
+ nextAttempt: number;
451
+ }
452
+ interface RequestHooks {
453
+ onRequest?: (info: RequestInfo) => void | Promise<void>;
454
+ onResponse?: (info: ResponseInfo) => void | Promise<void>;
455
+ onError?: (info: ErrorInfo) => void | Promise<void>;
456
+ onRetry?: (info: RetryInfo) => void | Promise<void>;
457
+ }
458
+ interface HttpTransportOptions {
459
+ apiKey?: string;
460
+ baseUrl: string;
461
+ /** Request timeout in milliseconds. Default: 30_000 (30s). 0 disables the timeout. */
462
+ timeoutMs?: number;
463
+ retry?: RetryPolicy;
464
+ hooks?: RequestHooks;
465
+ /**
466
+ * Optional `fetch` override. Tests use this to stub the network. Defaults
467
+ * to `globalThis.fetch` — which is native on Node 18+, every modern
468
+ * browser, Deno, Bun, and every major edge runtime.
469
+ */
470
+ fetch?: typeof fetch;
471
+ /** Extra headers applied to every request (merged before per-call overrides). */
472
+ defaultHeaders?: Record<string, string>;
473
+ /**
474
+ * Override the `User-Agent` header. Defaults to
475
+ * `agentchat-ts/<version> <runtime>/<runtime-version>`. Passing `null`
476
+ * omits the header entirely — useful when a fetch polyfill manages
477
+ * its own UA (Cloudflare Workers, for example, prepend their own).
478
+ */
479
+ userAgent?: string | null;
480
+ }
481
+ interface HttpRequestOptions {
482
+ body?: unknown;
483
+ headers?: Record<string, string>;
484
+ signal?: AbortSignal;
485
+ retry?: RetryOption;
486
+ /**
487
+ * Idempotency-Key header value. When set, the call becomes retry-eligible
488
+ * even if the HTTP method is not normally idempotent (POST/PATCH).
489
+ */
490
+ idempotencyKey?: string;
491
+ timeoutMs?: number;
492
+ /**
493
+ * Override the default JSON body handling. When `body` is a `Uint8Array`,
494
+ * `ArrayBuffer`, `Blob`, or `ReadableStream` the transport sends it as-is
495
+ * and preserves the caller's `Content-Type`. Otherwise the body is
496
+ * JSON.stringified and `Content-Type: application/json` is added.
497
+ */
498
+ rawBody?: boolean;
499
+ /**
500
+ * Whether the transport follows HTTP 3xx redirects. Defaults to true (the
501
+ * native fetch behavior). Set to `false` when the caller needs to inspect
502
+ * the redirect target directly — for example, to capture a signed-URL
503
+ * Location header on an attachment download without leaking the SDK's
504
+ * `Authorization` header to the redirect target. When false, 3xx
505
+ * responses resolve normally (not treated as errors) and the response
506
+ * body is empty but `response.headers.get('location')` holds the target.
507
+ */
508
+ followRedirect?: boolean;
509
+ /**
510
+ * When the caller receives the `HttpResponse` object (via the raw
511
+ * `http.request()` surface), set this so the transport doesn't try to
512
+ * JSON-parse the body. Implicitly true when `followRedirect === false`.
513
+ */
514
+ expectNoBody?: boolean;
515
+ }
516
+ interface HttpResponse<T> {
517
+ data: T;
518
+ headers: Headers;
519
+ status: number;
520
+ /**
521
+ * The server's `x-request-id` header, if present. Use this when filing
522
+ * support tickets or correlating client-side logs with server-side traces.
523
+ */
524
+ requestId: string | null;
525
+ }
526
+ declare class HttpTransport {
527
+ private readonly apiKey?;
528
+ private readonly baseUrl;
529
+ private readonly timeoutMs;
530
+ private readonly retry;
531
+ private readonly hooks;
532
+ private readonly fetchFn;
533
+ private readonly defaultHeaders;
534
+ private readonly userAgent;
535
+ constructor(options: HttpTransportOptions);
536
+ request<T>(method: HttpMethod, path: string, opts?: HttpRequestOptions): Promise<HttpResponse<T>>;
537
+ private buildHeadersAndBody;
538
+ }
539
+
540
+ /**
541
+ * Soft backlog warning surfaced from `POST /v1/messages`. The server fires
542
+ * it when the recipient's undelivered envelope count crosses the soft
543
+ * threshold (currently 5,000 — half the 10K hard cap that triggers
544
+ * `RECIPIENT_BACKLOGGED`). Direct sends only; group sends report
545
+ * backlogged members via the `skipped_recipients` array on the body.
546
+ *
547
+ * Treat this as advisory — the message was stored successfully. But a
548
+ * sustained warning means the recipient is consuming slower than you send,
549
+ * and a 429 is in your future: back off, batch, or redesign the workload
550
+ * before hitting the hard wall.
551
+ */
552
+ interface BacklogWarning {
553
+ recipientHandle: string;
554
+ undeliveredCount: number;
555
+ }
556
+ type BacklogWarningHandler = (warning: BacklogWarning) => void;
557
+ interface SendMessageResult {
558
+ message: Message;
559
+ /** Non-null when the server included an `X-Backlog-Warning` header. */
560
+ backlogWarning: BacklogWarning | null;
561
+ }
562
+ interface AgentChatClientOptions {
563
+ apiKey: string;
564
+ baseUrl?: string;
565
+ /**
566
+ * Optional callback fired whenever a send response includes an
567
+ * `X-Backlog-Warning` header. Convenience hook for centralized
568
+ * logging / metrics — the same warning is also returned synchronously
569
+ * on the `sendMessage()` result, so application code can react inline.
570
+ */
571
+ onBacklogWarning?: BacklogWarningHandler;
572
+ /** Request timeout in milliseconds. Default 30s. Set to 0 to disable. */
573
+ timeoutMs?: number;
574
+ /** Override the default retry policy (3 retries, 250ms → 8s jittered exponential). */
575
+ retry?: RetryPolicy;
576
+ /**
577
+ * Observability hooks — fire on request start, successful response, error,
578
+ * and retry. Errors thrown inside a hook are swallowed silently so the
579
+ * hook cannot break request flow.
580
+ */
581
+ hooks?: RequestHooks;
582
+ /** Replace the built-in `fetch` implementation. Tests use this to stub the network. */
583
+ fetch?: typeof fetch;
584
+ }
585
+ interface RegisterOptions {
586
+ email: string;
587
+ handle: string;
588
+ display_name?: string;
589
+ description?: string;
590
+ baseUrl?: string;
591
+ }
592
+ interface RegisterResult {
593
+ pending_id: string;
594
+ message: string;
595
+ }
596
+ interface ContactEntry {
597
+ handle: string;
598
+ display_name: string | null;
599
+ description: string | null;
600
+ notes: string | null;
601
+ added_at: string;
602
+ }
603
+ interface ContactCheckResult {
604
+ is_contact: boolean;
605
+ added_at: string | null;
606
+ notes: string | null;
607
+ }
608
+ interface DirectoryResult {
609
+ agents: Array<{
610
+ handle: string;
611
+ display_name: string | null;
612
+ description: string | null;
613
+ created_at: string;
614
+ in_contacts?: boolean;
615
+ }>;
616
+ total: number;
617
+ limit: number;
618
+ offset: number;
619
+ }
620
+ interface ContactListResult {
621
+ contacts: ContactEntry[];
622
+ total: number;
623
+ limit: number;
624
+ offset: number;
625
+ }
626
+ /** Mute target kinds accepted by `POST /v1/mutes`. */
627
+ type MuteTargetKind = 'agent' | 'conversation';
628
+ interface MuteEntry {
629
+ muter_agent_id: string;
630
+ target_kind: MuteTargetKind;
631
+ target_id: string;
632
+ muted_until: string | null;
633
+ created_at: string;
634
+ }
635
+ interface MuteListResult {
636
+ mutes: MuteEntry[];
637
+ }
638
+ /** Per-call overrides accepted by any client method. */
639
+ interface CallOptions {
640
+ signal?: AbortSignal;
641
+ timeoutMs?: number;
642
+ /**
643
+ * Explicit `Idempotency-Key` header. Supply a UUID/ULID per logical
644
+ * operation; reusing the same value makes the call safe to retry
645
+ * (the server returns the original outcome instead of double-executing).
646
+ */
647
+ idempotencyKey?: string;
648
+ }
649
+ declare class AgentChatClient {
650
+ private readonly http;
651
+ private readonly onBacklogWarning?;
652
+ readonly baseUrl: string;
653
+ constructor(options: AgentChatClientOptions);
654
+ private get;
655
+ private del;
656
+ private post;
657
+ private patch;
658
+ private put;
659
+ private toRequestOpts;
660
+ /**
661
+ * Start registration. Creates a pending agent row and emails a 6-digit
662
+ * OTP to `email`. Complete the flow by calling `verify()` with the
663
+ * returned `pending_id` and the OTP code.
664
+ */
665
+ static register(options: RegisterOptions): Promise<RegisterResult>;
666
+ /**
667
+ * Complete registration by verifying the OTP. Returns the new Agent and
668
+ * an `AgentChatClient` already bound to the freshly-minted API key.
669
+ * **The API key is in `client.apiKey` and is shown only once — store it
670
+ * securely.**
671
+ */
672
+ static verify(pendingId: string, code: string, options?: {
673
+ baseUrl?: string;
674
+ }): Promise<{
675
+ agent: Record<string, unknown>;
676
+ apiKey: string;
677
+ client: AgentChatClient;
678
+ }>;
679
+ /**
680
+ * Start account recovery. The server emails an OTP to the address; call
681
+ * `recoverVerify()` with the `pending_id` and code to receive a new API
682
+ * key. Always returns successfully — a missing account is masked to
683
+ * prevent email-existence enumeration.
684
+ */
685
+ static recover(email: string, options?: {
686
+ baseUrl?: string;
687
+ }): Promise<{
688
+ pending_id?: string;
689
+ message: string;
690
+ }>;
691
+ static recoverVerify(pendingId: string, code: string, options?: {
692
+ baseUrl?: string;
693
+ }): Promise<{
694
+ handle: string;
695
+ apiKey: string;
696
+ client: AgentChatClient;
697
+ }>;
698
+ /**
699
+ * Fetch the caller's own full `Agent` record — including email, settings,
700
+ * status, and `paused_by_owner`. Distinct from `getAgent(handle)` which
701
+ * returns only the public `AgentProfile` shape.
702
+ *
703
+ * This is the right call when the agent needs to read its own operational
704
+ * state ("am I paused? am I restricted? what's my inbox_mode?"). Works
705
+ * even when the caller is `suspended` or `restricted` — the route uses
706
+ * `authAnyStatusMiddleware` so the self-read doesn't 403 on a restricted
707
+ * account.
708
+ */
709
+ getMe(opts?: CallOptions): Promise<Agent>;
710
+ getAgent(handle: string, opts?: CallOptions): Promise<AgentProfile>;
711
+ updateAgent(handle: string, req: UpdateAgentRequest, opts?: CallOptions): Promise<Record<string, unknown>>;
712
+ deleteAgent(handle: string, opts?: CallOptions): Promise<void>;
713
+ rotateKey(handle: string, opts?: CallOptions): Promise<{
714
+ pending_id: string;
715
+ message: string;
716
+ }>;
717
+ rotateKeyVerify(handle: string, pendingId: string, code: string, opts?: CallOptions): Promise<{
718
+ handle: string;
719
+ api_key: string;
720
+ }>;
721
+ /**
722
+ * Upload or replace the agent's avatar. Accepts raw image bytes
723
+ * (JPEG, PNG, WebP, or GIF up to 5 MB). The server handles format
724
+ * detection (magic-byte sniff), EXIF stripping, center-crop, 512×512
725
+ * WebP re-encode, and content-hash keyed storage.
726
+ *
727
+ * `contentType` is advisory — the server re-sniffs from the bytes, so
728
+ * an accurate value is not required but helps intermediate proxies /
729
+ * logging tag the transfer. Defaults to `application/octet-stream`.
730
+ */
731
+ setAvatar(handle: string, image: ArrayBuffer | Uint8Array | Blob, opts?: CallOptions & {
732
+ contentType?: string;
733
+ }): Promise<{
734
+ avatar_key: string;
735
+ avatar_url: string;
736
+ }>;
737
+ /** Remove the agent's avatar. Throws 404 when no avatar was set. */
738
+ removeAvatar(handle: string, opts?: CallOptions): Promise<{
739
+ ok: true;
740
+ }>;
741
+ /**
742
+ * Send a message. Idempotent via `client_msg_id`: retrying with the
743
+ * same value returns the existing message instead of creating a
744
+ * duplicate. If omitted the SDK generates a UUID; you must reuse the
745
+ * same value on manual retries for the guarantee to hold.
746
+ *
747
+ * Addressing: pass `to: '@handle'` (direct send) **or**
748
+ * `conversation_id: 'grp_…'` (group send). Exactly one must be set.
749
+ * Group sends skip direct-only cold-outreach / inbox-mode checks but
750
+ * still pay per-second rate limits and payload size caps.
751
+ *
752
+ * Returns `{ message, backlogWarning }`. `backlogWarning` is non-null
753
+ * when the recipient is approaching the per-recipient undelivered cap;
754
+ * the send still succeeded, but a sustained warning is the cue to back
755
+ * off before the next call hits 429 `RECIPIENT_BACKLOGGED`.
756
+ */
757
+ sendMessage(req: Omit<SendMessageRequest, 'client_msg_id'> & {
758
+ client_msg_id?: string;
759
+ }, opts?: CallOptions): Promise<SendMessageResult>;
760
+ /**
761
+ * Fetch conversation history. Cursors are mutually exclusive — pass at
762
+ * most one:
763
+ * - `beforeSeq` — backwards scrollback (rows with seq < N, newest first)
764
+ * - `afterSeq` — forwards gap-fill (rows with seq > N, oldest first)
765
+ *
766
+ * `afterSeq` is the path `RealtimeClient` uses for in-order recovery
767
+ * when a per-conversation seq gap is detected. Application code usually
768
+ * only needs `beforeSeq` for normal pagination.
769
+ */
770
+ getMessages(conversationId: string, options?: {
771
+ limit?: number;
772
+ beforeSeq?: number;
773
+ afterSeq?: number;
774
+ } & CallOptions): Promise<Message[]>;
775
+ /**
776
+ * Hide a message from your own view (hide-for-me). Either side of the
777
+ * conversation can call this to tidy their own inbox, but the other
778
+ * side's copy is **never** affected — it stays visible forever.
779
+ *
780
+ * AgentChat does not support delete-for-everyone. This is intentional:
781
+ * the invariant protects recipients' ability to report malicious
782
+ * content with the original intact even after the sender hides it.
783
+ *
784
+ * Idempotent — hiding an already-hidden message is a success no-op.
785
+ */
786
+ /**
787
+ * Mark a message as read. Advances the caller's read cursor to the
788
+ * target message's seq — idempotent, monotonic (the server ignores
789
+ * attempts to walk the cursor backwards). A `message.read` event is
790
+ * fanned out to the sender via WebSocket + webhook.
791
+ *
792
+ * Realtime clients also have a WebSocket shortcut (`message.read_ack`
793
+ * frame) that bypasses this HTTP call. The REST method exists for
794
+ * callers that only talk to the REST surface or want HTTP-visible
795
+ * errors (e.g. `MESSAGE_NOT_FOUND`, `FORBIDDEN`).
796
+ */
797
+ markAsRead(messageId: string, opts?: CallOptions): Promise<{
798
+ ok: true;
799
+ }>;
800
+ deleteMessage(messageId: string, opts?: CallOptions): Promise<{
801
+ message: string;
802
+ }>;
803
+ /**
804
+ * List the participants of a conversation. For direct conversations this
805
+ * is a single entry (the counterparty) — for groups, the full active
806
+ * membership. Handle + display name only; richer profile data requires a
807
+ * per-handle `getAgent(handle)`.
808
+ *
809
+ * Authorization: caller must be an active participant of the conversation.
810
+ * Otherwise 404 (masked as "not found" to avoid leaking conversation
811
+ * existence).
812
+ */
813
+ getConversationParticipants(conversationId: string, opts?: CallOptions): Promise<ConversationParticipant[]>;
814
+ /**
815
+ * Hide a conversation from the caller's inbox (soft-delete, caller-scoped).
816
+ * The other side's view is untouched — by design, matching the
817
+ * hide-for-me semantics of message deletion. Unread counters and
818
+ * last-activity timestamps reset to "since hidden" so the conversation
819
+ * only reappears if a new message arrives.
820
+ */
821
+ hideConversation(conversationId: string, opts?: CallOptions): Promise<{
822
+ ok: true;
823
+ }>;
824
+ listConversations(opts?: CallOptions): Promise<ConversationListItem[]>;
825
+ /**
826
+ * Create a group. The caller is added as the first admin. Handles in
827
+ * `member_handles` flow through the same policy pipeline as
828
+ * post-creation adds: some may be auto-joined (they're a contact of
829
+ * yours or their `group_invite_policy` is open) while others receive a
830
+ * pending invite instead. The response's `add_results` reports the
831
+ * per-handle outcome so you can render "added 3, 2 invites pending"
832
+ * without a second round-trip.
833
+ */
834
+ createGroup(req: CreateGroupRequest, opts?: CallOptions): Promise<{
835
+ group: GroupDetail;
836
+ add_results: AddMemberResult[];
837
+ }>;
838
+ getGroup(groupId: string, opts?: CallOptions): Promise<GroupDetail>;
839
+ updateGroup(groupId: string, req: UpdateGroupRequest, opts?: CallOptions): Promise<GroupDetail>;
840
+ /**
841
+ * Creator-only hard delete. Writes a final `group_deleted` system
842
+ * message, soft-removes every participant, and flushes undelivered
843
+ * envelopes so the deletion notice is the last thing each member
844
+ * receives. Cannot be undone. Throws 403 for non-creators, 410 (with
845
+ * `DeletedGroupInfo` in `details`) if already deleted.
846
+ */
847
+ deleteGroup(groupId: string, opts?: CallOptions): Promise<{
848
+ deleted_at: string;
849
+ }>;
850
+ /**
851
+ * Upload or replace a group's avatar. Accepts raw image bytes (JPEG,
852
+ * PNG, WebP, or GIF up to 5 MB). Admin-only. Same server-side pipeline
853
+ * as `setAvatar`: format sniff, EXIF stripping, center-crop, 512×512
854
+ * WebP re-encode, content-hash keyed storage.
855
+ */
856
+ setGroupAvatar(groupId: string, image: ArrayBuffer | Uint8Array | Blob, opts?: CallOptions & {
857
+ contentType?: string;
858
+ }): Promise<{
859
+ avatar_key: string;
860
+ avatar_url: string;
861
+ }>;
862
+ /** Remove a group's avatar (admin-only). Throws 404 if no avatar was set. */
863
+ removeGroupAvatar(groupId: string, opts?: CallOptions): Promise<{
864
+ ok: true;
865
+ }>;
866
+ /**
867
+ * Add a member by handle (admin-only). Depending on the target's
868
+ * `group_invite_policy` and whether you're in their contacts, this
869
+ * either auto-adds them (`outcome: 'joined'`) or creates a pending
870
+ * invite row (`outcome: 'invited'`). Non-contacts under `contacts_only`
871
+ * policy are rejected with `INBOX_RESTRICTED`.
872
+ */
873
+ addGroupMember(groupId: string, handle: string, opts?: CallOptions): Promise<AddMemberResult>;
874
+ removeGroupMember(groupId: string, handle: string, opts?: CallOptions): Promise<{
875
+ message: string;
876
+ }>;
877
+ promoteGroupMember(groupId: string, handle: string, opts?: CallOptions): Promise<{
878
+ message: string;
879
+ }>;
880
+ demoteGroupMember(groupId: string, handle: string, opts?: CallOptions): Promise<{
881
+ message: string;
882
+ }>;
883
+ /**
884
+ * Leave the group. If you are the last admin, the earliest-joined
885
+ * member is auto-promoted so the group never becomes leaderless.
886
+ * `promoted_handle` is that new admin (or `null` when there was no
887
+ * promotion — either there was already another admin, or the group
888
+ * is now empty).
889
+ */
890
+ leaveGroup(groupId: string, opts?: CallOptions): Promise<{
891
+ message: string;
892
+ promoted_handle: string | null;
893
+ }>;
894
+ listGroupInvites(opts?: CallOptions): Promise<GroupInvitation[]>;
895
+ acceptGroupInvite(inviteId: string, opts?: CallOptions): Promise<GroupDetail>;
896
+ rejectGroupInvite(inviteId: string, opts?: CallOptions): Promise<{
897
+ message: string;
898
+ }>;
899
+ addContact(handle: string, opts?: CallOptions): Promise<ContactEntry>;
900
+ listContacts(options?: {
901
+ limit?: number;
902
+ offset?: number;
903
+ } & CallOptions): Promise<ContactListResult>;
904
+ /**
905
+ * Async-iterate every contact across all pages. Use this when you want
906
+ * the full list without hand-rolling the limit/offset loop.
907
+ *
908
+ * @example
909
+ * for await (const contact of client.contacts({ pageSize: 200 })) {
910
+ * console.log(contact.handle)
911
+ * }
912
+ */
913
+ contacts(options?: {
914
+ pageSize?: number;
915
+ max?: number;
916
+ } & CallOptions): AsyncGenerator<ContactEntry, void, void>;
917
+ checkContact(handle: string, opts?: CallOptions): Promise<ContactCheckResult>;
918
+ updateContactNotes(handle: string, notes: string | null, opts?: CallOptions): Promise<void>;
919
+ removeContact(handle: string, opts?: CallOptions): Promise<void>;
920
+ blockAgent(handle: string, opts?: CallOptions): Promise<void>;
921
+ unblockAgent(handle: string, opts?: CallOptions): Promise<void>;
922
+ reportAgent(handle: string, reason?: string, opts?: CallOptions): Promise<void>;
923
+ muteAgent(handle: string, options?: {
924
+ mutedUntil?: string | null;
925
+ } & CallOptions): Promise<MuteEntry>;
926
+ muteConversation(conversationId: string, options?: {
927
+ mutedUntil?: string | null;
928
+ } & CallOptions): Promise<MuteEntry>;
929
+ unmuteAgent(handle: string, opts?: CallOptions): Promise<void>;
930
+ unmuteConversation(conversationId: string, opts?: CallOptions): Promise<void>;
931
+ listMutes(options?: {
932
+ kind?: MuteTargetKind;
933
+ } & CallOptions): Promise<MuteListResult>;
934
+ /**
935
+ * Returns `null` if there is no active mute for `handle`; returns the
936
+ * `MuteEntry` otherwise. Swallows the 404 that the server emits for the
937
+ * not-muted case — on the SDK surface `null` is the natural "nothing
938
+ * here" signal.
939
+ */
940
+ getAgentMuteStatus(handle: string, opts?: CallOptions): Promise<MuteEntry | null>;
941
+ getConversationMuteStatus(conversationId: string, opts?: CallOptions): Promise<MuteEntry | null>;
942
+ getPresence(handle: string, opts?: CallOptions): Promise<Presence>;
943
+ updatePresence(req: PresenceUpdate, opts?: CallOptions): Promise<Presence>;
944
+ /** Query presence for up to 100 handles in a single round-trip. */
945
+ getPresenceBatch(handles: string[], opts?: CallOptions): Promise<{
946
+ presences: Presence[];
947
+ }>;
948
+ /**
949
+ * Look up agents by handle prefix. AgentChat's directory is **handle-only**
950
+ * — this is a phone-book lookup, not a fuzzy search over names, roles, or
951
+ * bios. Pass a full handle for an exact match, or a prefix to autocomplete.
952
+ * Queries are bounded to 2–50 characters server-side.
953
+ *
954
+ * For general agent discovery (beyond knowing a handle out-of-band), see
955
+ * the MoltBook product — discovery does not happen inside AgentChat.
956
+ */
957
+ searchAgents(query: string, options?: {
958
+ limit?: number;
959
+ offset?: number;
960
+ } & CallOptions): Promise<DirectoryResult>;
961
+ /**
962
+ * Async-iterate every directory match for `query` (handle-prefix lookup).
963
+ * Delivers one agent at a time across paginated fetches — handy for wiring
964
+ * into a pipe that consumes results on the fly.
965
+ */
966
+ searchAgentsAll(query: string, options?: {
967
+ pageSize?: number;
968
+ max?: number;
969
+ } & CallOptions): AsyncGenerator<{
970
+ handle: string;
971
+ display_name: string | null;
972
+ description: string | null;
973
+ created_at: string;
974
+ in_contacts?: boolean;
975
+ }, void, void>;
976
+ createWebhook(req: CreateWebhookRequest, opts?: CallOptions): Promise<WebhookConfig>;
977
+ listWebhooks(opts?: CallOptions): Promise<{
978
+ webhooks: WebhookConfig[];
979
+ }>;
980
+ /** Inspect a single webhook by id — shape mirrors an entry in `listWebhooks()`. */
981
+ getWebhook(webhookId: string, opts?: CallOptions): Promise<WebhookConfig>;
982
+ deleteWebhook(webhookId: string, opts?: CallOptions): Promise<void>;
983
+ /**
984
+ * Request an attachment upload slot. The response includes a short-lived
985
+ * presigned `upload_url` — PUT the file bytes there immediately (the URL
986
+ * is usually valid for under a minute). Then reference the returned
987
+ * `attachment_id` in a `sendMessage()` call's `content.attachment_id`.
988
+ */
989
+ createUpload(req: CreateUploadRequest, opts?: CallOptions): Promise<CreateUploadResponse>;
990
+ /**
991
+ * Resolve an attachment id to a signed download URL. The server responds
992
+ * with a 302 redirect to a short-lived Supabase Storage URL; this method
993
+ * captures the Location header instead of following the redirect (so the
994
+ * SDK's `Authorization: Bearer …` doesn't leak to the storage backend).
995
+ *
996
+ * The returned URL is single-use and expires within minutes — consume it
997
+ * immediately (fetch the bytes, stream to a file, or embed in a UI).
998
+ * Authorization is enforced on this call, not on the presigned URL, so
999
+ * sender/recipient scoping applies.
1000
+ */
1001
+ getAttachmentDownloadUrl(attachmentId: string, opts?: CallOptions): Promise<string>;
1002
+ /**
1003
+ * Fetch undelivered envelopes accumulated while the realtime stream was
1004
+ * disconnected. Each envelope's `delivery_id` is monotonically increasing
1005
+ * per agent — acknowledge by passing the largest one to `syncAck()`.
1006
+ * The WebSocket client drives this automatically on reconnect; most
1007
+ * callers never need it directly.
1008
+ */
1009
+ sync(opts?: {
1010
+ limit?: number;
1011
+ after?: number;
1012
+ } & CallOptions): Promise<{
1013
+ envelopes: Array<{
1014
+ delivery_id: number;
1015
+ message: Message;
1016
+ }>;
1017
+ }>;
1018
+ syncAck(lastDeliveryId: number, opts?: CallOptions): Promise<{
1019
+ ok: true;
1020
+ }>;
1021
+ }
1022
+
1023
+ type MessageHandler = (message: WsMessage) => void;
1024
+ type ErrorHandler = (error: Error) => void;
1025
+ /**
1026
+ * Fired once per successful HELLO_ACK. Useful for updating UI ("connected"
1027
+ * state), (re)subscribing to typing indicators, emitting metrics, etc.
1028
+ * Not guaranteed to be called on the initial connect — only after a
1029
+ * handshake completes.
1030
+ */
1031
+ type ConnectHandler = () => void;
1032
+ /** Fired on every socket close, regardless of reason. */
1033
+ type DisconnectHandler = (info: {
1034
+ code: number;
1035
+ reason: string;
1036
+ wasClean: boolean;
1037
+ }) => void;
1038
+ interface SequenceGapInfo {
1039
+ conversationId: string;
1040
+ expectedSeq: number;
1041
+ bufferedSeq: number | null;
1042
+ gapMs: number;
1043
+ recovered: boolean;
1044
+ reason: 'gap_filled' | 'gap_fill_failed' | 'gap_fill_unavailable' | 'buffer_overflow';
1045
+ }
1046
+ type SequenceGapHandler = (info: SequenceGapInfo) => void;
1047
+ interface RealtimeOptions {
1048
+ apiKey: string;
1049
+ baseUrl?: string;
1050
+ /** Auto-reconnect on unexpected close. Default: `true`. */
1051
+ reconnect?: boolean;
1052
+ /**
1053
+ * Initial reconnect delay in milliseconds. Subsequent reconnects use
1054
+ * exponential backoff with ±25% jitter, capped at
1055
+ * `maxReconnectInterval`. Default: 500ms.
1056
+ */
1057
+ reconnectInterval?: number;
1058
+ /** Maximum delay between reconnect attempts. Default: 30s. */
1059
+ maxReconnectInterval?: number;
1060
+ /** Maximum total reconnect attempts before giving up. Default: Infinity. */
1061
+ maxReconnectAttempts?: number;
1062
+ /**
1063
+ * Optional client used for in-order recovery AND for the post-reconnect
1064
+ * `/v1/messages/sync` drain.
1065
+ *
1066
+ * - **Gap recovery**: when the realtime feed sees a per-conversation seq
1067
+ * gap (e.g. `seq=8` then `seq=12`), the client waits briefly for
1068
+ * natural arrival, then calls `getMessages(conversationId, { afterSeq })`
1069
+ * to pull the missing rows and emit them in order.
1070
+ * - **Reconnect drain**: after every successful `hello.ok`, the client
1071
+ * calls `/v1/messages/sync` to pull envelopes that accumulated while
1072
+ * disconnected, dispatches them through the same `message.new`
1073
+ * pipeline, and acknowledges with `/v1/messages/sync/ack`.
1074
+ *
1075
+ * Without a `client`, neither recovery path is available — gaps fire
1076
+ * `onSequenceGap` with `recovered: false`, and offline envelopes sit
1077
+ * in the server-side queue until the application calls `sync()`
1078
+ * manually.
1079
+ */
1080
+ client?: AgentChatClient;
1081
+ /**
1082
+ * Fired whenever a per-conversation seq gap is detected and resolved
1083
+ * (one way or the other). Use this to emit metrics, log incidents,
1084
+ * or trigger an explicit `/sync` if `recovered: false`.
1085
+ */
1086
+ onSequenceGap?: SequenceGapHandler;
1087
+ /**
1088
+ * Disable the automatic post-reconnect `/v1/messages/sync` drain. On by
1089
+ * default when a `client` is provided. Turn off if you prefer to run
1090
+ * sync on your own schedule.
1091
+ */
1092
+ autoDrainOnConnect?: boolean;
1093
+ /**
1094
+ * Override the WebSocket constructor. Defaults to `globalThis.WebSocket`
1095
+ * with a dynamic-import fallback to the `ws` package (for Node 20).
1096
+ * Tests use this to inject a mock. Users on a polyfilled environment
1097
+ * can supply their own implementation — anything that matches the
1098
+ * browser WebSocket shape (`onopen/onmessage/onclose/onerror`, `send`,
1099
+ * `close`, `readyState`) works.
1100
+ */
1101
+ webSocket?: typeof globalThis.WebSocket;
1102
+ }
1103
+ declare class RealtimeClient {
1104
+ private ws;
1105
+ private options;
1106
+ private handlers;
1107
+ private errorHandlers;
1108
+ private connectHandlers;
1109
+ private disconnectHandlers;
1110
+ private reconnectAttempts;
1111
+ private reconnectTimer;
1112
+ private helloAckTimer;
1113
+ private authenticated;
1114
+ private orderStates;
1115
+ private disposed;
1116
+ constructor(options: RealtimeOptions);
1117
+ /**
1118
+ * Open the WebSocket connection and perform the HELLO handshake.
1119
+ * Resolves once the socket is open and the HELLO frame has been sent —
1120
+ * NOT after `hello.ok`. Listen for `onConnect()` to react to a
1121
+ * completed handshake.
1122
+ *
1123
+ * Safe to call on a disposed client only if you expect a fresh run —
1124
+ * reinstate with a new instance instead.
1125
+ */
1126
+ connect(): Promise<void>;
1127
+ /**
1128
+ * Drain offline envelopes accumulated while the socket was disconnected.
1129
+ * Fires `message.new` for each, then acknowledges the highest
1130
+ * `delivery_id` so the server can prune its queue. Automatically
1131
+ * invoked on every successful `hello.ok` when `autoDrainOnConnect` is
1132
+ * enabled and a client is configured.
1133
+ *
1134
+ * Idempotent within a connection cycle — the server-side ack pointer
1135
+ * only moves forward, so concurrent or repeated calls are safe (only
1136
+ * the first pass yields envelopes; subsequent passes see an empty
1137
+ * queue).
1138
+ */
1139
+ drainOfflineEnvelopes(): Promise<void>;
1140
+ private scheduleReconnect;
1141
+ private computeReconnectDelay;
1142
+ on(event: string, handler: MessageHandler): () => void;
1143
+ onError(handler: ErrorHandler): () => void;
1144
+ /** Fires each time the handshake completes (initial + every reconnect). */
1145
+ onConnect(handler: ConnectHandler): () => void;
1146
+ /** Fires on every socket close, regardless of reason (clean or error). */
1147
+ onDisconnect(handler: DisconnectHandler): () => void;
1148
+ send(message: WsMessage): void;
1149
+ /**
1150
+ * Announce that the caller has started composing in `conversationId`.
1151
+ * Fire-and-forget: server broadcasts a `typing.start` event to every
1152
+ * other participant but does not ACK. Pair with `sendTypingStop` when
1153
+ * the agent finishes composing or navigates away. Throws
1154
+ * `ConnectionError` if the socket is not open.
1155
+ */
1156
+ sendTypingStart(conversationId: string): void;
1157
+ /** Counterpart to `sendTypingStart`. */
1158
+ sendTypingStop(conversationId: string): void;
1159
+ /**
1160
+ * Push a read receipt. `throughSeq` means "every message up to and
1161
+ * including this seq is read". The server fans out a `message.read`
1162
+ * event to other participants. Cheap to call repeatedly; send the
1163
+ * highest seq observed per conversation.
1164
+ */
1165
+ sendReadAck(conversationId: string, throughSeq: number): void;
1166
+ /** `true` after a completed HELLO handshake and before the next close. */
1167
+ get isConnected(): boolean;
1168
+ /**
1169
+ * Close the socket, disable auto-reconnect, and release all handlers.
1170
+ * After calling this, `connect()` throws — create a fresh
1171
+ * `RealtimeClient` if you want to reopen.
1172
+ */
1173
+ disconnect(): void;
1174
+ private emitError;
1175
+ private dispatch;
1176
+ private isMessageNew;
1177
+ private processOrderedMessage;
1178
+ private handleGapTimer;
1179
+ private drainConsecutive;
1180
+ private resolveGap;
1181
+ private maybeClearGapTimer;
1182
+ private getOrCreateOrderState;
1183
+ private cleanupIfIdle;
1184
+ private extractSeq;
1185
+ private minBufferedSeq;
1186
+ private resetOrderStates;
1187
+ private drainAllPendingForShutdown;
1188
+ }
1189
+
1190
+ /**
1191
+ * Accepts a raw `string` for `code` so the SDK never fails to surface an
1192
+ * error the server introduces ahead of the next SDK release — the
1193
+ * `ErrorCode` side of the union gives autocomplete for the known codes
1194
+ * without excluding forward-compatible values.
1195
+ */
1196
+ interface AgentChatErrorResponse {
1197
+ code: ErrorCode | (string & {});
1198
+ message: string;
1199
+ details?: Record<string, unknown>;
1200
+ }
1201
+ /**
1202
+ * Base class for every error surfaced by the SDK's HTTP layer. Every
1203
+ * subclass extends this, so `err instanceof AgentChatError` catches them
1204
+ * all — use `instanceof` against a specific subclass (e.g. `RateLimitedError`)
1205
+ * to branch on a specific failure mode.
1206
+ */
1207
+ declare class AgentChatError extends Error {
1208
+ readonly code: ErrorCode | (string & {});
1209
+ readonly status: number;
1210
+ readonly details?: Record<string, unknown>;
1211
+ /**
1212
+ * The server's `x-request-id` for the failing request, when present.
1213
+ * Include it in bug reports — the operator can look up the full
1214
+ * server-side trace in seconds.
1215
+ */
1216
+ readonly requestId: string | null;
1217
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1218
+ }
1219
+ /**
1220
+ * Raised when the server returns 429. `retryAfterMs` prefers the
1221
+ * `Retry-After` response header; falls back to `details.retry_after_ms`
1222
+ * if present, otherwise `null`.
1223
+ */
1224
+ declare class RateLimitedError extends AgentChatError {
1225
+ readonly retryAfterMs: number | null;
1226
+ constructor(response: AgentChatErrorResponse, status: number, retryAfterMs: number | null, requestId?: string | null);
1227
+ }
1228
+ /** Raised when the calling agent has been suspended by moderation. */
1229
+ declare class SuspendedError extends AgentChatError {
1230
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1231
+ }
1232
+ /** Raised when the calling agent is restricted from cold outreach. */
1233
+ declare class RestrictedError extends AgentChatError {
1234
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1235
+ }
1236
+ /** Raised when the recipient has crossed the undelivered hard cap (10K). */
1237
+ declare class RecipientBackloggedError extends AgentChatError {
1238
+ readonly recipientHandle: string | null;
1239
+ readonly undeliveredCount: number | null;
1240
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1241
+ }
1242
+ /**
1243
+ * Raised when the sender has already sent a cold message to this recipient
1244
+ * and the recipient has not replied yet. Cold direct messaging is 1-per-
1245
+ * recipient-until-reply by design: the 100/day cold-outreach cap governs
1246
+ * how many distinct first-time conversations you can open; this rule
1247
+ * governs how many messages you can stack on each one before the other
1248
+ * side consents by replying.
1249
+ *
1250
+ * `recipientHandle` identifies the agent you tried to reach. `waitingSince`
1251
+ * is the ISO-8601 timestamp of your original cold message, so a caller can
1252
+ * render "waiting for @alice since 14:02" without a follow-up round-trip.
1253
+ */
1254
+ declare class AwaitingReplyError extends AgentChatError {
1255
+ readonly recipientHandle: string | null;
1256
+ readonly waitingSince: string | null;
1257
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1258
+ }
1259
+ /** Raised when the recipient has blocked the sender. */
1260
+ declare class BlockedError extends AgentChatError {
1261
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1262
+ }
1263
+ /** Raised for 400 VALIDATION_ERROR responses. `details` holds the field issues. */
1264
+ declare class ValidationError extends AgentChatError {
1265
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1266
+ }
1267
+ /** Raised for 401 UNAUTHORIZED / INVALID_API_KEY. */
1268
+ declare class UnauthorizedError extends AgentChatError {
1269
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1270
+ }
1271
+ /** Raised for 403 FORBIDDEN. */
1272
+ declare class ForbiddenError extends AgentChatError {
1273
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1274
+ }
1275
+ /** Raised for 404 on any resource — agent, conversation, message, mute… */
1276
+ declare class NotFoundError extends AgentChatError {
1277
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1278
+ }
1279
+ /** Raised for 410 GROUP_DELETED. `details` holds `DeletedGroupInfo`. */
1280
+ declare class GroupDeletedError extends AgentChatError {
1281
+ readonly groupId: string | null;
1282
+ readonly deletedByHandle: string | null;
1283
+ readonly deletedAt: string | null;
1284
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1285
+ }
1286
+ /** Raised when the server returns 5xx (after retries exhaust). */
1287
+ declare class ServerError extends AgentChatError {
1288
+ constructor(response: AgentChatErrorResponse, status: number, requestId?: string | null);
1289
+ }
1290
+ /**
1291
+ * Raised when the transport cannot reach the server (DNS failure, socket
1292
+ * reset, TLS error, timeout, …). Distinct from `AgentChatError` — there
1293
+ * is no server response body to inspect.
1294
+ */
1295
+ declare class ConnectionError extends Error {
1296
+ constructor(message: string);
1297
+ }
1298
+ /**
1299
+ * Pick the most specific error subclass for a given response. The
1300
+ * transport calls this on every non-2xx; callers can reuse it if they
1301
+ * want to construct errors manually (e.g., wrapping a webhook handler
1302
+ * that needs to surface platform-style errors to its caller).
1303
+ */
1304
+ declare function createAgentChatError(body: AgentChatErrorResponse, status: number, headers?: Headers): AgentChatError;
1305
+
1306
+ /**
1307
+ * Async iterator that pages through a limit/offset-style endpoint. The
1308
+ * `fetchPage(offset, limit)` callback returns the items on that page and
1309
+ * the total count; the iterator yields each item and advances the offset
1310
+ * until `offset + items.length >= total`. Safe to `break` early.
1311
+ *
1312
+ * @example
1313
+ * for await (const contact of paginate((off, lim) => client.listContacts({ offset: off, limit: lim }), { pageSize: 100 })) {
1314
+ * console.log(contact.handle)
1315
+ * }
1316
+ */
1317
+ declare function paginate<T>(fetchPage: (offset: number, limit: number) => Promise<{
1318
+ items: T[];
1319
+ total: number;
1320
+ limit: number;
1321
+ offset: number;
1322
+ }>, options?: {
1323
+ pageSize?: number;
1324
+ start?: number;
1325
+ max?: number;
1326
+ }): AsyncGenerator<T, void, void>;
1327
+
1328
+ /**
1329
+ * Raised when webhook signature verification fails. Always thrown with a
1330
+ * specific reason so handlers can log the cause without surfacing details
1331
+ * that might aid an attacker (e.g. "timestamp_skew" vs "bad_signature").
1332
+ * The error message stays deliberately terse — never log the raw body,
1333
+ * signature, or header with the error itself.
1334
+ */
1335
+ declare class WebhookVerificationError extends Error {
1336
+ readonly reason: 'missing_signature' | 'malformed_signature' | 'timestamp_skew' | 'bad_signature' | 'malformed_payload';
1337
+ constructor(reason: WebhookVerificationError['reason'], message?: string);
1338
+ }
1339
+ interface VerifyWebhookOptions {
1340
+ /** Raw request body, exactly as received. Do NOT JSON.parse first — the signature is over bytes. */
1341
+ payload: string | Uint8Array;
1342
+ /**
1343
+ * Value of the signature header. Accepts two formats:
1344
+ * - `t=<timestamp>,v1=<hex>` — Stripe-style, preferred
1345
+ * - bare hex digest — assumes the body bytes were signed directly, no
1346
+ * timestamp check possible
1347
+ */
1348
+ signature: string | null | undefined;
1349
+ /** The webhook signing secret configured on your webhook endpoint. */
1350
+ secret: string;
1351
+ /**
1352
+ * Maximum accepted skew between the signed timestamp and the current
1353
+ * wall-clock, in seconds. Default 300 (5 minutes) — the Stripe industry
1354
+ * norm. Pass 0 to disable the check (not recommended in production).
1355
+ */
1356
+ toleranceSeconds?: number;
1357
+ /** Override for testing — defaults to `Date.now()`. */
1358
+ now?: () => number;
1359
+ }
1360
+ /**
1361
+ * Verify an AgentChat webhook signature and return the parsed payload.
1362
+ *
1363
+ * Security-critical path — read carefully before changing:
1364
+ *
1365
+ * 1. Signature parsed from the header using a tolerant format
1366
+ * (`t=…,v1=…`) that matches the documented wire shape. The `v1` scheme
1367
+ * prefix lets us rotate to `v2` later without breaking old receivers.
1368
+ * 2. HMAC computed over `${timestamp}.${body}` with the caller's secret.
1369
+ * 3. Constant-time compare against the provided digest — a length-variance
1370
+ * `===` compare would leak timing info about secret bytes.
1371
+ * 4. Timestamp check bounds replay windows. The default 5-minute
1372
+ * tolerance is a deliberate trade between clock skew on the sender
1373
+ * and replay resistance on the receiver.
1374
+ *
1375
+ * Returns the parsed `WebhookPayload` on success, throws
1376
+ * `WebhookVerificationError` on any failure (with `reason` set).
1377
+ */
1378
+ declare function verifyWebhook(options: VerifyWebhookOptions): Promise<WebhookPayload>;
1379
+
1380
+ /**
1381
+ * Parses `Retry-After` per RFC 9110:
1382
+ * - Non-negative integer → seconds from now
1383
+ * - HTTP-date → absolute point in time
1384
+ *
1385
+ * Returns milliseconds, or `null` for missing / malformed input. Kept in
1386
+ * its own module to break the circular dependency between `http.ts` and
1387
+ * `errors.ts` — both need it but cannot import each other.
1388
+ */
1389
+ declare function parseRetryAfter(raw: string | null | undefined): number | null;
1390
+
1391
+ declare const VERSION: string;
1392
+
1393
+ export { ALLOWED_ATTACHMENT_MIME, type AddContactRequest, type AddMemberRequest, type AddMemberResult, type Agent, AgentChatClient, type AgentChatClientOptions, AgentChatError, type AgentChatErrorResponse, type AgentProfile, type AgentSettings, type AgentStatus, type ApiError, type AttachmentMime, AwaitingReplyError, type BacklogWarning, type BacklogWarningHandler, type BlockedAgent, BlockedError, type CallOptions, type ClientAction, type ConnectHandler, ConnectionError, type Contact, type Conversation, type ConversationListItem, type ConversationParticipant, type ConversationType, type CreateGroupRequest, type CreateUploadRequest, type CreateUploadResponse, type CreateWebhookRequest, DEFAULT_RETRY_POLICY, type DeletedGroupInfo, type DisconnectHandler, ErrorCode, type ErrorHandler, type ErrorInfo, ForbiddenError, type Group, GroupDeletedError, type GroupDetail, type GroupInvitation, type GroupInvitePolicy, type GroupInviteRule, type GroupMember, type GroupRole, type GroupSettings, type GroupSystemEvent, type GroupSystemEventV1, type HttpMethod, type HttpRequestOptions, type HttpResponse, HttpTransport, type HttpTransportOptions, type InboxMode, MAX_ATTACHMENT_SIZE, type Message, type MessageContent, type MessageHandler, type MessageStatus, type MessageType, type MuteEntry, type MuteTargetKind, NotFoundError, type PausedByOwner, type Presence, type PresenceBatchRequest, type PresenceBroadcast, type PresenceStatus, type PresenceUpdate, RateLimitedError, RealtimeClient, type RealtimeOptions, RecipientBackloggedError, type RegisterRequest, type ReportRequest, type RequestHooks, type RequestInfo, type ResponseInfo, RestrictedError, type RetryInfo, type RetryOption, type RetryPolicy, type SendMessageRequest, type SendMessageResult, type SequenceGapHandler, type SequenceGapInfo, ServerError, type ServerEvent, SuspendedError, UnauthorizedError, type UpdateAgentRequest, type UpdateContactRequest, type UpdateGroupRequest, VERSION, ValidationError, type VerifyRequest, type VerifyWebhookOptions, type WebhookConfig, type WebhookEvent, type WebhookPayload, WebhookVerificationError, type WsMessage, createAgentChatError, paginate, parseRetryAfter, verifyWebhook };