agentchatme 1.1.1 → 1.2.1

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",
@@ -268,7 +274,7 @@ function createAgentChatError(body, status, headers) {
268
274
  }
269
275
 
270
276
  // src/version.ts
271
- var VERSION = "1.1.1" ;
277
+ var VERSION = "1.2.1" ;
272
278
 
273
279
  // src/runtime.ts
274
280
  function detectRuntime() {
@@ -645,10 +651,19 @@ function generateClientMsgId() {
645
651
  }
646
652
  return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
647
653
  }
654
+ var INBOX_WAIT_TIMEOUT_GRACE_MS = 1e4;
648
655
  var AgentChatClient = class _AgentChatClient {
649
656
  http;
650
657
  onBacklogWarning;
651
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;
652
667
  constructor(options) {
653
668
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
654
669
  this.http = new HttpTransport({
@@ -661,6 +676,53 @@ var AgentChatClient = class _AgentChatClient {
661
676
  defaultHeaders: clientIdentityHeaders(options.clientIdentity)
662
677
  });
663
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);
664
726
  }
665
727
  // ─── Internal request helpers ─────────────────────────────────────────────
666
728
  async get(path, opts) {
@@ -1426,33 +1488,60 @@ var AgentChatClient = class _AgentChatClient {
1426
1488
  };
1427
1489
 
1428
1490
  // src/ws-resolver.ts
1429
- 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
+ }
1430
1503
  async function resolveWebSocket() {
1431
- if (cached) return cached;
1432
1504
  const native = globalThis.WebSocket;
1433
- if (native) {
1434
- cached = native;
1435
- return native;
1436
- }
1505
+ if (!isNode() && native) return native;
1506
+ let wsFailure;
1437
1507
  try {
1438
- const mod = await import('ws');
1439
- const ctor = mod.default ?? mod.WebSocket;
1440
- if (!ctor) {
1441
- throw new Error("The `ws` package loaded but did not export a WebSocket constructor.");
1442
- }
1443
- cached = ctor;
1444
- return ctor;
1508
+ return await importWs();
1445
1509
  } catch (err) {
1446
- const reason = err instanceof Error ? err.message : String(err);
1447
- throw new Error(
1448
- `AgentChat SDK: no WebSocket implementation available. ${reason}
1449
- Install the \`ws\` package if you're on Node 20 (Node 22+ has a native WebSocket).`
1450
- );
1451
- }
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
+ );
1452
1518
  }
1453
1519
 
1454
1520
  // src/realtime.ts
1455
- 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
+ }
1456
1545
  var STABLE_CONNECTION_MS = 3e4;
1457
1546
  var RAPID_RECONNECT_MS = 6e4;
1458
1547
  var INSTABILITY_WARN_THRESHOLD = 5;
@@ -1461,7 +1550,6 @@ var MAX_BUFFERED_PER_CONVERSATION = 500;
1461
1550
  var GAP_FILL_LIMIT = 200;
1462
1551
  var SYNC_DRAIN_PAGE_SIZE = 200;
1463
1552
  var DEFAULT_DEDUP_CACHE_SIZE = 2048;
1464
- var TERMINAL_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401, 4403]);
1465
1553
  function isValidSyncRow(row) {
1466
1554
  if (typeof row !== "object" || row === null || Array.isArray(row)) return false;
1467
1555
  const r = row;
@@ -1496,6 +1584,11 @@ var RealtimeClient = class {
1496
1584
  errorHandlers = /* @__PURE__ */ new Set();
1497
1585
  connectHandlers = /* @__PURE__ */ new Set();
1498
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. */
1499
1592
  reconnectAttempts = 0;
1500
1593
  /** Clears reconnectAttempts once this connection proves itself stable. */
1501
1594
  stabilityTimer = null;
@@ -1503,21 +1596,43 @@ var RealtimeClient = class {
1503
1596
  * the operator warning only; backoff itself uses reconnectAttempts. */
1504
1597
  rapidReconnects = 0;
1505
1598
  lastConnectAt = null;
1599
+ /** The pending backoff or blocked-retry timer — at most one at a time. */
1506
1600
  reconnectTimer = null;
1507
- 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;
1508
1608
  authenticated = false;
1509
1609
  // True only when the server echoed the 'ack' capability in hello.ok.
1510
1610
  // Per-connection: reset on every close and re-negotiated on every HELLO.
1511
1611
  ackMode = false;
1512
- // Set immediately before our own close(1008, 'HELLO ack timeout') so the
1513
- // onclose handler can tell this transient self-close apart from a
1514
- // server-initiated 1008 (which is terminal — invalid credentials).
1515
- 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;
1516
1616
  // Bounded LRU of recently-dispatched message ids (Set iteration order is
1517
1617
  // insertion order — delete + re-add refreshes recency). Ids are added
1518
1618
  // only AFTER a successful dispatch: adding earlier would let a failed
1519
1619
  // dispatch suppress its own redelivery.
1520
1620
  dedupSeen = /* @__PURE__ */ new Set();
1621
+ // Dispatches still running, by message id. A second copy of an id that is
1622
+ // here on the same connection (the server's reconnect backlog and the REST
1623
+ // drain bring the same stored rows; a slow handler is still on the first)
1624
+ // is not handed to the handlers again: it takes the first copy's outcome,
1625
+ // and nothing ever waits for it. An entry lives exactly as long as its
1626
+ // handlers run, so the map is bounded by the dispatches in flight.
1627
+ inFlight = /* @__PURE__ */ new Map();
1628
+ // Drain rows that adopted an in-flight copy instead of being dispatched.
1629
+ // The cursor reads that copy's outcome; it never waits for it.
1630
+ drainAdopted = /* @__PURE__ */ new WeakMap();
1631
+ // Bumped on every socket close. Copies adopt an in-flight first copy only
1632
+ // on the same connection; a re-offer on a later one is dispatched afresh
1633
+ // even while the first copy runs (a handler that never finishes must not
1634
+ // swallow every re-offer).
1635
+ generation = 0;
1521
1636
  // Envelopes injected by the REST drain, as opposed to live WS frames.
1522
1637
  // Drain rows are acknowledged via the REST sync/ack cursor, never via a
1523
1638
  // WS ack frame; everything else on the message.new pipeline (live frames,
@@ -1537,51 +1652,73 @@ var RealtimeClient = class {
1537
1652
  disposed = false;
1538
1653
  constructor(options) {
1539
1654
  const dedupCacheSize = typeof options.dedupCacheSize === "number" && Number.isFinite(options.dedupCacheSize) && options.dedupCacheSize >= 1 ? Math.floor(options.dedupCacheSize) : DEFAULT_DEDUP_CACHE_SIZE;
1655
+ const handshakeTimeoutMs = typeof options.handshakeTimeoutMs === "number" && Number.isFinite(options.handshakeTimeoutMs) && options.handshakeTimeoutMs > 0 ? options.handshakeTimeoutMs : DEFAULT_HANDSHAKE_TIMEOUT_MS;
1656
+ const livenessTimeoutMs = typeof options.livenessTimeoutMs === "number" && Number.isFinite(options.livenessTimeoutMs) && options.livenessTimeoutMs >= 0 ? options.livenessTimeoutMs : null;
1540
1657
  this.options = {
1541
1658
  baseUrl: options.baseUrl ?? "wss://api.agentchat.me",
1542
1659
  reconnect: options.reconnect ?? true,
1543
1660
  reconnectInterval: options.reconnectInterval ?? 500,
1544
1661
  maxReconnectInterval: options.maxReconnectInterval ?? 3e4,
1545
- maxReconnectAttempts: options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY,
1662
+ handshakeTimeoutMs,
1663
+ livenessTimeoutMs,
1546
1664
  apiKey: options.apiKey,
1547
1665
  client: options.client,
1548
1666
  onSequenceGap: options.onSequenceGap,
1549
1667
  autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),
1550
1668
  dedupCacheSize,
1669
+ ackOnReceipt: options.ackOnReceipt ?? false,
1551
1670
  webSocket: options.webSocket,
1552
1671
  clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY
1553
1672
  };
1554
1673
  }
1555
1674
  /**
1556
1675
  * Open the WebSocket connection and perform the HELLO handshake.
1557
- * Resolves once the socket is open and the HELLO frame has been sent —
1558
- * NOT after `hello.ok`. Listen for `onConnect()` to react to a
1559
- * completed handshake.
1676
+ * Resolves once the socket has been constructed and its handlers bound —
1677
+ * NOT after `hello.ok`. Listen for `onConnect()` or `on('state')` to react
1678
+ * to a completed handshake.
1560
1679
  *
1561
- * Safe to call on a disposed client only if you expect a fresh run —
1562
- * reinstate with a new instance instead.
1680
+ * Also the way to retry at once: called while `backoff` or `blocked`, it
1681
+ * cancels the pending timer and opens a socket now. A no-op while a socket
1682
+ * is already connecting or connected. Throws after `disconnect()` — create
1683
+ * a fresh `RealtimeClient` instead. Rejects, without retrying, when no
1684
+ * WebSocket implementation exists (neither `ws` nor a native one): that is
1685
+ * a configuration error and the client stays `idle`.
1563
1686
  */
1564
1687
  async connect() {
1565
1688
  if (this.disposed) {
1566
1689
  throw new ConnectionError("RealtimeClient has been disposed; create a new instance to reconnect.");
1567
1690
  }
1691
+ if (this.ws) return;
1692
+ this.clearReconnectTimer();
1568
1693
  let WebSocketCtor;
1569
1694
  try {
1570
1695
  WebSocketCtor = this.options.webSocket ?? await resolveWebSocket();
1571
1696
  } catch (err) {
1572
- const error = err instanceof Error ? err : new ConnectionError("Failed to resolve WebSocket");
1697
+ this.setState("idle");
1698
+ throw err instanceof Error ? err : new ConnectionError("Failed to resolve WebSocket");
1699
+ }
1700
+ if (this.disposed || this.ws) return;
1701
+ this.setState("connecting");
1702
+ const url = `${this.options.baseUrl}/v1/ws`;
1703
+ let ws;
1704
+ try {
1705
+ ws = new WebSocketCtor(url);
1706
+ } catch (err) {
1707
+ const error = err instanceof Error ? err : new ConnectionError("WebSocket constructor threw");
1573
1708
  this.emitError(error);
1574
1709
  this.scheduleReconnect();
1575
1710
  throw error;
1576
1711
  }
1577
- const url = `${this.options.baseUrl}/v1/ws`;
1578
- this.ws = new WebSocketCtor(url);
1712
+ this.ws = ws;
1579
1713
  this.authenticated = false;
1580
1714
  this.ackMode = false;
1581
- this.helloTimeoutClose = false;
1582
- this.ws.onopen = () => {
1715
+ this.livenessMs = this.options.livenessTimeoutMs ?? (isPingCapable(ws) ? DEFAULT_LIVENESS_TIMEOUT_MS : 0);
1716
+ this.armHandshakeDeadline();
1717
+ const current = () => this.ws === ws;
1718
+ ws.onopen = () => {
1719
+ if (!current()) return;
1583
1720
  try {
1584
- this.ws.send(
1721
+ ws.send(
1585
1722
  JSON.stringify({
1586
1723
  type: "hello",
1587
1724
  api_key: this.options.apiKey,
@@ -1592,18 +1729,12 @@ var RealtimeClient = class {
1592
1729
  );
1593
1730
  } catch (err) {
1594
1731
  this.emitError(err instanceof Error ? err : new ConnectionError("HELLO send failed"));
1595
- return;
1732
+ this.abandonSocket(CLIENT_CLOSE_CODE, "client HELLO send failed");
1596
1733
  }
1597
- this.helloAckTimer = setTimeout(() => {
1598
- this.emitError(new ConnectionError("HELLO ack timeout"));
1599
- this.helloTimeoutClose = true;
1600
- try {
1601
- this.ws?.close(1008, "HELLO ack timeout");
1602
- } catch {
1603
- }
1604
- }, HELLO_ACK_TIMEOUT_MS);
1605
1734
  };
1606
- this.ws.onmessage = (event) => {
1735
+ ws.onmessage = (event) => {
1736
+ if (!current()) return;
1737
+ this.touchLiveness();
1607
1738
  let message;
1608
1739
  try {
1609
1740
  message = JSON.parse(String(event.data));
@@ -1615,11 +1746,11 @@ var RealtimeClient = class {
1615
1746
  this.authenticated = true;
1616
1747
  const caps = message.capabilities;
1617
1748
  this.ackMode = Array.isArray(caps) && caps.includes("ack");
1749
+ this.clearHandshakeTimer();
1750
+ this.touchLiveness();
1618
1751
  this.startStabilityTimer();
1619
- if (this.helloAckTimer) {
1620
- clearTimeout(this.helloAckTimer);
1621
- this.helloAckTimer = null;
1622
- }
1752
+ this.blockedAnnounced = false;
1753
+ this.setState("ready");
1623
1754
  for (const handler of this.connectHandlers) {
1624
1755
  try {
1625
1756
  handler();
@@ -1637,42 +1768,42 @@ var RealtimeClient = class {
1637
1768
  return;
1638
1769
  }
1639
1770
  if (this.isMessageNew(message)) {
1771
+ if (this.options.ackOnReceipt) {
1772
+ const messageId = this.extractMessageId(message);
1773
+ if (messageId !== null) this.sendAckFrame(messageId);
1774
+ }
1640
1775
  this.processOrderedMessage(message);
1641
1776
  return;
1642
1777
  }
1778
+ if (this.isWake(message)) {
1779
+ this.dispatchWake(message);
1780
+ return;
1781
+ }
1643
1782
  this.dispatch(message);
1644
1783
  };
1645
- this.ws.onerror = () => {
1784
+ ws.onerror = () => {
1785
+ if (!current()) return;
1646
1786
  this.emitError(new ConnectionError("WebSocket error"));
1647
1787
  };
1648
- this.ws.onclose = (event) => {
1649
- if (this.helloAckTimer) {
1650
- clearTimeout(this.helloAckTimer);
1651
- this.helloAckTimer = null;
1652
- }
1653
- this.cancelStabilityTimer();
1654
- this.noteConnectionEnded();
1655
- this.authenticated = false;
1656
- this.ackMode = false;
1657
- const selfClosedForHelloTimeout = this.helloTimeoutClose;
1658
- this.helloTimeoutClose = false;
1659
- for (const handler of this.disconnectHandlers) {
1660
- try {
1661
- handler({ code: event.code, reason: event.reason, wasClean: event.wasClean });
1662
- } catch {
1663
- }
1664
- }
1665
- this.resetOrderStates();
1666
- if (TERMINAL_CLOSE_CODES.has(event.code) && !selfClosedForHelloTimeout) {
1667
- this.emitError(
1668
- new ConnectionError(
1669
- `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.`
1670
- )
1671
- );
1672
- return;
1673
- }
1674
- this.scheduleReconnect();
1788
+ ws.onclose = (event) => {
1789
+ if (!current()) return;
1790
+ this.ws = null;
1791
+ this.handleClose({
1792
+ code: event.code,
1793
+ // A polyfilled socket may omit the reason; the rejection rule
1794
+ // lowercases it, so it must be a string here.
1795
+ reason: String(event.reason ?? ""),
1796
+ wasClean: event.wasClean,
1797
+ initiator: "server"
1798
+ });
1675
1799
  };
1800
+ if (isPingCapable(ws)) {
1801
+ const alive = () => {
1802
+ if (current()) this.touchLiveness();
1803
+ };
1804
+ ws.on("ping", alive);
1805
+ ws.on("pong", alive);
1806
+ }
1676
1807
  }
1677
1808
  /**
1678
1809
  * Drain offline envelopes accumulated while the socket was disconnected.
@@ -1690,17 +1821,26 @@ var RealtimeClient = class {
1690
1821
  * Correctness rules, in cursor order:
1691
1822
  * - A row failing minimal validation stops the drain: the clean prefix
1692
1823
  * before it is processed and acked; the cursor never crosses the row.
1824
+ * - A row whose message another copy is still handling on this connection
1825
+ * (the server's reconnect backlog brings the same rows) is not
1826
+ * dispatched again, and the drain never waits for that copy: the cursor
1827
+ * covers the row only if the copy already finished cleanly, otherwise
1828
+ * it stops there and the next drain covers it as a dedup hit.
1693
1829
  * - A row whose handler threw is not acked — nor is anything after it
1694
1830
  * (the ack cursor is at-or-before) — so the server re-offers it; the
1695
1831
  * dedup cache suppresses re-dispatch of its acked predecessors.
1696
- * - A row parked in the out-of-order buffer (awaiting seq gap-fill) is
1697
- * not acked until actually dispatched: acks FREEZE at the last settled
1698
- * row for the remainder of the drain. Without this, a disconnect that
1699
- * clears the ordering buffers (`resetOrderStates`) would silently drop
1700
- * an already-acked message — acked-but-undispatched is exactly the
1832
+ * - A row no handler has been handed yet is not acked: acks FREEZE at the
1833
+ * last settled row for the remainder of the drain. That is a row
1834
+ * parked in the out-of-order buffer (awaiting seq gap-fill), and also a
1835
+ * row that was parked when the socket closed: in the default mode the
1836
+ * close clears the ordering buffers (`resetOrderStates`) without
1837
+ * dispatching them, possibly while the drain is still awaiting an
1838
+ * earlier row's handler. Covering either would mark a message
1839
+ * delivered that no handler saw — acked-but-undispatched is exactly the
1701
1840
  * loss the ack protocol exists to prevent. Reading continues so the
1702
1841
  * in-session gap-fill still resolves; the frozen tail is re-offered on
1703
- * the next drain and absorbed by the dedup cache.
1842
+ * the next drain (or the server's reconnect backlog) and absorbed by
1843
+ * the dedup cache.
1704
1844
  *
1705
1845
  * Concurrent calls are coalesced (the second returns immediately). The
1706
1846
  * server-side ack pointer only moves forward, so re-running after a
@@ -1765,14 +1905,22 @@ var RealtimeClient = class {
1765
1905
  const row = rows[i];
1766
1906
  const envelope = envelopes[i];
1767
1907
  if (!row || !envelope) break;
1768
- const settlement = this.drainSettlements.get(envelope);
1769
- if (settlement) {
1770
- const ok = await settlement;
1771
- if (!ok) {
1908
+ const adopted = this.drainAdopted.get(envelope);
1909
+ if (adopted) {
1910
+ if (!adopted.settled || !adopted.ok) {
1772
1911
  acksFrozen = true;
1773
1912
  break;
1774
1913
  }
1775
- } else if (this.isBufferedInOrderState(row)) {
1914
+ const adoptedId = row.delivery_id;
1915
+ if (typeof adoptedId === "string" && adoptedId.length > 0) ackCursor = adoptedId;
1916
+ continue;
1917
+ }
1918
+ const settlement = this.drainSettlements.get(envelope);
1919
+ if (!settlement) {
1920
+ acksFrozen = true;
1921
+ break;
1922
+ }
1923
+ if (!await settlement) {
1776
1924
  acksFrozen = true;
1777
1925
  break;
1778
1926
  }
@@ -1804,14 +1952,6 @@ var RealtimeClient = class {
1804
1952
  after = nextAfter;
1805
1953
  }
1806
1954
  }
1807
- // True when a drain row is currently parked in the per-conversation
1808
- // out-of-order buffer (its dispatch is deferred to the gap-fill
1809
- // machinery — natural arrival, gap-fill fetch, or forced resolveGap).
1810
- isBufferedInOrderState(row) {
1811
- if (typeof row.seq !== "number") return false;
1812
- const state = this.orderStates.get(row.conversation_id);
1813
- return state !== void 0 && state.buffer.has(row.seq);
1814
- }
1815
1955
  /**
1816
1956
  * Clear the reconnect backoff once this connection proves itself.
1817
1957
  *
@@ -1829,8 +1969,9 @@ var RealtimeClient = class {
1829
1969
  if (this.disposed || !this.authenticated) return;
1830
1970
  this.reconnectAttempts = 0;
1831
1971
  this.rapidReconnects = 0;
1972
+ this.longOutageAnnounced = false;
1832
1973
  }, STABLE_CONNECTION_MS);
1833
- this.stabilityTimer.unref?.();
1974
+ unref(this.stabilityTimer);
1834
1975
  }
1835
1976
  cancelStabilityTimer() {
1836
1977
  if (this.stabilityTimer) {
@@ -1842,6 +1983,8 @@ var RealtimeClient = class {
1842
1983
  * Track short-lived connections and warn once they form a pattern.
1843
1984
  * A flapping client looks healthy from the inside — every reconnect
1844
1985
  * succeeds — so without this the operator has no local signal at all.
1986
+ * The notice goes through `onError` like every other signal: an SDK
1987
+ * that runs as a guest inside a host process does not own its console.
1845
1988
  */
1846
1989
  noteConnectionEnded() {
1847
1990
  const started = this.lastConnectAt;
@@ -1853,43 +1996,253 @@ var RealtimeClient = class {
1853
1996
  }
1854
1997
  this.rapidReconnects++;
1855
1998
  if (this.rapidReconnects === INSTABILITY_WARN_THRESHOLD) {
1856
- console.warn(
1857
- `[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.`
1999
+ this.emitError(
2000
+ new ConnectionError(
2001
+ `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.`
2002
+ )
1858
2003
  );
1859
2004
  }
1860
2005
  }
2006
+ // ─── Lifecycle: close funnel, backoff, blocked, watchdogs ───────────────
2007
+ //
2008
+ // Invariant: the client never parks itself. Every close leads to a timer
2009
+ // (backoff or blocked retry) or, with `reconnect: false`, to `idle` where
2010
+ // the application's next connect() picks up. Only disconnect() ends it.
2011
+ /**
2012
+ * The single funnel for "this socket is over", whoever ended it. Runs
2013
+ * after `this.ws` has been let go of, so nothing here touches the socket
2014
+ * again. Decides what comes next — backoff, blocked or idle, never nothing.
2015
+ */
2016
+ handleClose(info) {
2017
+ const duringHandshake = !this.authenticated;
2018
+ this.clearWatchdogs();
2019
+ this.cancelStabilityTimer();
2020
+ this.noteConnectionEnded();
2021
+ this.authenticated = false;
2022
+ this.ackMode = false;
2023
+ for (const handler of this.disconnectHandlers) {
2024
+ try {
2025
+ handler(info);
2026
+ } catch {
2027
+ }
2028
+ }
2029
+ if (this.options.ackOnReceipt) this.flushParkedFrames("connection_closed");
2030
+ this.resetOrderStates();
2031
+ this.generation++;
2032
+ if (this.disposed) return;
2033
+ if (info.initiator === "server" && duringHandshake && isAuthRejectionClose(info.code, info.reason)) {
2034
+ this.enterBlocked(info.code, info.reason);
2035
+ return;
2036
+ }
2037
+ this.scheduleReconnect();
2038
+ }
2039
+ /**
2040
+ * End the current socket on the client's own decision (a watchdog trip,
2041
+ * a HELLO that could not be sent) and move on at once, without waiting for
2042
+ * the socket's close event: on a dead pipe a polite close waits for a
2043
+ * reply that never comes. Terminated where the API allows it (Node `ws`),
2044
+ * closed otherwise; its own late events are ignored because it is no
2045
+ * longer `this.ws`.
2046
+ */
2047
+ abandonSocket(code, reason) {
2048
+ const ws = this.ws;
2049
+ if (!ws) return;
2050
+ this.ws = null;
2051
+ const terminate = ws.terminate;
2052
+ try {
2053
+ if (typeof terminate === "function") terminate.call(ws);
2054
+ else ws.close(code, reason);
2055
+ } catch {
2056
+ }
2057
+ this.handleClose({ code, reason, wasClean: false, initiator: "client" });
2058
+ }
1861
2059
  scheduleReconnect() {
1862
2060
  if (this.disposed) return;
1863
- if (!this.options.reconnect) return;
1864
- if (this.reconnectAttempts >= this.options.maxReconnectAttempts) return;
1865
2061
  if (this.reconnectTimer) return;
2062
+ if (!this.options.reconnect) {
2063
+ this.setState("idle");
2064
+ return;
2065
+ }
1866
2066
  this.reconnectAttempts++;
1867
- const delay = this.computeReconnectDelay(this.reconnectAttempts);
2067
+ const attempt = this.reconnectAttempts;
2068
+ if (attempt > LONG_OUTAGE_AFTER_ATTEMPTS && !this.longOutageAnnounced) {
2069
+ this.longOutageAnnounced = true;
2070
+ this.emitError(
2071
+ new ConnectionError(
2072
+ `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`
2073
+ )
2074
+ );
2075
+ }
2076
+ const delay = this.computeReconnectDelay(attempt);
2077
+ this.setState("backoff");
1868
2078
  this.reconnectTimer = setTimeout(() => {
1869
2079
  this.reconnectTimer = null;
1870
- void this.connect().catch((err) => {
1871
- this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
1872
- });
2080
+ this.retryNow();
1873
2081
  }, delay);
1874
2082
  }
2083
+ /**
2084
+ * The server rejected the credential. `blocked` is not the end: a fresh
2085
+ * HELLO goes out every AUTH_RETRY_INTERVAL_MS (jittered) until one is
2086
+ * accepted — keys get rotated back and accounts get reinstated, and the
2087
+ * running client has no other way to learn it. The first rejection of a
2088
+ * run is an error; the following ones only fire `blocked`, so an operator
2089
+ * sees one line per incident rather than one every quarter hour.
2090
+ */
2091
+ enterBlocked(code, reason) {
2092
+ const retryInMs = this.options.reconnect ? this.jittered(AUTH_RETRY_INTERVAL_MS, AUTH_RETRY_JITTER_RATIO) : null;
2093
+ this.setState("blocked");
2094
+ if (!this.blockedAnnounced) {
2095
+ this.blockedAnnounced = true;
2096
+ this.emitError(
2097
+ new ConnectionError(
2098
+ `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")
2099
+ )
2100
+ );
2101
+ }
2102
+ const info = { code, reason, retryInMs };
2103
+ for (const handler of this.blockedHandlers) {
2104
+ try {
2105
+ handler(info);
2106
+ } catch {
2107
+ }
2108
+ }
2109
+ if (retryInMs === null) return;
2110
+ this.reconnectTimer = setTimeout(() => {
2111
+ this.reconnectTimer = null;
2112
+ this.retryNow();
2113
+ }, retryInMs);
2114
+ }
2115
+ /**
2116
+ * The timer-driven attempt. connect() emits and re-arms on its own for
2117
+ * every failure it retries (a throwing constructor, a close); the one
2118
+ * failure it does not retry — no WebSocket implementation at all — left
2119
+ * nothing armed, so it is announced here: the operator should see why the
2120
+ * client went quiet.
2121
+ */
2122
+ retryNow() {
2123
+ void this.connect().catch((err) => {
2124
+ if (this.disposed || this.ws || this.reconnectTimer) return;
2125
+ this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
2126
+ });
2127
+ }
2128
+ clearReconnectTimer() {
2129
+ if (this.reconnectTimer) {
2130
+ clearTimeout(this.reconnectTimer);
2131
+ this.reconnectTimer = null;
2132
+ }
2133
+ }
1875
2134
  computeReconnectDelay(attempt) {
1876
- const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 10));
1877
- const capped = Math.min(exp, this.options.maxReconnectInterval);
1878
- const jitter = 0.75 + Math.random() * 0.5;
1879
- return Math.max(0, Math.floor(capped * jitter));
2135
+ const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 20));
2136
+ const cap = attempt > LONG_OUTAGE_AFTER_ATTEMPTS ? this.longOutageCap() : this.options.maxReconnectInterval;
2137
+ return this.jitteredBelow(Math.min(exp, cap), RECONNECT_JITTER_RATIO);
2138
+ }
2139
+ longOutageCap() {
2140
+ return Math.max(this.options.maxReconnectInterval, LONG_OUTAGE_MAX_INTERVAL_MS);
2141
+ }
2142
+ /** Symmetric ±ratio jitter around `ms` — for the blocked retry, a range (10–15 min), not a cap. */
2143
+ jittered(ms, ratio) {
2144
+ const factor = 1 - ratio + Math.random() * 2 * ratio;
2145
+ return Math.max(0, Math.floor(ms * factor));
2146
+ }
2147
+ /** Jitter in [ms × (1 − ratio), ms]: `ms` is a ceiling. Thundering-herd-safe across a fleet. */
2148
+ jitteredBelow(ms, ratio) {
2149
+ const factor = 1 - Math.random() * ratio;
2150
+ return Math.max(0, Math.floor(ms * factor));
2151
+ }
2152
+ armHandshakeDeadline() {
2153
+ this.clearHandshakeTimer();
2154
+ const ms = this.options.handshakeTimeoutMs;
2155
+ this.handshakeTimer = setTimeout(() => {
2156
+ this.handshakeTimer = null;
2157
+ this.emitError(new ConnectionError(`handshake timeout: no hello.ok within ${ms}ms`));
2158
+ this.abandonSocket(CLIENT_CLOSE_CODE, "client handshake timeout");
2159
+ }, ms);
2160
+ unref(this.handshakeTimer);
2161
+ }
2162
+ /**
2163
+ * Note proof of life (any inbound frame, or a ping/pong on a socket that
2164
+ * shows them). The timer itself is lazy: it is armed once per connection
2165
+ * and, when it fires early because traffic arrived meanwhile, re-arms for
2166
+ * the remainder — one `Date.now()` per frame instead of a timer churn.
2167
+ */
2168
+ touchLiveness() {
2169
+ this.lastInboundAt = Date.now();
2170
+ if (this.livenessTimer === null) this.armLiveness(this.livenessMs);
2171
+ }
2172
+ armLiveness(ms) {
2173
+ if (this.livenessMs <= 0 || !this.ws || !this.authenticated) return;
2174
+ this.livenessTimer = setTimeout(() => {
2175
+ this.livenessTimer = null;
2176
+ const quietFor = Date.now() - this.lastInboundAt;
2177
+ if (quietFor < this.livenessMs) {
2178
+ this.armLiveness(this.livenessMs - quietFor);
2179
+ return;
2180
+ }
2181
+ this.emitError(
2182
+ new ConnectionError(`liveness timeout: nothing received for ${this.livenessMs}ms`)
2183
+ );
2184
+ this.abandonSocket(CLIENT_CLOSE_CODE, "client liveness timeout");
2185
+ }, Math.max(1, ms));
2186
+ unref(this.livenessTimer);
2187
+ }
2188
+ clearHandshakeTimer() {
2189
+ if (this.handshakeTimer) {
2190
+ clearTimeout(this.handshakeTimer);
2191
+ this.handshakeTimer = null;
2192
+ }
2193
+ }
2194
+ clearWatchdogs() {
2195
+ this.clearHandshakeTimer();
2196
+ if (this.livenessTimer) {
2197
+ clearTimeout(this.livenessTimer);
2198
+ this.livenessTimer = null;
2199
+ }
2200
+ }
2201
+ setState(next) {
2202
+ const previous = this._state;
2203
+ if (previous === next) return;
2204
+ this._state = next;
2205
+ for (const handler of this.stateHandlers) {
2206
+ try {
2207
+ handler(next, previous);
2208
+ } catch {
2209
+ }
2210
+ }
1880
2211
  }
1881
2212
  on(event, handler) {
2213
+ switch (event) {
2214
+ case "state":
2215
+ return this.subscribe(this.stateHandlers, handler);
2216
+ case "blocked":
2217
+ return this.subscribe(this.blockedHandlers, handler);
2218
+ case "stopped":
2219
+ return this.subscribe(this.stoppedHandlers, handler);
2220
+ }
1882
2221
  let handlers = this.handlers.get(event);
1883
2222
  if (!handlers) {
1884
2223
  handlers = /* @__PURE__ */ new Set();
1885
2224
  this.handlers.set(event, handlers);
1886
2225
  }
1887
- handlers.add(handler);
2226
+ const stored = handler;
2227
+ handlers.add(stored);
1888
2228
  return () => {
1889
- handlers.delete(handler);
2229
+ handlers.delete(stored);
1890
2230
  if (handlers.size === 0) this.handlers.delete(event);
1891
2231
  };
1892
2232
  }
2233
+ subscribe(set, handler) {
2234
+ set.add(handler);
2235
+ return () => {
2236
+ set.delete(handler);
2237
+ };
2238
+ }
2239
+ /**
2240
+ * Every signal the client has for its operator comes through here:
2241
+ * transport errors, handler failures, the watchdog and backoff notices
2242
+ * (`handshake timeout`, `liveness timeout`, `still reconnecting after
2243
+ * 60 …`, `server rejected the credential …`, `connection is unstable`).
2244
+ * The SDK never writes to the console.
2245
+ */
1893
2246
  onError(handler) {
1894
2247
  this.errorHandlers.add(handler);
1895
2248
  return () => this.errorHandlers.delete(handler);
@@ -1940,38 +2293,63 @@ var RealtimeClient = class {
1940
2293
  get isConnected() {
1941
2294
  return this.authenticated && this.ws?.readyState === 1;
1942
2295
  }
2296
+ /** Where the connection lifecycle is right now. See `RealtimeState`. */
2297
+ get state() {
2298
+ return this._state;
2299
+ }
1943
2300
  /**
1944
- * Close the socket, disable auto-reconnect, and release all handlers.
1945
- * After calling this, `connect()` throws — create a fresh
1946
- * `RealtimeClient` if you want to reopen.
2301
+ * `true` when the current connection's `hello.ok` echoed the `ack`
2302
+ * capability: the server keeps each envelope `stored` until this client
2303
+ * acknowledges it. `false` before `hello.ok`, after a close, and against
2304
+ * a legacy server (which marks envelopes delivered on push).
2305
+ */
2306
+ get ackNegotiated() {
2307
+ return this.ackMode;
2308
+ }
2309
+ /**
2310
+ * Close the socket, cancel every timer, and release all handlers. The
2311
+ * only way into `stopped`, and the only way the client ever stops on
2312
+ * purpose: works from any state (`blocked` and a pending backoff
2313
+ * included). `stopped` fires once. After this, `connect()` throws —
2314
+ * create a fresh `RealtimeClient` if you want to reopen.
1947
2315
  */
1948
2316
  disconnect() {
2317
+ if (this.disposed) return;
1949
2318
  this.disposed = true;
1950
2319
  this.options.reconnect = false;
1951
- if (this.reconnectTimer) {
1952
- clearTimeout(this.reconnectTimer);
1953
- this.reconnectTimer = null;
1954
- }
1955
- if (this.helloAckTimer) {
1956
- clearTimeout(this.helloAckTimer);
1957
- this.helloAckTimer = null;
1958
- }
2320
+ this.clearReconnectTimer();
2321
+ this.clearWatchdogs();
1959
2322
  this.cancelStabilityTimer();
1960
- this.drainAllPendingForShutdown();
2323
+ this.flushParkedFrames("gap_fill_unavailable");
2324
+ const ws = this.ws;
2325
+ this.ws = null;
1961
2326
  try {
1962
- this.ws?.close();
2327
+ ws?.close(1e3, "client disconnect");
1963
2328
  } catch {
1964
2329
  }
1965
- this.ws = null;
1966
2330
  this.authenticated = false;
2331
+ this.ackMode = false;
2332
+ this.setState("stopped");
2333
+ for (const handler of this.stoppedHandlers) {
2334
+ try {
2335
+ handler();
2336
+ } catch {
2337
+ }
2338
+ }
1967
2339
  this.handlers.clear();
1968
2340
  this.errorHandlers.clear();
1969
2341
  this.connectHandlers.clear();
1970
2342
  this.disconnectHandlers.clear();
2343
+ this.stateHandlers.clear();
2344
+ this.blockedHandlers.clear();
2345
+ this.stoppedHandlers.clear();
1971
2346
  }
1972
2347
  emitError(error) {
1973
2348
  for (const handler of this.errorHandlers) {
1974
- handler(error);
2349
+ try {
2350
+ handler(error);
2351
+ } catch {
2352
+ }
1975
2353
  }
1976
2354
  }
1977
2355
  dispatch(message) {
@@ -2003,6 +2381,10 @@ var RealtimeClient = class {
2003
2381
  * acked. Resolves `false` when any handler threw or rejected: the
2004
2382
  * message is NOT acked on any path and the server re-offers it.
2005
2383
  *
2384
+ * A copy of a message whose first copy is still with the handlers is not
2385
+ * dispatched again: it resolves with the first copy's outcome (and, when
2386
+ * that succeeded, is acked like a dedup hit).
2387
+ *
2006
2388
  * Ack routing: live frames (including server-pushed reconnect backlog
2007
2389
  * and gap-fill rows) send a WS `{type:'ack'}` frame when ack-mode was
2008
2390
  * negotiated; REST-drain rows are covered by the drain's sync/ack
@@ -2012,10 +2394,19 @@ var RealtimeClient = class {
2012
2394
  dispatchMessageNew(message) {
2013
2395
  const isDrainRow = this.restDrainOrigin.has(message);
2014
2396
  const messageId = this.extractMessageId(message);
2397
+ const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt;
2015
2398
  let settlement;
2399
+ const inFlight = messageId !== null ? this.inFlight.get(messageId) : void 0;
2400
+ const first = inFlight?.generation === this.generation ? inFlight : void 0;
2016
2401
  if (messageId !== null && this.dedupHit(messageId)) {
2017
2402
  settlement = Promise.resolve(true);
2018
- if (!isDrainRow) this.sendAckFrame(messageId);
2403
+ if (ackAfterDispatch) this.sendAckFrame(messageId);
2404
+ } else if (messageId !== null && first !== void 0) {
2405
+ if (isDrainRow) this.drainAdopted.set(message, first);
2406
+ settlement = first.promise.then((ok) => {
2407
+ if (ok && ackAfterDispatch) this.sendAckFrame(messageId);
2408
+ return ok;
2409
+ });
2019
2410
  } else {
2020
2411
  const handlers = this.handlers.get("message.new");
2021
2412
  const pending = [];
@@ -2029,7 +2420,13 @@ var RealtimeClient = class {
2029
2420
  }
2030
2421
  }
2031
2422
  }
2032
- settlement = Promise.allSettled(pending).then((outcomes) => {
2423
+ const entry = {
2424
+ promise: Promise.resolve(false),
2425
+ generation: this.generation,
2426
+ settled: false,
2427
+ ok: false
2428
+ };
2429
+ const own = Promise.allSettled(pending).then((outcomes) => {
2033
2430
  let ok = true;
2034
2431
  for (const outcome of outcomes) {
2035
2432
  if (outcome.status === "rejected") {
@@ -2037,13 +2434,21 @@ var RealtimeClient = class {
2037
2434
  this.emitError(toError(outcome.reason, "message.new"));
2038
2435
  }
2039
2436
  }
2437
+ if (messageId !== null && this.inFlight.get(messageId) === entry) {
2438
+ this.inFlight.delete(messageId);
2439
+ }
2440
+ entry.settled = true;
2441
+ entry.ok = ok;
2040
2442
  if (!ok) return false;
2041
2443
  if (messageId !== null) {
2042
2444
  this.dedupAdd(messageId);
2043
- if (!isDrainRow) this.sendAckFrame(messageId);
2445
+ if (ackAfterDispatch) this.sendAckFrame(messageId);
2044
2446
  }
2045
2447
  return true;
2046
2448
  });
2449
+ entry.promise = own;
2450
+ if (messageId !== null) this.inFlight.set(messageId, entry);
2451
+ settlement = own;
2047
2452
  }
2048
2453
  if (isDrainRow) this.drainSettlements.set(message, settlement);
2049
2454
  return settlement;
@@ -2088,12 +2493,45 @@ var RealtimeClient = class {
2088
2493
  isMessageNew(message) {
2089
2494
  return message.type === "message.new";
2090
2495
  }
2496
+ isWake(message) {
2497
+ return message.type === "wake";
2498
+ }
2499
+ /**
2500
+ * A `wake` frame is a content-free signal: validate the payload shape
2501
+ * (so `wake` handlers can trust the `WakeFrame` type), then dispatch. A
2502
+ * frame the server sent malformed is surfaced through `onError` rather
2503
+ * than handed to handlers as something it is not. Never acked — there is
2504
+ * no message to deliver.
2505
+ */
2506
+ dispatchWake(message) {
2507
+ const payload = message.payload;
2508
+ const reason = this.wakePayloadProblem(payload);
2509
+ if (reason !== null) {
2510
+ this.emitError(new ConnectionError(`wake frame failed validation: ${reason}`));
2511
+ return;
2512
+ }
2513
+ this.dispatch(message);
2514
+ }
2515
+ wakePayloadProblem(payload) {
2516
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
2517
+ return "payload is not an object";
2518
+ }
2519
+ const p = payload;
2520
+ for (const key of ["reason", "conversation_id", "anchor_message_id", "at"]) {
2521
+ if (typeof p[key] !== "string" || p[key] === "") return `${key} is not a non-empty string`;
2522
+ }
2523
+ if (typeof p.step !== "number" || !Number.isInteger(p.step)) return "step is not an integer";
2524
+ return null;
2525
+ }
2091
2526
  // ─── Per-conversation seq ordering ───────────────────────────────────────
2092
2527
  //
2093
2528
  // Invariant: for any conversation_id, handlers see message.new envelopes
2094
- // strictly in seq-ascending order with no skipped or repeated seqs (modulo
2095
- // the gap-fill failure path, where we surface the incident via
2096
- // onSequenceGap and continue forward).
2529
+ // in seq-ascending order with no skipped or repeated seqs — except that a
2530
+ // frame older than this connection's anchor (a stored row the drain brings
2531
+ // after a live frame anchored the conversation, or a seq a failed gap-fill
2532
+ // skipped) is dispatched late rather than dropped: never lost beats
2533
+ // strictly ordered, since the ack would otherwise bury it for good. The
2534
+ // dedup cache alone decides what is a repeat.
2097
2535
  //
2098
2536
  // Why per-conversation instead of global: seq numbers are minted per
2099
2537
  // conversation by send_message_atomic, so cross-conversation arrivals
@@ -2117,6 +2555,7 @@ var RealtimeClient = class {
2117
2555
  return;
2118
2556
  }
2119
2557
  if (seq < state.nextExpectedSeq) {
2558
+ this.dispatch(message);
2120
2559
  return;
2121
2560
  }
2122
2561
  if (seq === state.nextExpectedSeq) {
@@ -2190,10 +2629,15 @@ var RealtimeClient = class {
2190
2629
  const rowSeq = typeof row.seq === "number" ? row.seq : null;
2191
2630
  if (rowSeq === null || rowSeq < expectedSeq) continue;
2192
2631
  if (state.buffer.has(rowSeq)) continue;
2193
- state.buffer.set(rowSeq, {
2632
+ const envelope = {
2194
2633
  type: "message.new",
2195
2634
  payload: row
2196
- });
2635
+ };
2636
+ if (this.options.ackOnReceipt) {
2637
+ const messageId = this.extractMessageId(envelope);
2638
+ if (messageId !== null) this.sendAckFrame(messageId);
2639
+ }
2640
+ state.buffer.set(rowSeq, envelope);
2197
2641
  }
2198
2642
  const drainedThroughGap = this.drainConsecutive(conversationId, state);
2199
2643
  if (drainedThroughGap) {
@@ -2308,7 +2752,11 @@ var RealtimeClient = class {
2308
2752
  }
2309
2753
  this.orderStates.clear();
2310
2754
  }
2311
- drainAllPendingForShutdown() {
2755
+ // Hand every parked frame to the handlers in seq order per conversation,
2756
+ // cancel the gap timers and clear the ordering state. Used when frames
2757
+ // must not be dropped: on disconnect() (the caller is leaving) and, under
2758
+ // ackOnReceipt, on every socket close (the frames are already acked).
2759
+ flushParkedFrames(reason) {
2312
2760
  for (const [conversationId, state] of this.orderStates) {
2313
2761
  if (state.gapTimer !== null) {
2314
2762
  clearTimeout(state.gapTimer);
@@ -2324,13 +2772,268 @@ var RealtimeClient = class {
2324
2772
  bufferedSeq: seqs[0] ?? null,
2325
2773
  gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,
2326
2774
  recovered: false,
2327
- reason: "gap_fill_unavailable"
2775
+ reason
2328
2776
  });
2329
2777
  }
2330
2778
  this.orderStates.clear();
2331
2779
  }
2332
2780
  };
2333
2781
 
2782
+ // src/gate.ts
2783
+ var gate_exports = {};
2784
+ __export(gate_exports, {
2785
+ BARE_TOOL_NAMER: () => BARE_TOOL_NAMER,
2786
+ anchorOf: () => anchorOf,
2787
+ buildPrompt: () => buildPrompt,
2788
+ canonicalJson: () => canonicalJson,
2789
+ cardsOf: () => cardsOf,
2790
+ mcpToolNamer: () => mcpToolNamer,
2791
+ normalizeDecision: () => normalizeDecision,
2792
+ parseVerdicts: () => parseVerdicts,
2793
+ run: () => run
2794
+ });
2795
+ var BARE_TOOL_NAMER = (tool) => tool;
2796
+ function mcpToolNamer(serverName) {
2797
+ return (tool) => `mcp__${serverName}__${tool}`;
2798
+ }
2799
+ var HOSTED_TOOL_TOKEN = /\bagentchat_[a-z0-9_]+\b/g;
2800
+ var DECIDE_TOOL = "agentchat_decide";
2801
+ var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "respond", "answer", "yes", "true"]);
2802
+ var DISMISS_TOKENS = /* @__PURE__ */ new Set([
2803
+ "dismiss",
2804
+ "dismissed",
2805
+ "no_reply",
2806
+ "no-reply",
2807
+ "noreply",
2808
+ "silent",
2809
+ "silence",
2810
+ "skip",
2811
+ "ignore",
2812
+ "no",
2813
+ "false"
2814
+ ]);
2815
+ var DEFER_TOKENS = /* @__PURE__ */ new Set(["defer", "deferred", "later", "wait", "postpone"]);
2816
+ var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
2817
+ function cardsOf(tray) {
2818
+ const raw = tray.conversations;
2819
+ if (!Array.isArray(raw)) return [];
2820
+ return raw.filter(
2821
+ (card) => typeof card === "object" && card !== null && !Array.isArray(card) && typeof card.conversation_id === "string" && card.conversation_id.length > 0
2822
+ );
2823
+ }
2824
+ function categoriesOf(tray) {
2825
+ const raw = tray.categories;
2826
+ if (!Array.isArray(raw)) return [];
2827
+ return raw.filter((item) => typeof item === "string" && item.length > 0);
2828
+ }
2829
+ function anchorOf(card) {
2830
+ const preview = card.preview?.message_id;
2831
+ if (typeof preview === "string" && preview.length > 0) return preview;
2832
+ const last = card.last_message_id;
2833
+ if (typeof last === "string" && last.length > 0) return last;
2834
+ return void 0;
2835
+ }
2836
+ function canonicalJson(value) {
2837
+ return JSON.stringify(sortKeysDeep(value), null, 2);
2838
+ }
2839
+ function sortKeysDeep(value) {
2840
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
2841
+ if (typeof value === "object" && value !== null) {
2842
+ const source = value;
2843
+ const out = {};
2844
+ for (const key of Object.keys(source).sort()) {
2845
+ if (source[key] !== void 0) out[key] = sortKeysDeep(source[key]);
2846
+ }
2847
+ return out;
2848
+ }
2849
+ return value;
2850
+ }
2851
+ function buildPrompt(tray, options) {
2852
+ const question = tray.question;
2853
+ if (typeof question !== "string" || question.trim().length === 0) {
2854
+ throw new Error("gate: tray carries no question");
2855
+ }
2856
+ const namer = options?.toolNamer ?? BARE_TOOL_NAMER;
2857
+ const cards = cardsOf(tray);
2858
+ const categories = categoriesOf(tray);
2859
+ const sections = [];
2860
+ sections.push(
2861
+ `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.`
2862
+ );
2863
+ sections.push(question.trim().replace(HOSTED_TOOL_TOKEN, (token) => namer(token)));
2864
+ if (categories.length > 0) {
2865
+ sections.push(`Categories: ${categories.join(", ")}`);
2866
+ }
2867
+ const you = typeof tray.you === "string" && tray.you.length > 0 ? `You are ${tray.you}. ` : "";
2868
+ const count = cards.length;
2869
+ sections.push(
2870
+ `${you}Your tray, as the server built it: ${count} conversation${count === 1 ? "" : "s"}.`
2871
+ );
2872
+ cards.forEach((card, index) => {
2873
+ sections.push(`Card ${index + 1} of ${count}
2874
+ ${canonicalJson(card)}`);
2875
+ });
2876
+ let shape = '{"decisions": [{"conversation_id": "<conversation_id from a card>", "decision": "reply" | "dismiss" | "defer"';
2877
+ if (categories.length > 0) {
2878
+ shape += `, "category": "<one of: ${categories.join(", ")}>"`;
2879
+ }
2880
+ shape += "}]}";
2881
+ sections.push(
2882
+ "Answer with ONLY a JSON object, no prose and no code fences, in this shape: " + shape + " \u2014 one entry per card, every card decided."
2883
+ );
2884
+ return sections.join("\n\n");
2885
+ }
2886
+ function parseVerdicts(text, tray) {
2887
+ const raw = extractJson(text);
2888
+ if (raw === null) return null;
2889
+ let parsed;
2890
+ try {
2891
+ parsed = JSON.parse(raw);
2892
+ } catch {
2893
+ return null;
2894
+ }
2895
+ let items;
2896
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
2897
+ const record = parsed;
2898
+ items = record.decisions ?? record.verdicts;
2899
+ if (items === void 0 && "conversation_id" in record) items = [record];
2900
+ } else {
2901
+ items = parsed;
2902
+ }
2903
+ if (!Array.isArray(items)) return null;
2904
+ const known = new Set(cardsOf(tray).map((card) => card.conversation_id));
2905
+ const allowed = new Set(categoriesOf(tray).map((c) => c.toLowerCase()));
2906
+ const seen = /* @__PURE__ */ new Set();
2907
+ const out = [];
2908
+ for (const item of items) {
2909
+ if (typeof item !== "object" || item === null || Array.isArray(item)) continue;
2910
+ const entry = item;
2911
+ const id = entry.conversation_id;
2912
+ if (typeof id !== "string" || !known.has(id) || seen.has(id)) continue;
2913
+ const decision = normalizeDecision(entry.decision);
2914
+ if (decision === null) continue;
2915
+ seen.add(id);
2916
+ out.push({
2917
+ conversation_id: id,
2918
+ decision,
2919
+ category: normalizeCategory(entry.category, allowed)
2920
+ });
2921
+ }
2922
+ return out;
2923
+ }
2924
+ function extractJson(text) {
2925
+ if (typeof text !== "string" || text.trim().length === 0) return null;
2926
+ let s = text.trim();
2927
+ const fence = FENCE_RE.exec(s);
2928
+ if (fence?.[1]) s = fence[1].trim();
2929
+ const starts = [s.indexOf("{"), s.indexOf("[")].filter((i) => i !== -1);
2930
+ if (starts.length === 0) return null;
2931
+ const start = Math.min(...starts);
2932
+ const closer = s[start] === "{" ? "}" : "]";
2933
+ const end = s.lastIndexOf(closer);
2934
+ if (end <= start) return null;
2935
+ return s.slice(start, end + 1);
2936
+ }
2937
+ function normalizeDecision(value) {
2938
+ if (typeof value !== "string") return null;
2939
+ const token = value.trim().toLowerCase().replace(/\s+/g, "_");
2940
+ if (REPLY_TOKENS.has(token)) return "reply";
2941
+ if (DISMISS_TOKENS.has(token)) return "dismiss";
2942
+ if (DEFER_TOKENS.has(token)) return "defer";
2943
+ return null;
2944
+ }
2945
+ function normalizeCategory(value, allowed) {
2946
+ if (allowed.size === 0 || typeof value !== "string") return null;
2947
+ const token = value.trim().toLowerCase();
2948
+ return allowed.has(token) ? token : null;
2949
+ }
2950
+ async function run(options) {
2951
+ const cards = cardsOf(options.tray);
2952
+ const ids = cards.map((card) => card.conversation_id);
2953
+ if (ids.length === 0) return emptyResult("empty", [], null);
2954
+ let text;
2955
+ try {
2956
+ const prompt = buildPrompt(options.tray, { toolNamer: options.toolNamer });
2957
+ text = await options.callModel(prompt);
2958
+ } catch (err) {
2959
+ return emptyResult("fail_closed", ids, `model call failed: ${describe(err)}`);
2960
+ }
2961
+ const verdicts = parseVerdicts(text, options.tray);
2962
+ if (verdicts === null || verdicts.length === 0) {
2963
+ return emptyResult("fail_closed", ids, "no usable verdicts in the answer");
2964
+ }
2965
+ const byId = new Map(cards.map((card) => [card.conversation_id, card]));
2966
+ const decided = new Set(verdicts.map((v) => v.conversation_id));
2967
+ const reply = [];
2968
+ const recordFailures = [];
2969
+ let recorded = 0;
2970
+ for (const verdict of verdicts) {
2971
+ const card = byId.get(verdict.conversation_id);
2972
+ if (!card) continue;
2973
+ if (verdict.decision === "reply") {
2974
+ reply.push(deferredReply(options.client, card, verdict.category));
2975
+ continue;
2976
+ }
2977
+ try {
2978
+ await options.client.decisions.record(verdict.conversation_id, {
2979
+ decision: verdict.decision,
2980
+ category: verdict.category ?? void 0,
2981
+ throughMessageId: anchorOf(card)
2982
+ });
2983
+ recorded += 1;
2984
+ } catch (err) {
2985
+ recordFailures.push({ conversation_id: verdict.conversation_id, error: toError2(err) });
2986
+ }
2987
+ }
2988
+ return {
2989
+ outcome: "decided",
2990
+ reply,
2991
+ verdicts,
2992
+ undecided: ids.filter((id) => !decided.has(id)),
2993
+ recorded,
2994
+ recordFailures,
2995
+ failure: null
2996
+ };
2997
+ }
2998
+ function deferredReply(client, card, category) {
2999
+ let inFlight = null;
3000
+ return {
3001
+ conversationId: card.conversation_id,
3002
+ card,
3003
+ category,
3004
+ record: () => {
3005
+ if (inFlight === null) {
3006
+ inFlight = client.decisions.record(card.conversation_id, {
3007
+ decision: "reply",
3008
+ category: category ?? void 0,
3009
+ throughMessageId: anchorOf(card)
3010
+ }).catch((err) => {
3011
+ inFlight = null;
3012
+ throw err;
3013
+ });
3014
+ }
3015
+ return inFlight;
3016
+ }
3017
+ };
3018
+ }
3019
+ function emptyResult(outcome, undecided, failure) {
3020
+ return {
3021
+ outcome,
3022
+ reply: [],
3023
+ verdicts: [],
3024
+ undecided,
3025
+ recorded: 0,
3026
+ recordFailures: [],
3027
+ failure
3028
+ };
3029
+ }
3030
+ function toError2(err) {
3031
+ return err instanceof Error ? err : new Error(String(err));
3032
+ }
3033
+ function describe(err) {
3034
+ return err instanceof Error ? err.message : String(err);
3035
+ }
3036
+
2334
3037
  // src/render.ts
2335
3038
  var SEC = 1e3;
2336
3039
  var MIN = 60 * SEC;
@@ -2382,6 +3085,11 @@ function renderMessageContext(message, opts = {}) {
2382
3085
  return lines.join("\n");
2383
3086
  }
2384
3087
 
3088
+ // src/types/inbox-tray.ts
3089
+ var INBOX_TRAY_DEFAULT_LIMIT = 20;
3090
+ var INBOX_TRAY_MAX_LIMIT = 50;
3091
+ var INBOX_WAIT_MAX_MS = 5e4;
3092
+
2385
3093
  // src/types/attachment.ts
2386
3094
  var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
2387
3095
  var ALLOWED_ATTACHMENT_MIME = [
@@ -2401,6 +3109,6 @@ var ALLOWED_ATTACHMENT_MIME = [
2401
3109
  "video/webm"
2402
3110
  ];
2403
3111
 
2404
- export { ALLOWED_ATTACHMENT_MIME, AgentChatClient, AgentChatError, AwaitingReplyError, BlockedError, ConnectionError, DEFAULT_RETRY_POLICY, EmailExhaustedError, EmailLimitReachedError, ErrorCode, ForbiddenError, GroupDeletedError, HandleRequiredError, HttpTransport, MAX_ATTACHMENT_SIZE, NotFoundError, RateLimitedError, RealtimeClient, RecipientBackloggedError, RestrictedError, ServerError, SuspendedError, UnauthorizedError, VERSION, ValidationError, createAgentChatError, paginate, parseRetryAfter, renderMessageContext };
3112
+ 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 };
2405
3113
  //# sourceMappingURL=index.js.map
2406
3114
  //# sourceMappingURL=index.js.map