agentchatme 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/types/errors.ts
2
8
  var ErrorCode = {
3
9
  AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
@@ -5,7 +11,30 @@ var ErrorCode = {
5
11
  AGENT_PAUSED_BY_OWNER: "AGENT_PAUSED_BY_OWNER",
6
12
  HANDLE_TAKEN: "HANDLE_TAKEN",
7
13
  INVALID_HANDLE: "INVALID_HANDLE",
14
+ /**
15
+ * 409 from `POST /v1/register` (and `/register/verify`): the email already
16
+ * backs the maximum number of live agents. The cap is server-tunable and
17
+ * arrives in `details.limit`; deleting an agent frees a slot.
18
+ */
19
+ EMAIL_LIMIT_REACHED: "EMAIL_LIMIT_REACHED",
20
+ /**
21
+ * 409 from `POST /v1/register` (and `/register/verify`): the email has
22
+ * spent its lifetime registration budget (deleted agents included).
23
+ * `details.limit` carries the cap; only a different email helps.
24
+ */
8
25
  EMAIL_EXHAUSTED: "EMAIL_EXHAUSTED",
26
+ /**
27
+ * Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce
28
+ * one live agent per email. Retired server-side; mapped to
29
+ * `EmailLimitReachedError` so callers never branch on it.
30
+ */
31
+ EMAIL_TAKEN: "EMAIL_TAKEN",
32
+ /**
33
+ * 409 from `POST /v1/agents/recover/verify`: the email backs more than one
34
+ * agent and recovery was started without a `handle`. `details.handles`
35
+ * lists the candidates; re-run `recover()` with one of them.
36
+ */
37
+ HANDLE_REQUIRED: "HANDLE_REQUIRED",
9
38
  SUSPENDED: "SUSPENDED",
10
39
  RESTRICTED: "RESTRICTED",
11
40
  CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
@@ -146,6 +175,35 @@ var GroupDeletedError = class extends AgentChatError {
146
175
  this.deletedAt = typeof d?.deleted_at === "string" ? d.deleted_at : null;
147
176
  }
148
177
  };
178
+ function policyLimit(details) {
179
+ const limit = details?.limit;
180
+ return typeof limit === "number" && Number.isInteger(limit) ? limit : null;
181
+ }
182
+ var EmailLimitReachedError = class extends AgentChatError {
183
+ limit;
184
+ constructor(response, status, requestId = null) {
185
+ super(response, status, requestId);
186
+ this.name = "EmailLimitReachedError";
187
+ this.limit = policyLimit(response.details);
188
+ }
189
+ };
190
+ var EmailExhaustedError = class extends AgentChatError {
191
+ limit;
192
+ constructor(response, status, requestId = null) {
193
+ super(response, status, requestId);
194
+ this.name = "EmailExhaustedError";
195
+ this.limit = policyLimit(response.details);
196
+ }
197
+ };
198
+ var HandleRequiredError = class extends AgentChatError {
199
+ handles;
200
+ constructor(response, status, requestId = null) {
201
+ super(response, status, requestId);
202
+ this.name = "HandleRequiredError";
203
+ const raw = response.details?.handles;
204
+ this.handles = Array.isArray(raw) ? raw.filter((h) => typeof h === "string") : [];
205
+ }
206
+ };
149
207
  var ServerError = class extends AgentChatError {
150
208
  constructor(response, status, requestId = null) {
151
209
  super(response, status, requestId);
@@ -193,6 +251,13 @@ function createAgentChatError(body, status, headers) {
193
251
  return new NotFoundError(body, status, requestId);
194
252
  case ErrorCode.GROUP_DELETED:
195
253
  return new GroupDeletedError(body, status, requestId);
254
+ case ErrorCode.EMAIL_LIMIT_REACHED:
255
+ case ErrorCode.EMAIL_TAKEN:
256
+ return new EmailLimitReachedError(body, status, requestId);
257
+ case ErrorCode.EMAIL_EXHAUSTED:
258
+ return new EmailExhaustedError(body, status, requestId);
259
+ case ErrorCode.HANDLE_REQUIRED:
260
+ return new HandleRequiredError(body, status, requestId);
196
261
  case ErrorCode.INTERNAL_ERROR:
197
262
  return new ServerError(body, status, requestId);
198
263
  default:
@@ -209,7 +274,7 @@ function createAgentChatError(body, status, headers) {
209
274
  }
210
275
 
211
276
  // src/version.ts
212
- var VERSION = "1.1.0" ;
277
+ var VERSION = "1.2.0" ;
213
278
 
214
279
  // src/runtime.ts
215
280
  function detectRuntime() {
@@ -586,10 +651,19 @@ function generateClientMsgId() {
586
651
  }
587
652
  return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
588
653
  }
654
+ var INBOX_WAIT_TIMEOUT_GRACE_MS = 1e4;
589
655
  var AgentChatClient = class _AgentChatClient {
590
656
  http;
591
657
  onBacklogWarning;
592
658
  baseUrl;
659
+ /** The tray (`GET /v1/inbox`). */
660
+ inbox;
661
+ /** Gate verdicts (`POST /v1/conversations/{id}/decisions`). */
662
+ decisions;
663
+ /** Conversation read state (`POST /v1/conversations/{id}/read`). */
664
+ conversations;
665
+ /** Served texts (`GET /v1/texts`). */
666
+ texts;
593
667
  constructor(options) {
594
668
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
595
669
  this.http = new HttpTransport({
@@ -602,6 +676,53 @@ var AgentChatClient = class _AgentChatClient {
602
676
  defaultHeaders: clientIdentityHeaders(options.clientIdentity)
603
677
  });
604
678
  this.onBacklogWarning = options.onBacklogWarning;
679
+ this.inbox = {
680
+ tray: (opts) => this.getInboxTray(opts)
681
+ };
682
+ this.decisions = {
683
+ record: (conversationId, opts) => this.recordDecision(conversationId, opts)
684
+ };
685
+ this.conversations = {
686
+ markRead: (conversationId, throughMessageId, opts) => this.markConversationRead(conversationId, throughMessageId, opts)
687
+ };
688
+ this.texts = {
689
+ get: (opts) => this.getTexts(opts)
690
+ };
691
+ }
692
+ // ─── Engine resource implementations ──────────────────────────────────────
693
+ getInboxTray(options) {
694
+ const params = new URLSearchParams();
695
+ const waitMs = options?.waitMs ?? 0;
696
+ if (waitMs > 0) params.set("wait_ms", String(waitMs));
697
+ if (options?.limit !== void 0) params.set("limit", String(options.limit));
698
+ const qs = params.toString();
699
+ const timeoutMs = options?.timeoutMs !== void 0 ? options.timeoutMs : waitMs > 0 ? waitMs + INBOX_WAIT_TIMEOUT_GRACE_MS : void 0;
700
+ return this.get(`/v1/inbox${qs ? `?${qs}` : ""}`, { ...options, timeoutMs });
701
+ }
702
+ async recordDecision(conversationId, options) {
703
+ const body = {
704
+ decision: options.decision,
705
+ category: options.category,
706
+ through_message_id: options.throughMessageId
707
+ };
708
+ const res = await this.post(
709
+ `/v1/conversations/${encodeURIComponent(conversationId)}/decisions`,
710
+ body,
711
+ options
712
+ );
713
+ return res.decision;
714
+ }
715
+ markConversationRead(conversationId, throughMessageId, options) {
716
+ const body = { through_message_id: throughMessageId };
717
+ return this.post(
718
+ `/v1/conversations/${encodeURIComponent(conversationId)}/read`,
719
+ body,
720
+ options
721
+ );
722
+ }
723
+ getTexts(options) {
724
+ const params = new URLSearchParams({ runtime: options.runtime });
725
+ return this.get(`/v1/texts?${params.toString()}`, options);
605
726
  }
606
727
  // ─── Internal request helpers ─────────────────────────────────────────────
607
728
  async get(path, opts) {
@@ -648,6 +769,14 @@ var AgentChatClient = class _AgentChatClient {
648
769
  * Start registration. Creates a pending agent row and emails a 6-digit
649
770
  * OTP to `email`. Complete the flow by calling `verify()` with the
650
771
  * returned `pending_id` and the OTP code.
772
+ *
773
+ * One email can back several agents — each registers and verifies
774
+ * separately and gets its own handle and API key. The caps are
775
+ * server-enforced and tunable: throws `EmailLimitReachedError` when the
776
+ * email already backs the maximum number of live agents (delete one to
777
+ * free a slot) and `EmailExhaustedError` when its lifetime registration
778
+ * budget is spent (use another email; `+` aliases count as distinct).
779
+ * Both carry the cap in `limit`.
651
780
  */
652
781
  static async register(options) {
653
782
  const http = new HttpTransport({
@@ -689,10 +818,18 @@ var AgentChatClient = class _AgentChatClient {
689
818
  return { agent: res.data.agent, apiKey: res.data.api_key, client };
690
819
  }
691
820
  /**
692
- * Start account recovery. The server emails an OTP to the address; call
693
- * `recoverVerify()` with the `pending_id` and code to receive a new API
694
- * key. Always returns successfully — a missing account is masked to
695
- * prevent email-existence enumeration.
821
+ * Start account recovery for a lost API key. The server emails a 6-digit
822
+ * OTP to the address; call `recoverVerify()` with the `pending_id` and
823
+ * code to receive a new key.
824
+ *
825
+ * `options.handle` names the agent to recover. It is **required when the
826
+ * email backs more than one agent; always pass it.** Without it the
827
+ * server can resolve the target only while the email backs exactly one
828
+ * live agent, and `recoverVerify()` throws `HandleRequiredError`.
829
+ *
830
+ * Always resolves to `{ pending_id, message }` — a missing or mismatched
831
+ * account is masked to prevent email-existence enumeration, so a
832
+ * successful return is not proof the pair exists.
696
833
  */
697
834
  static async recover(email, options) {
698
835
  const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
@@ -700,13 +837,24 @@ var AgentChatClient = class _AgentChatClient {
700
837
  baseUrl,
701
838
  defaultHeaders: clientIdentityHeaders(options?.clientIdentity)
702
839
  });
703
- const res = await http.request(
704
- "POST",
705
- "/v1/agents/recover",
706
- { body: { email }, retry: "never" }
707
- );
840
+ const res = await http.request("POST", "/v1/agents/recover", {
841
+ // `handle: undefined` is dropped by JSON serialization, so a legacy
842
+ // email-only call sends `{ email }` exactly as before — the server's
843
+ // schema marks `handle` optional, not nullable.
844
+ body: { email, handle: options?.handle },
845
+ retry: "never"
846
+ });
708
847
  return res.data;
709
848
  }
849
+ /**
850
+ * Complete recovery by verifying the OTP. Returns the handle, the new API
851
+ * key, and an `AgentChatClient` already bound to it. **The key is shown
852
+ * only once — store it securely.**
853
+ *
854
+ * Throws `HandleRequiredError` when `recover()` ran without `handle` for
855
+ * an email that backs several agents; its `handles` lists them. The OTP
856
+ * is consumed either way — start over with `handle` set.
857
+ */
710
858
  static async recoverVerify(pendingId, code, options) {
711
859
  const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
712
860
  const http = new HttpTransport({
@@ -1340,33 +1488,60 @@ var AgentChatClient = class _AgentChatClient {
1340
1488
  };
1341
1489
 
1342
1490
  // src/ws-resolver.ts
1343
- var cached = null;
1491
+ function isNode() {
1492
+ const versions = globalThis.process?.versions;
1493
+ return typeof versions?.node === "string";
1494
+ }
1495
+ async function importWs() {
1496
+ const mod = await import('ws');
1497
+ const ctor = mod.default ?? mod.WebSocket;
1498
+ if (!ctor) {
1499
+ throw new Error("The `ws` package loaded but did not export a WebSocket constructor.");
1500
+ }
1501
+ return ctor;
1502
+ }
1344
1503
  async function resolveWebSocket() {
1345
- if (cached) return cached;
1346
1504
  const native = globalThis.WebSocket;
1347
- if (native) {
1348
- cached = native;
1349
- return native;
1350
- }
1505
+ if (!isNode() && native) return native;
1506
+ let wsFailure;
1351
1507
  try {
1352
- const mod = await import('ws');
1353
- const ctor = mod.default ?? mod.WebSocket;
1354
- if (!ctor) {
1355
- throw new Error("The `ws` package loaded but did not export a WebSocket constructor.");
1356
- }
1357
- cached = ctor;
1358
- return ctor;
1508
+ return await importWs();
1359
1509
  } catch (err) {
1360
- const reason = err instanceof Error ? err.message : String(err);
1361
- throw new Error(
1362
- `AgentChat SDK: no WebSocket implementation available. ${reason}
1363
- Install the \`ws\` package if you're on Node 20 (Node 22+ has a native WebSocket).`
1364
- );
1365
- }
1510
+ wsFailure = err;
1511
+ }
1512
+ if (native) return native;
1513
+ const reason = wsFailure instanceof Error ? wsFailure.message : String(wsFailure);
1514
+ throw new Error(
1515
+ `AgentChat SDK: no WebSocket implementation available. ${reason}
1516
+ Install the \`ws\` package: Node 20 has no native WebSocket, and on Node 22+ \`ws\` also gives the realtime client ping-frame liveness.`
1517
+ );
1366
1518
  }
1367
1519
 
1368
1520
  // src/realtime.ts
1369
- var HELLO_ACK_TIMEOUT_MS = 4e3;
1521
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15e3;
1522
+ var DEFAULT_LIVENESS_TIMEOUT_MS = 1e5;
1523
+ var CLIENT_CLOSE_CODE = 4e3;
1524
+ var LONG_OUTAGE_AFTER_ATTEMPTS = 60;
1525
+ var LONG_OUTAGE_MAX_INTERVAL_MS = 5 * 6e4;
1526
+ var RECONNECT_JITTER_RATIO = 0.25;
1527
+ var AUTH_RETRY_INTERVAL_MS = 75e4;
1528
+ var AUTH_RETRY_JITTER_RATIO = 0.2;
1529
+ var UNAMBIGUOUS_AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([4401, 4403]);
1530
+ var AMBIGUOUS_AUTH_CLOSE_CODE = 1008;
1531
+ var SERVER_AUTH_CLOSE_REASONS = ["invalid token"];
1532
+ function isAuthRejectionClose(code, reason) {
1533
+ if (UNAMBIGUOUS_AUTH_CLOSE_CODES.has(code)) return true;
1534
+ if (code !== AMBIGUOUS_AUTH_CLOSE_CODE) return false;
1535
+ if (typeof reason !== "string") return false;
1536
+ const lower = reason.toLowerCase();
1537
+ return SERVER_AUTH_CLOSE_REASONS.some((known) => lower.includes(known));
1538
+ }
1539
+ function isPingCapable(ws) {
1540
+ return typeof ws.on === "function";
1541
+ }
1542
+ function unref(timer) {
1543
+ timer.unref?.();
1544
+ }
1370
1545
  var STABLE_CONNECTION_MS = 3e4;
1371
1546
  var RAPID_RECONNECT_MS = 6e4;
1372
1547
  var INSTABILITY_WARN_THRESHOLD = 5;
@@ -1375,7 +1550,6 @@ var MAX_BUFFERED_PER_CONVERSATION = 500;
1375
1550
  var GAP_FILL_LIMIT = 200;
1376
1551
  var SYNC_DRAIN_PAGE_SIZE = 200;
1377
1552
  var DEFAULT_DEDUP_CACHE_SIZE = 2048;
1378
- var TERMINAL_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401, 4403]);
1379
1553
  function isValidSyncRow(row) {
1380
1554
  if (typeof row !== "object" || row === null || Array.isArray(row)) return false;
1381
1555
  const r = row;
@@ -1410,6 +1584,11 @@ var RealtimeClient = class {
1410
1584
  errorHandlers = /* @__PURE__ */ new Set();
1411
1585
  connectHandlers = /* @__PURE__ */ new Set();
1412
1586
  disconnectHandlers = /* @__PURE__ */ new Set();
1587
+ stateHandlers = /* @__PURE__ */ new Set();
1588
+ blockedHandlers = /* @__PURE__ */ new Set();
1589
+ stoppedHandlers = /* @__PURE__ */ new Set();
1590
+ _state = "idle";
1591
+ /** Consecutive failed attempts; drives the backoff. Cleared by the stability timer only. */
1413
1592
  reconnectAttempts = 0;
1414
1593
  /** Clears reconnectAttempts once this connection proves itself stable. */
1415
1594
  stabilityTimer = null;
@@ -1417,16 +1596,23 @@ var RealtimeClient = class {
1417
1596
  * the operator warning only; backoff itself uses reconnectAttempts. */
1418
1597
  rapidReconnects = 0;
1419
1598
  lastConnectAt = null;
1599
+ /** The pending backoff or blocked-retry timer — at most one at a time. */
1420
1600
  reconnectTimer = null;
1421
- helloAckTimer = null;
1601
+ /** Handshake deadline: armed by connect(), cleared by hello.ok or close. */
1602
+ handshakeTimer = null;
1603
+ /** Idle deadline: armed by hello.ok; inbound frames and pings refresh it. */
1604
+ livenessTimer = null;
1605
+ /** Idle deadline in effect for the current socket; 0 = off. */
1606
+ livenessMs = 0;
1607
+ lastInboundAt = 0;
1422
1608
  authenticated = false;
1423
1609
  // True only when the server echoed the 'ack' capability in hello.ok.
1424
1610
  // Per-connection: reset on every close and re-negotiated on every HELLO.
1425
1611
  ackMode = false;
1426
- // Set immediately before our own close(1008, 'HELLO ack timeout') so the
1427
- // onclose handler can tell this transient self-close apart from a
1428
- // server-initiated 1008 (which is terminal — invalid credentials).
1429
- helloTimeoutClose = false;
1612
+ /** One error per long outage, then silent until a stable connection. */
1613
+ longOutageAnnounced = false;
1614
+ /** One error per run of rejected handshakes, then silent until hello.ok. */
1615
+ blockedAnnounced = false;
1430
1616
  // Bounded LRU of recently-dispatched message ids (Set iteration order is
1431
1617
  // insertion order — delete + re-add refreshes recency). Ids are added
1432
1618
  // only AFTER a successful dispatch: adding earlier would let a failed
@@ -1451,51 +1637,73 @@ var RealtimeClient = class {
1451
1637
  disposed = false;
1452
1638
  constructor(options) {
1453
1639
  const dedupCacheSize = typeof options.dedupCacheSize === "number" && Number.isFinite(options.dedupCacheSize) && options.dedupCacheSize >= 1 ? Math.floor(options.dedupCacheSize) : DEFAULT_DEDUP_CACHE_SIZE;
1640
+ const handshakeTimeoutMs = typeof options.handshakeTimeoutMs === "number" && Number.isFinite(options.handshakeTimeoutMs) && options.handshakeTimeoutMs > 0 ? options.handshakeTimeoutMs : DEFAULT_HANDSHAKE_TIMEOUT_MS;
1641
+ const livenessTimeoutMs = typeof options.livenessTimeoutMs === "number" && Number.isFinite(options.livenessTimeoutMs) && options.livenessTimeoutMs >= 0 ? options.livenessTimeoutMs : null;
1454
1642
  this.options = {
1455
1643
  baseUrl: options.baseUrl ?? "wss://api.agentchat.me",
1456
1644
  reconnect: options.reconnect ?? true,
1457
1645
  reconnectInterval: options.reconnectInterval ?? 500,
1458
1646
  maxReconnectInterval: options.maxReconnectInterval ?? 3e4,
1459
- maxReconnectAttempts: options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY,
1647
+ handshakeTimeoutMs,
1648
+ livenessTimeoutMs,
1460
1649
  apiKey: options.apiKey,
1461
1650
  client: options.client,
1462
1651
  onSequenceGap: options.onSequenceGap,
1463
1652
  autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),
1464
1653
  dedupCacheSize,
1654
+ ackOnReceipt: options.ackOnReceipt ?? false,
1465
1655
  webSocket: options.webSocket,
1466
1656
  clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY
1467
1657
  };
1468
1658
  }
1469
1659
  /**
1470
1660
  * Open the WebSocket connection and perform the HELLO handshake.
1471
- * Resolves once the socket is open and the HELLO frame has been sent —
1472
- * NOT after `hello.ok`. Listen for `onConnect()` to react to a
1473
- * completed handshake.
1661
+ * Resolves once the socket has been constructed and its handlers bound —
1662
+ * NOT after `hello.ok`. Listen for `onConnect()` or `on('state')` to react
1663
+ * to a completed handshake.
1474
1664
  *
1475
- * Safe to call on a disposed client only if you expect a fresh run —
1476
- * reinstate with a new instance instead.
1665
+ * Also the way to retry at once: called while `backoff` or `blocked`, it
1666
+ * cancels the pending timer and opens a socket now. A no-op while a socket
1667
+ * is already connecting or connected. Throws after `disconnect()` — create
1668
+ * a fresh `RealtimeClient` instead. Rejects, without retrying, when no
1669
+ * WebSocket implementation exists (neither `ws` nor a native one): that is
1670
+ * a configuration error and the client stays `idle`.
1477
1671
  */
1478
1672
  async connect() {
1479
1673
  if (this.disposed) {
1480
1674
  throw new ConnectionError("RealtimeClient has been disposed; create a new instance to reconnect.");
1481
1675
  }
1676
+ if (this.ws) return;
1677
+ this.clearReconnectTimer();
1482
1678
  let WebSocketCtor;
1483
1679
  try {
1484
1680
  WebSocketCtor = this.options.webSocket ?? await resolveWebSocket();
1485
1681
  } catch (err) {
1486
- const error = err instanceof Error ? err : new ConnectionError("Failed to resolve WebSocket");
1682
+ this.setState("idle");
1683
+ throw err instanceof Error ? err : new ConnectionError("Failed to resolve WebSocket");
1684
+ }
1685
+ if (this.disposed || this.ws) return;
1686
+ this.setState("connecting");
1687
+ const url = `${this.options.baseUrl}/v1/ws`;
1688
+ let ws;
1689
+ try {
1690
+ ws = new WebSocketCtor(url);
1691
+ } catch (err) {
1692
+ const error = err instanceof Error ? err : new ConnectionError("WebSocket constructor threw");
1487
1693
  this.emitError(error);
1488
1694
  this.scheduleReconnect();
1489
1695
  throw error;
1490
1696
  }
1491
- const url = `${this.options.baseUrl}/v1/ws`;
1492
- this.ws = new WebSocketCtor(url);
1697
+ this.ws = ws;
1493
1698
  this.authenticated = false;
1494
1699
  this.ackMode = false;
1495
- this.helloTimeoutClose = false;
1496
- this.ws.onopen = () => {
1700
+ this.livenessMs = this.options.livenessTimeoutMs ?? (isPingCapable(ws) ? DEFAULT_LIVENESS_TIMEOUT_MS : 0);
1701
+ this.armHandshakeDeadline();
1702
+ const current = () => this.ws === ws;
1703
+ ws.onopen = () => {
1704
+ if (!current()) return;
1497
1705
  try {
1498
- this.ws.send(
1706
+ ws.send(
1499
1707
  JSON.stringify({
1500
1708
  type: "hello",
1501
1709
  api_key: this.options.apiKey,
@@ -1506,18 +1714,12 @@ var RealtimeClient = class {
1506
1714
  );
1507
1715
  } catch (err) {
1508
1716
  this.emitError(err instanceof Error ? err : new ConnectionError("HELLO send failed"));
1509
- return;
1717
+ this.abandonSocket(CLIENT_CLOSE_CODE, "client HELLO send failed");
1510
1718
  }
1511
- this.helloAckTimer = setTimeout(() => {
1512
- this.emitError(new ConnectionError("HELLO ack timeout"));
1513
- this.helloTimeoutClose = true;
1514
- try {
1515
- this.ws?.close(1008, "HELLO ack timeout");
1516
- } catch {
1517
- }
1518
- }, HELLO_ACK_TIMEOUT_MS);
1519
1719
  };
1520
- this.ws.onmessage = (event) => {
1720
+ ws.onmessage = (event) => {
1721
+ if (!current()) return;
1722
+ this.touchLiveness();
1521
1723
  let message;
1522
1724
  try {
1523
1725
  message = JSON.parse(String(event.data));
@@ -1529,11 +1731,11 @@ var RealtimeClient = class {
1529
1731
  this.authenticated = true;
1530
1732
  const caps = message.capabilities;
1531
1733
  this.ackMode = Array.isArray(caps) && caps.includes("ack");
1734
+ this.clearHandshakeTimer();
1735
+ this.touchLiveness();
1532
1736
  this.startStabilityTimer();
1533
- if (this.helloAckTimer) {
1534
- clearTimeout(this.helloAckTimer);
1535
- this.helloAckTimer = null;
1536
- }
1737
+ this.blockedAnnounced = false;
1738
+ this.setState("ready");
1537
1739
  for (const handler of this.connectHandlers) {
1538
1740
  try {
1539
1741
  handler();
@@ -1551,42 +1753,42 @@ var RealtimeClient = class {
1551
1753
  return;
1552
1754
  }
1553
1755
  if (this.isMessageNew(message)) {
1756
+ if (this.options.ackOnReceipt) {
1757
+ const messageId = this.extractMessageId(message);
1758
+ if (messageId !== null) this.sendAckFrame(messageId);
1759
+ }
1554
1760
  this.processOrderedMessage(message);
1555
1761
  return;
1556
1762
  }
1763
+ if (this.isWake(message)) {
1764
+ this.dispatchWake(message);
1765
+ return;
1766
+ }
1557
1767
  this.dispatch(message);
1558
1768
  };
1559
- this.ws.onerror = () => {
1769
+ ws.onerror = () => {
1770
+ if (!current()) return;
1560
1771
  this.emitError(new ConnectionError("WebSocket error"));
1561
1772
  };
1562
- this.ws.onclose = (event) => {
1563
- if (this.helloAckTimer) {
1564
- clearTimeout(this.helloAckTimer);
1565
- this.helloAckTimer = null;
1566
- }
1567
- this.cancelStabilityTimer();
1568
- this.noteConnectionEnded();
1569
- this.authenticated = false;
1570
- this.ackMode = false;
1571
- const selfClosedForHelloTimeout = this.helloTimeoutClose;
1572
- this.helloTimeoutClose = false;
1573
- for (const handler of this.disconnectHandlers) {
1574
- try {
1575
- handler({ code: event.code, reason: event.reason, wasClean: event.wasClean });
1576
- } catch {
1577
- }
1578
- }
1579
- this.resetOrderStates();
1580
- if (TERMINAL_CLOSE_CODES.has(event.code) && !selfClosedForHelloTimeout) {
1581
- this.emitError(
1582
- new ConnectionError(
1583
- `WebSocket closed with terminal code ${event.code}${event.reason ? ` (${event.reason})` : ""}; the server rejected the session and auto-reconnect has stopped. Check the API key, then create a new RealtimeClient.`
1584
- )
1585
- );
1586
- return;
1587
- }
1588
- this.scheduleReconnect();
1773
+ ws.onclose = (event) => {
1774
+ if (!current()) return;
1775
+ this.ws = null;
1776
+ this.handleClose({
1777
+ code: event.code,
1778
+ // A polyfilled socket may omit the reason; the rejection rule
1779
+ // lowercases it, so it must be a string here.
1780
+ reason: String(event.reason ?? ""),
1781
+ wasClean: event.wasClean,
1782
+ initiator: "server"
1783
+ });
1589
1784
  };
1785
+ if (isPingCapable(ws)) {
1786
+ const alive = () => {
1787
+ if (current()) this.touchLiveness();
1788
+ };
1789
+ ws.on("ping", alive);
1790
+ ws.on("pong", alive);
1791
+ }
1590
1792
  }
1591
1793
  /**
1592
1794
  * Drain offline envelopes accumulated while the socket was disconnected.
@@ -1743,8 +1945,9 @@ var RealtimeClient = class {
1743
1945
  if (this.disposed || !this.authenticated) return;
1744
1946
  this.reconnectAttempts = 0;
1745
1947
  this.rapidReconnects = 0;
1948
+ this.longOutageAnnounced = false;
1746
1949
  }, STABLE_CONNECTION_MS);
1747
- this.stabilityTimer.unref?.();
1950
+ unref(this.stabilityTimer);
1748
1951
  }
1749
1952
  cancelStabilityTimer() {
1750
1953
  if (this.stabilityTimer) {
@@ -1756,6 +1959,8 @@ var RealtimeClient = class {
1756
1959
  * Track short-lived connections and warn once they form a pattern.
1757
1960
  * A flapping client looks healthy from the inside — every reconnect
1758
1961
  * succeeds — so without this the operator has no local signal at all.
1962
+ * The notice goes through `onError` like every other signal: an SDK
1963
+ * that runs as a guest inside a host process does not own its console.
1759
1964
  */
1760
1965
  noteConnectionEnded() {
1761
1966
  const started = this.lastConnectAt;
@@ -1767,43 +1972,252 @@ var RealtimeClient = class {
1767
1972
  }
1768
1973
  this.rapidReconnects++;
1769
1974
  if (this.rapidReconnects === INSTABILITY_WARN_THRESHOLD) {
1770
- console.warn(
1771
- `[agentchat] realtime connection is unstable: ${this.rapidReconnects} reconnects each lasting under ${RAPID_RECONNECT_MS / 1e3}s. Backing off (next retry in up to ${this.options.maxReconnectInterval / 1e3}s). This usually means the network path or a local supervisor is dropping the socket, not an AgentChat outage.`
1975
+ this.emitError(
1976
+ new ConnectionError(
1977
+ `realtime connection is unstable: ${this.rapidReconnects} consecutive connections each lasting under ${RAPID_RECONNECT_MS / 1e3}s. Backing off (next retry in up to ${this.options.maxReconnectInterval / 1e3}s). This usually means the network path or a local supervisor is dropping the socket, not an AgentChat outage.`
1978
+ )
1772
1979
  );
1773
1980
  }
1774
1981
  }
1982
+ // ─── Lifecycle: close funnel, backoff, blocked, watchdogs ───────────────
1983
+ //
1984
+ // Invariant: the client never parks itself. Every close leads to a timer
1985
+ // (backoff or blocked retry) or, with `reconnect: false`, to `idle` where
1986
+ // the application's next connect() picks up. Only disconnect() ends it.
1987
+ /**
1988
+ * The single funnel for "this socket is over", whoever ended it. Runs
1989
+ * after `this.ws` has been let go of, so nothing here touches the socket
1990
+ * again. Decides what comes next — backoff, blocked or idle, never nothing.
1991
+ */
1992
+ handleClose(info) {
1993
+ const duringHandshake = !this.authenticated;
1994
+ this.clearWatchdogs();
1995
+ this.cancelStabilityTimer();
1996
+ this.noteConnectionEnded();
1997
+ this.authenticated = false;
1998
+ this.ackMode = false;
1999
+ for (const handler of this.disconnectHandlers) {
2000
+ try {
2001
+ handler(info);
2002
+ } catch {
2003
+ }
2004
+ }
2005
+ if (this.options.ackOnReceipt) this.flushParkedFrames("connection_closed");
2006
+ this.resetOrderStates();
2007
+ if (this.disposed) return;
2008
+ if (info.initiator === "server" && duringHandshake && isAuthRejectionClose(info.code, info.reason)) {
2009
+ this.enterBlocked(info.code, info.reason);
2010
+ return;
2011
+ }
2012
+ this.scheduleReconnect();
2013
+ }
2014
+ /**
2015
+ * End the current socket on the client's own decision (a watchdog trip,
2016
+ * a HELLO that could not be sent) and move on at once, without waiting for
2017
+ * the socket's close event: on a dead pipe a polite close waits for a
2018
+ * reply that never comes. Terminated where the API allows it (Node `ws`),
2019
+ * closed otherwise; its own late events are ignored because it is no
2020
+ * longer `this.ws`.
2021
+ */
2022
+ abandonSocket(code, reason) {
2023
+ const ws = this.ws;
2024
+ if (!ws) return;
2025
+ this.ws = null;
2026
+ const terminate = ws.terminate;
2027
+ try {
2028
+ if (typeof terminate === "function") terminate.call(ws);
2029
+ else ws.close(code, reason);
2030
+ } catch {
2031
+ }
2032
+ this.handleClose({ code, reason, wasClean: false, initiator: "client" });
2033
+ }
1775
2034
  scheduleReconnect() {
1776
2035
  if (this.disposed) return;
1777
- if (!this.options.reconnect) return;
1778
- if (this.reconnectAttempts >= this.options.maxReconnectAttempts) return;
1779
2036
  if (this.reconnectTimer) return;
2037
+ if (!this.options.reconnect) {
2038
+ this.setState("idle");
2039
+ return;
2040
+ }
1780
2041
  this.reconnectAttempts++;
1781
- const delay = this.computeReconnectDelay(this.reconnectAttempts);
2042
+ const attempt = this.reconnectAttempts;
2043
+ if (attempt > LONG_OUTAGE_AFTER_ATTEMPTS && !this.longOutageAnnounced) {
2044
+ this.longOutageAnnounced = true;
2045
+ this.emitError(
2046
+ new ConnectionError(
2047
+ `still reconnecting after ${LONG_OUTAGE_AFTER_ATTEMPTS} consecutive failed attempts; backing off to at most ${Math.round(this.longOutageCap() / 1e3)}s between attempts and not giving up`
2048
+ )
2049
+ );
2050
+ }
2051
+ const delay = this.computeReconnectDelay(attempt);
2052
+ this.setState("backoff");
1782
2053
  this.reconnectTimer = setTimeout(() => {
1783
2054
  this.reconnectTimer = null;
1784
- void this.connect().catch((err) => {
1785
- this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
1786
- });
2055
+ this.retryNow();
1787
2056
  }, delay);
1788
2057
  }
2058
+ /**
2059
+ * The server rejected the credential. `blocked` is not the end: a fresh
2060
+ * HELLO goes out every AUTH_RETRY_INTERVAL_MS (jittered) until one is
2061
+ * accepted — keys get rotated back and accounts get reinstated, and the
2062
+ * running client has no other way to learn it. The first rejection of a
2063
+ * run is an error; the following ones only fire `blocked`, so an operator
2064
+ * sees one line per incident rather than one every quarter hour.
2065
+ */
2066
+ enterBlocked(code, reason) {
2067
+ const retryInMs = this.options.reconnect ? this.jittered(AUTH_RETRY_INTERVAL_MS, AUTH_RETRY_JITTER_RATIO) : null;
2068
+ this.setState("blocked");
2069
+ if (!this.blockedAnnounced) {
2070
+ this.blockedAnnounced = true;
2071
+ this.emitError(
2072
+ new ConnectionError(
2073
+ `server rejected the credential (close ${code}${reason ? ` ${reason}` : ""}); ` + (retryInMs !== null ? `retrying with a fresh HELLO in about ${Math.round(retryInMs / 6e4)} min and every 10\u201315 min after that until it is accepted again` : "reconnect is off, so call connect() to try again")
2074
+ )
2075
+ );
2076
+ }
2077
+ const info = { code, reason, retryInMs };
2078
+ for (const handler of this.blockedHandlers) {
2079
+ try {
2080
+ handler(info);
2081
+ } catch {
2082
+ }
2083
+ }
2084
+ if (retryInMs === null) return;
2085
+ this.reconnectTimer = setTimeout(() => {
2086
+ this.reconnectTimer = null;
2087
+ this.retryNow();
2088
+ }, retryInMs);
2089
+ }
2090
+ /**
2091
+ * The timer-driven attempt. connect() emits and re-arms on its own for
2092
+ * every failure it retries (a throwing constructor, a close); the one
2093
+ * failure it does not retry — no WebSocket implementation at all — left
2094
+ * nothing armed, so it is announced here: the operator should see why the
2095
+ * client went quiet.
2096
+ */
2097
+ retryNow() {
2098
+ void this.connect().catch((err) => {
2099
+ if (this.disposed || this.ws || this.reconnectTimer) return;
2100
+ this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
2101
+ });
2102
+ }
2103
+ clearReconnectTimer() {
2104
+ if (this.reconnectTimer) {
2105
+ clearTimeout(this.reconnectTimer);
2106
+ this.reconnectTimer = null;
2107
+ }
2108
+ }
1789
2109
  computeReconnectDelay(attempt) {
1790
- const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 10));
1791
- const capped = Math.min(exp, this.options.maxReconnectInterval);
1792
- const jitter = 0.75 + Math.random() * 0.5;
1793
- return Math.max(0, Math.floor(capped * jitter));
2110
+ const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 20));
2111
+ const cap = attempt > LONG_OUTAGE_AFTER_ATTEMPTS ? this.longOutageCap() : this.options.maxReconnectInterval;
2112
+ return this.jitteredBelow(Math.min(exp, cap), RECONNECT_JITTER_RATIO);
2113
+ }
2114
+ longOutageCap() {
2115
+ return Math.max(this.options.maxReconnectInterval, LONG_OUTAGE_MAX_INTERVAL_MS);
2116
+ }
2117
+ /** Symmetric ±ratio jitter around `ms` — for the blocked retry, a range (10–15 min), not a cap. */
2118
+ jittered(ms, ratio) {
2119
+ const factor = 1 - ratio + Math.random() * 2 * ratio;
2120
+ return Math.max(0, Math.floor(ms * factor));
2121
+ }
2122
+ /** Jitter in [ms × (1 − ratio), ms]: `ms` is a ceiling. Thundering-herd-safe across a fleet. */
2123
+ jitteredBelow(ms, ratio) {
2124
+ const factor = 1 - Math.random() * ratio;
2125
+ return Math.max(0, Math.floor(ms * factor));
2126
+ }
2127
+ armHandshakeDeadline() {
2128
+ this.clearHandshakeTimer();
2129
+ const ms = this.options.handshakeTimeoutMs;
2130
+ this.handshakeTimer = setTimeout(() => {
2131
+ this.handshakeTimer = null;
2132
+ this.emitError(new ConnectionError(`handshake timeout: no hello.ok within ${ms}ms`));
2133
+ this.abandonSocket(CLIENT_CLOSE_CODE, "client handshake timeout");
2134
+ }, ms);
2135
+ unref(this.handshakeTimer);
2136
+ }
2137
+ /**
2138
+ * Note proof of life (any inbound frame, or a ping/pong on a socket that
2139
+ * shows them). The timer itself is lazy: it is armed once per connection
2140
+ * and, when it fires early because traffic arrived meanwhile, re-arms for
2141
+ * the remainder — one `Date.now()` per frame instead of a timer churn.
2142
+ */
2143
+ touchLiveness() {
2144
+ this.lastInboundAt = Date.now();
2145
+ if (this.livenessTimer === null) this.armLiveness(this.livenessMs);
2146
+ }
2147
+ armLiveness(ms) {
2148
+ if (this.livenessMs <= 0 || !this.ws || !this.authenticated) return;
2149
+ this.livenessTimer = setTimeout(() => {
2150
+ this.livenessTimer = null;
2151
+ const quietFor = Date.now() - this.lastInboundAt;
2152
+ if (quietFor < this.livenessMs) {
2153
+ this.armLiveness(this.livenessMs - quietFor);
2154
+ return;
2155
+ }
2156
+ this.emitError(
2157
+ new ConnectionError(`liveness timeout: nothing received for ${this.livenessMs}ms`)
2158
+ );
2159
+ this.abandonSocket(CLIENT_CLOSE_CODE, "client liveness timeout");
2160
+ }, Math.max(1, ms));
2161
+ unref(this.livenessTimer);
2162
+ }
2163
+ clearHandshakeTimer() {
2164
+ if (this.handshakeTimer) {
2165
+ clearTimeout(this.handshakeTimer);
2166
+ this.handshakeTimer = null;
2167
+ }
2168
+ }
2169
+ clearWatchdogs() {
2170
+ this.clearHandshakeTimer();
2171
+ if (this.livenessTimer) {
2172
+ clearTimeout(this.livenessTimer);
2173
+ this.livenessTimer = null;
2174
+ }
2175
+ }
2176
+ setState(next) {
2177
+ const previous = this._state;
2178
+ if (previous === next) return;
2179
+ this._state = next;
2180
+ for (const handler of this.stateHandlers) {
2181
+ try {
2182
+ handler(next, previous);
2183
+ } catch {
2184
+ }
2185
+ }
1794
2186
  }
1795
2187
  on(event, handler) {
2188
+ switch (event) {
2189
+ case "state":
2190
+ return this.subscribe(this.stateHandlers, handler);
2191
+ case "blocked":
2192
+ return this.subscribe(this.blockedHandlers, handler);
2193
+ case "stopped":
2194
+ return this.subscribe(this.stoppedHandlers, handler);
2195
+ }
1796
2196
  let handlers = this.handlers.get(event);
1797
2197
  if (!handlers) {
1798
2198
  handlers = /* @__PURE__ */ new Set();
1799
2199
  this.handlers.set(event, handlers);
1800
2200
  }
1801
- handlers.add(handler);
2201
+ const stored = handler;
2202
+ handlers.add(stored);
1802
2203
  return () => {
1803
- handlers.delete(handler);
2204
+ handlers.delete(stored);
1804
2205
  if (handlers.size === 0) this.handlers.delete(event);
1805
2206
  };
1806
2207
  }
2208
+ subscribe(set, handler) {
2209
+ set.add(handler);
2210
+ return () => {
2211
+ set.delete(handler);
2212
+ };
2213
+ }
2214
+ /**
2215
+ * Every signal the client has for its operator comes through here:
2216
+ * transport errors, handler failures, the watchdog and backoff notices
2217
+ * (`handshake timeout`, `liveness timeout`, `still reconnecting after
2218
+ * 60 …`, `server rejected the credential …`, `connection is unstable`).
2219
+ * The SDK never writes to the console.
2220
+ */
1807
2221
  onError(handler) {
1808
2222
  this.errorHandlers.add(handler);
1809
2223
  return () => this.errorHandlers.delete(handler);
@@ -1854,38 +2268,63 @@ var RealtimeClient = class {
1854
2268
  get isConnected() {
1855
2269
  return this.authenticated && this.ws?.readyState === 1;
1856
2270
  }
2271
+ /** Where the connection lifecycle is right now. See `RealtimeState`. */
2272
+ get state() {
2273
+ return this._state;
2274
+ }
1857
2275
  /**
1858
- * Close the socket, disable auto-reconnect, and release all handlers.
1859
- * After calling this, `connect()` throws — create a fresh
1860
- * `RealtimeClient` if you want to reopen.
2276
+ * `true` when the current connection's `hello.ok` echoed the `ack`
2277
+ * capability: the server keeps each envelope `stored` until this client
2278
+ * acknowledges it. `false` before `hello.ok`, after a close, and against
2279
+ * a legacy server (which marks envelopes delivered on push).
2280
+ */
2281
+ get ackNegotiated() {
2282
+ return this.ackMode;
2283
+ }
2284
+ /**
2285
+ * Close the socket, cancel every timer, and release all handlers. The
2286
+ * only way into `stopped`, and the only way the client ever stops on
2287
+ * purpose: works from any state (`blocked` and a pending backoff
2288
+ * included). `stopped` fires once. After this, `connect()` throws —
2289
+ * create a fresh `RealtimeClient` if you want to reopen.
1861
2290
  */
1862
2291
  disconnect() {
2292
+ if (this.disposed) return;
1863
2293
  this.disposed = true;
1864
2294
  this.options.reconnect = false;
1865
- if (this.reconnectTimer) {
1866
- clearTimeout(this.reconnectTimer);
1867
- this.reconnectTimer = null;
1868
- }
1869
- if (this.helloAckTimer) {
1870
- clearTimeout(this.helloAckTimer);
1871
- this.helloAckTimer = null;
1872
- }
2295
+ this.clearReconnectTimer();
2296
+ this.clearWatchdogs();
1873
2297
  this.cancelStabilityTimer();
1874
- this.drainAllPendingForShutdown();
2298
+ this.flushParkedFrames("gap_fill_unavailable");
2299
+ const ws = this.ws;
2300
+ this.ws = null;
1875
2301
  try {
1876
- this.ws?.close();
2302
+ ws?.close(1e3, "client disconnect");
1877
2303
  } catch {
1878
2304
  }
1879
- this.ws = null;
1880
2305
  this.authenticated = false;
2306
+ this.ackMode = false;
2307
+ this.setState("stopped");
2308
+ for (const handler of this.stoppedHandlers) {
2309
+ try {
2310
+ handler();
2311
+ } catch {
2312
+ }
2313
+ }
1881
2314
  this.handlers.clear();
1882
2315
  this.errorHandlers.clear();
1883
2316
  this.connectHandlers.clear();
1884
2317
  this.disconnectHandlers.clear();
2318
+ this.stateHandlers.clear();
2319
+ this.blockedHandlers.clear();
2320
+ this.stoppedHandlers.clear();
1885
2321
  }
1886
2322
  emitError(error) {
1887
2323
  for (const handler of this.errorHandlers) {
1888
- handler(error);
2324
+ try {
2325
+ handler(error);
2326
+ } catch {
2327
+ }
1889
2328
  }
1890
2329
  }
1891
2330
  dispatch(message) {
@@ -1926,10 +2365,11 @@ var RealtimeClient = class {
1926
2365
  dispatchMessageNew(message) {
1927
2366
  const isDrainRow = this.restDrainOrigin.has(message);
1928
2367
  const messageId = this.extractMessageId(message);
2368
+ const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt;
1929
2369
  let settlement;
1930
2370
  if (messageId !== null && this.dedupHit(messageId)) {
1931
2371
  settlement = Promise.resolve(true);
1932
- if (!isDrainRow) this.sendAckFrame(messageId);
2372
+ if (ackAfterDispatch) this.sendAckFrame(messageId);
1933
2373
  } else {
1934
2374
  const handlers = this.handlers.get("message.new");
1935
2375
  const pending = [];
@@ -1954,7 +2394,7 @@ var RealtimeClient = class {
1954
2394
  if (!ok) return false;
1955
2395
  if (messageId !== null) {
1956
2396
  this.dedupAdd(messageId);
1957
- if (!isDrainRow) this.sendAckFrame(messageId);
2397
+ if (ackAfterDispatch) this.sendAckFrame(messageId);
1958
2398
  }
1959
2399
  return true;
1960
2400
  });
@@ -2002,12 +2442,45 @@ var RealtimeClient = class {
2002
2442
  isMessageNew(message) {
2003
2443
  return message.type === "message.new";
2004
2444
  }
2445
+ isWake(message) {
2446
+ return message.type === "wake";
2447
+ }
2448
+ /**
2449
+ * A `wake` frame is a content-free signal: validate the payload shape
2450
+ * (so `wake` handlers can trust the `WakeFrame` type), then dispatch. A
2451
+ * frame the server sent malformed is surfaced through `onError` rather
2452
+ * than handed to handlers as something it is not. Never acked — there is
2453
+ * no message to deliver.
2454
+ */
2455
+ dispatchWake(message) {
2456
+ const payload = message.payload;
2457
+ const reason = this.wakePayloadProblem(payload);
2458
+ if (reason !== null) {
2459
+ this.emitError(new ConnectionError(`wake frame failed validation: ${reason}`));
2460
+ return;
2461
+ }
2462
+ this.dispatch(message);
2463
+ }
2464
+ wakePayloadProblem(payload) {
2465
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
2466
+ return "payload is not an object";
2467
+ }
2468
+ const p = payload;
2469
+ for (const key of ["reason", "conversation_id", "anchor_message_id", "at"]) {
2470
+ if (typeof p[key] !== "string" || p[key] === "") return `${key} is not a non-empty string`;
2471
+ }
2472
+ if (typeof p.step !== "number" || !Number.isInteger(p.step)) return "step is not an integer";
2473
+ return null;
2474
+ }
2005
2475
  // ─── Per-conversation seq ordering ───────────────────────────────────────
2006
2476
  //
2007
2477
  // Invariant: for any conversation_id, handlers see message.new envelopes
2008
- // strictly in seq-ascending order with no skipped or repeated seqs (modulo
2009
- // the gap-fill failure path, where we surface the incident via
2010
- // onSequenceGap and continue forward).
2478
+ // in seq-ascending order with no skipped or repeated seqs — except that a
2479
+ // frame older than this connection's anchor (a stored row the drain brings
2480
+ // after a live frame anchored the conversation, or a seq a failed gap-fill
2481
+ // skipped) is dispatched late rather than dropped: never lost beats
2482
+ // strictly ordered, since the ack would otherwise bury it for good. The
2483
+ // dedup cache alone decides what is a repeat.
2011
2484
  //
2012
2485
  // Why per-conversation instead of global: seq numbers are minted per
2013
2486
  // conversation by send_message_atomic, so cross-conversation arrivals
@@ -2031,6 +2504,7 @@ var RealtimeClient = class {
2031
2504
  return;
2032
2505
  }
2033
2506
  if (seq < state.nextExpectedSeq) {
2507
+ this.dispatch(message);
2034
2508
  return;
2035
2509
  }
2036
2510
  if (seq === state.nextExpectedSeq) {
@@ -2104,10 +2578,15 @@ var RealtimeClient = class {
2104
2578
  const rowSeq = typeof row.seq === "number" ? row.seq : null;
2105
2579
  if (rowSeq === null || rowSeq < expectedSeq) continue;
2106
2580
  if (state.buffer.has(rowSeq)) continue;
2107
- state.buffer.set(rowSeq, {
2581
+ const envelope = {
2108
2582
  type: "message.new",
2109
2583
  payload: row
2110
- });
2584
+ };
2585
+ if (this.options.ackOnReceipt) {
2586
+ const messageId = this.extractMessageId(envelope);
2587
+ if (messageId !== null) this.sendAckFrame(messageId);
2588
+ }
2589
+ state.buffer.set(rowSeq, envelope);
2111
2590
  }
2112
2591
  const drainedThroughGap = this.drainConsecutive(conversationId, state);
2113
2592
  if (drainedThroughGap) {
@@ -2222,7 +2701,11 @@ var RealtimeClient = class {
2222
2701
  }
2223
2702
  this.orderStates.clear();
2224
2703
  }
2225
- drainAllPendingForShutdown() {
2704
+ // Hand every parked frame to the handlers in seq order per conversation,
2705
+ // cancel the gap timers and clear the ordering state. Used when frames
2706
+ // must not be dropped: on disconnect() (the caller is leaving) and, under
2707
+ // ackOnReceipt, on every socket close (the frames are already acked).
2708
+ flushParkedFrames(reason) {
2226
2709
  for (const [conversationId, state] of this.orderStates) {
2227
2710
  if (state.gapTimer !== null) {
2228
2711
  clearTimeout(state.gapTimer);
@@ -2238,13 +2721,268 @@ var RealtimeClient = class {
2238
2721
  bufferedSeq: seqs[0] ?? null,
2239
2722
  gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,
2240
2723
  recovered: false,
2241
- reason: "gap_fill_unavailable"
2724
+ reason
2242
2725
  });
2243
2726
  }
2244
2727
  this.orderStates.clear();
2245
2728
  }
2246
2729
  };
2247
2730
 
2731
+ // src/gate.ts
2732
+ var gate_exports = {};
2733
+ __export(gate_exports, {
2734
+ BARE_TOOL_NAMER: () => BARE_TOOL_NAMER,
2735
+ anchorOf: () => anchorOf,
2736
+ buildPrompt: () => buildPrompt,
2737
+ canonicalJson: () => canonicalJson,
2738
+ cardsOf: () => cardsOf,
2739
+ mcpToolNamer: () => mcpToolNamer,
2740
+ normalizeDecision: () => normalizeDecision,
2741
+ parseVerdicts: () => parseVerdicts,
2742
+ run: () => run
2743
+ });
2744
+ var BARE_TOOL_NAMER = (tool) => tool;
2745
+ function mcpToolNamer(serverName) {
2746
+ return (tool) => `mcp__${serverName}__${tool}`;
2747
+ }
2748
+ var HOSTED_TOOL_TOKEN = /\bagentchat_[a-z0-9_]+\b/g;
2749
+ var DECIDE_TOOL = "agentchat_decide";
2750
+ var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "respond", "answer", "yes", "true"]);
2751
+ var DISMISS_TOKENS = /* @__PURE__ */ new Set([
2752
+ "dismiss",
2753
+ "dismissed",
2754
+ "no_reply",
2755
+ "no-reply",
2756
+ "noreply",
2757
+ "silent",
2758
+ "silence",
2759
+ "skip",
2760
+ "ignore",
2761
+ "no",
2762
+ "false"
2763
+ ]);
2764
+ var DEFER_TOKENS = /* @__PURE__ */ new Set(["defer", "deferred", "later", "wait", "postpone"]);
2765
+ var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
2766
+ function cardsOf(tray) {
2767
+ const raw = tray.conversations;
2768
+ if (!Array.isArray(raw)) return [];
2769
+ return raw.filter(
2770
+ (card) => typeof card === "object" && card !== null && !Array.isArray(card) && typeof card.conversation_id === "string" && card.conversation_id.length > 0
2771
+ );
2772
+ }
2773
+ function categoriesOf(tray) {
2774
+ const raw = tray.categories;
2775
+ if (!Array.isArray(raw)) return [];
2776
+ return raw.filter((item) => typeof item === "string" && item.length > 0);
2777
+ }
2778
+ function anchorOf(card) {
2779
+ const preview = card.preview?.message_id;
2780
+ if (typeof preview === "string" && preview.length > 0) return preview;
2781
+ const last = card.last_message_id;
2782
+ if (typeof last === "string" && last.length > 0) return last;
2783
+ return void 0;
2784
+ }
2785
+ function canonicalJson(value) {
2786
+ return JSON.stringify(sortKeysDeep(value), null, 2);
2787
+ }
2788
+ function sortKeysDeep(value) {
2789
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
2790
+ if (typeof value === "object" && value !== null) {
2791
+ const source = value;
2792
+ const out = {};
2793
+ for (const key of Object.keys(source).sort()) {
2794
+ if (source[key] !== void 0) out[key] = sortKeysDeep(source[key]);
2795
+ }
2796
+ return out;
2797
+ }
2798
+ return value;
2799
+ }
2800
+ function buildPrompt(tray, options) {
2801
+ const question = tray.question;
2802
+ if (typeof question !== "string" || question.trim().length === 0) {
2803
+ throw new Error("gate: tray carries no question");
2804
+ }
2805
+ const namer = options?.toolNamer ?? BARE_TOOL_NAMER;
2806
+ const cards = cardsOf(tray);
2807
+ const categories = categoriesOf(tray);
2808
+ const sections = [];
2809
+ sections.push(
2810
+ `You are triaging your AgentChat tray before any turn starts. This call has NO tools: do not call ${namer(DECIDE_TOOL)}, do not open or send anything, and do not write a reply. Answer the question below for every card, in JSON only; the host records your verdicts from that JSON. Where the question says to record a verdict or to send, that happens later: for each conversation you mark "reply", a turn will be started in which you open it and reply.`
2811
+ );
2812
+ sections.push(question.trim().replace(HOSTED_TOOL_TOKEN, (token) => namer(token)));
2813
+ if (categories.length > 0) {
2814
+ sections.push(`Categories: ${categories.join(", ")}`);
2815
+ }
2816
+ const you = typeof tray.you === "string" && tray.you.length > 0 ? `You are ${tray.you}. ` : "";
2817
+ const count = cards.length;
2818
+ sections.push(
2819
+ `${you}Your tray, as the server built it: ${count} conversation${count === 1 ? "" : "s"}.`
2820
+ );
2821
+ cards.forEach((card, index) => {
2822
+ sections.push(`Card ${index + 1} of ${count}
2823
+ ${canonicalJson(card)}`);
2824
+ });
2825
+ let shape = '{"decisions": [{"conversation_id": "<conversation_id from a card>", "decision": "reply" | "dismiss" | "defer"';
2826
+ if (categories.length > 0) {
2827
+ shape += `, "category": "<one of: ${categories.join(", ")}>"`;
2828
+ }
2829
+ shape += "}]}";
2830
+ sections.push(
2831
+ "Answer with ONLY a JSON object, no prose and no code fences, in this shape: " + shape + " \u2014 one entry per card, every card decided."
2832
+ );
2833
+ return sections.join("\n\n");
2834
+ }
2835
+ function parseVerdicts(text, tray) {
2836
+ const raw = extractJson(text);
2837
+ if (raw === null) return null;
2838
+ let parsed;
2839
+ try {
2840
+ parsed = JSON.parse(raw);
2841
+ } catch {
2842
+ return null;
2843
+ }
2844
+ let items;
2845
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
2846
+ const record = parsed;
2847
+ items = record.decisions ?? record.verdicts;
2848
+ if (items === void 0 && "conversation_id" in record) items = [record];
2849
+ } else {
2850
+ items = parsed;
2851
+ }
2852
+ if (!Array.isArray(items)) return null;
2853
+ const known = new Set(cardsOf(tray).map((card) => card.conversation_id));
2854
+ const allowed = new Set(categoriesOf(tray).map((c) => c.toLowerCase()));
2855
+ const seen = /* @__PURE__ */ new Set();
2856
+ const out = [];
2857
+ for (const item of items) {
2858
+ if (typeof item !== "object" || item === null || Array.isArray(item)) continue;
2859
+ const entry = item;
2860
+ const id = entry.conversation_id;
2861
+ if (typeof id !== "string" || !known.has(id) || seen.has(id)) continue;
2862
+ const decision = normalizeDecision(entry.decision);
2863
+ if (decision === null) continue;
2864
+ seen.add(id);
2865
+ out.push({
2866
+ conversation_id: id,
2867
+ decision,
2868
+ category: normalizeCategory(entry.category, allowed)
2869
+ });
2870
+ }
2871
+ return out;
2872
+ }
2873
+ function extractJson(text) {
2874
+ if (typeof text !== "string" || text.trim().length === 0) return null;
2875
+ let s = text.trim();
2876
+ const fence = FENCE_RE.exec(s);
2877
+ if (fence?.[1]) s = fence[1].trim();
2878
+ const starts = [s.indexOf("{"), s.indexOf("[")].filter((i) => i !== -1);
2879
+ if (starts.length === 0) return null;
2880
+ const start = Math.min(...starts);
2881
+ const closer = s[start] === "{" ? "}" : "]";
2882
+ const end = s.lastIndexOf(closer);
2883
+ if (end <= start) return null;
2884
+ return s.slice(start, end + 1);
2885
+ }
2886
+ function normalizeDecision(value) {
2887
+ if (typeof value !== "string") return null;
2888
+ const token = value.trim().toLowerCase().replace(/\s+/g, "_");
2889
+ if (REPLY_TOKENS.has(token)) return "reply";
2890
+ if (DISMISS_TOKENS.has(token)) return "dismiss";
2891
+ if (DEFER_TOKENS.has(token)) return "defer";
2892
+ return null;
2893
+ }
2894
+ function normalizeCategory(value, allowed) {
2895
+ if (allowed.size === 0 || typeof value !== "string") return null;
2896
+ const token = value.trim().toLowerCase();
2897
+ return allowed.has(token) ? token : null;
2898
+ }
2899
+ async function run(options) {
2900
+ const cards = cardsOf(options.tray);
2901
+ const ids = cards.map((card) => card.conversation_id);
2902
+ if (ids.length === 0) return emptyResult("empty", [], null);
2903
+ let text;
2904
+ try {
2905
+ const prompt = buildPrompt(options.tray, { toolNamer: options.toolNamer });
2906
+ text = await options.callModel(prompt);
2907
+ } catch (err) {
2908
+ return emptyResult("fail_closed", ids, `model call failed: ${describe(err)}`);
2909
+ }
2910
+ const verdicts = parseVerdicts(text, options.tray);
2911
+ if (verdicts === null || verdicts.length === 0) {
2912
+ return emptyResult("fail_closed", ids, "no usable verdicts in the answer");
2913
+ }
2914
+ const byId = new Map(cards.map((card) => [card.conversation_id, card]));
2915
+ const decided = new Set(verdicts.map((v) => v.conversation_id));
2916
+ const reply = [];
2917
+ const recordFailures = [];
2918
+ let recorded = 0;
2919
+ for (const verdict of verdicts) {
2920
+ const card = byId.get(verdict.conversation_id);
2921
+ if (!card) continue;
2922
+ if (verdict.decision === "reply") {
2923
+ reply.push(deferredReply(options.client, card, verdict.category));
2924
+ continue;
2925
+ }
2926
+ try {
2927
+ await options.client.decisions.record(verdict.conversation_id, {
2928
+ decision: verdict.decision,
2929
+ category: verdict.category ?? void 0,
2930
+ throughMessageId: anchorOf(card)
2931
+ });
2932
+ recorded += 1;
2933
+ } catch (err) {
2934
+ recordFailures.push({ conversation_id: verdict.conversation_id, error: toError2(err) });
2935
+ }
2936
+ }
2937
+ return {
2938
+ outcome: "decided",
2939
+ reply,
2940
+ verdicts,
2941
+ undecided: ids.filter((id) => !decided.has(id)),
2942
+ recorded,
2943
+ recordFailures,
2944
+ failure: null
2945
+ };
2946
+ }
2947
+ function deferredReply(client, card, category) {
2948
+ let inFlight = null;
2949
+ return {
2950
+ conversationId: card.conversation_id,
2951
+ card,
2952
+ category,
2953
+ record: () => {
2954
+ if (inFlight === null) {
2955
+ inFlight = client.decisions.record(card.conversation_id, {
2956
+ decision: "reply",
2957
+ category: category ?? void 0,
2958
+ throughMessageId: anchorOf(card)
2959
+ }).catch((err) => {
2960
+ inFlight = null;
2961
+ throw err;
2962
+ });
2963
+ }
2964
+ return inFlight;
2965
+ }
2966
+ };
2967
+ }
2968
+ function emptyResult(outcome, undecided, failure) {
2969
+ return {
2970
+ outcome,
2971
+ reply: [],
2972
+ verdicts: [],
2973
+ undecided,
2974
+ recorded: 0,
2975
+ recordFailures: [],
2976
+ failure
2977
+ };
2978
+ }
2979
+ function toError2(err) {
2980
+ return err instanceof Error ? err : new Error(String(err));
2981
+ }
2982
+ function describe(err) {
2983
+ return err instanceof Error ? err.message : String(err);
2984
+ }
2985
+
2248
2986
  // src/render.ts
2249
2987
  var SEC = 1e3;
2250
2988
  var MIN = 60 * SEC;
@@ -2296,6 +3034,11 @@ function renderMessageContext(message, opts = {}) {
2296
3034
  return lines.join("\n");
2297
3035
  }
2298
3036
 
3037
+ // src/types/inbox-tray.ts
3038
+ var INBOX_TRAY_DEFAULT_LIMIT = 20;
3039
+ var INBOX_TRAY_MAX_LIMIT = 50;
3040
+ var INBOX_WAIT_MAX_MS = 5e4;
3041
+
2299
3042
  // src/types/attachment.ts
2300
3043
  var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
2301
3044
  var ALLOWED_ATTACHMENT_MIME = [
@@ -2315,6 +3058,6 @@ var ALLOWED_ATTACHMENT_MIME = [
2315
3058
  "video/webm"
2316
3059
  ];
2317
3060
 
2318
- export { ALLOWED_ATTACHMENT_MIME, AgentChatClient, AgentChatError, AwaitingReplyError, BlockedError, ConnectionError, DEFAULT_RETRY_POLICY, ErrorCode, ForbiddenError, GroupDeletedError, HttpTransport, MAX_ATTACHMENT_SIZE, NotFoundError, RateLimitedError, RealtimeClient, RecipientBackloggedError, RestrictedError, ServerError, SuspendedError, UnauthorizedError, VERSION, ValidationError, createAgentChatError, paginate, parseRetryAfter, renderMessageContext };
3061
+ export { ALLOWED_ATTACHMENT_MIME, AgentChatClient, AgentChatError, AwaitingReplyError, BlockedError, ConnectionError, DEFAULT_RETRY_POLICY, EmailExhaustedError, EmailLimitReachedError, ErrorCode, ForbiddenError, GroupDeletedError, HandleRequiredError, HttpTransport, INBOX_TRAY_DEFAULT_LIMIT, INBOX_TRAY_MAX_LIMIT, INBOX_WAIT_MAX_MS, MAX_ATTACHMENT_SIZE, NotFoundError, RateLimitedError, RealtimeClient, RecipientBackloggedError, RestrictedError, ServerError, SuspendedError, UnauthorizedError, VERSION, ValidationError, createAgentChatError, gate_exports as gate, isAuthRejectionClose, paginate, parseRetryAfter, renderMessageContext };
2319
3062
  //# sourceMappingURL=index.js.map
2320
3063
  //# sourceMappingURL=index.js.map