agentchatme 1.1.1 → 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",
@@ -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.0" ;
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,16 +1596,23 @@ 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
@@ -1537,51 +1637,73 @@ var RealtimeClient = class {
1537
1637
  disposed = false;
1538
1638
  constructor(options) {
1539
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;
1540
1642
  this.options = {
1541
1643
  baseUrl: options.baseUrl ?? "wss://api.agentchat.me",
1542
1644
  reconnect: options.reconnect ?? true,
1543
1645
  reconnectInterval: options.reconnectInterval ?? 500,
1544
1646
  maxReconnectInterval: options.maxReconnectInterval ?? 3e4,
1545
- maxReconnectAttempts: options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY,
1647
+ handshakeTimeoutMs,
1648
+ livenessTimeoutMs,
1546
1649
  apiKey: options.apiKey,
1547
1650
  client: options.client,
1548
1651
  onSequenceGap: options.onSequenceGap,
1549
1652
  autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),
1550
1653
  dedupCacheSize,
1654
+ ackOnReceipt: options.ackOnReceipt ?? false,
1551
1655
  webSocket: options.webSocket,
1552
1656
  clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY
1553
1657
  };
1554
1658
  }
1555
1659
  /**
1556
1660
  * 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.
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.
1560
1664
  *
1561
- * Safe to call on a disposed client only if you expect a fresh run —
1562
- * 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`.
1563
1671
  */
1564
1672
  async connect() {
1565
1673
  if (this.disposed) {
1566
1674
  throw new ConnectionError("RealtimeClient has been disposed; create a new instance to reconnect.");
1567
1675
  }
1676
+ if (this.ws) return;
1677
+ this.clearReconnectTimer();
1568
1678
  let WebSocketCtor;
1569
1679
  try {
1570
1680
  WebSocketCtor = this.options.webSocket ?? await resolveWebSocket();
1571
1681
  } catch (err) {
1572
- 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");
1573
1693
  this.emitError(error);
1574
1694
  this.scheduleReconnect();
1575
1695
  throw error;
1576
1696
  }
1577
- const url = `${this.options.baseUrl}/v1/ws`;
1578
- this.ws = new WebSocketCtor(url);
1697
+ this.ws = ws;
1579
1698
  this.authenticated = false;
1580
1699
  this.ackMode = false;
1581
- this.helloTimeoutClose = false;
1582
- 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;
1583
1705
  try {
1584
- this.ws.send(
1706
+ ws.send(
1585
1707
  JSON.stringify({
1586
1708
  type: "hello",
1587
1709
  api_key: this.options.apiKey,
@@ -1592,18 +1714,12 @@ var RealtimeClient = class {
1592
1714
  );
1593
1715
  } catch (err) {
1594
1716
  this.emitError(err instanceof Error ? err : new ConnectionError("HELLO send failed"));
1595
- return;
1717
+ this.abandonSocket(CLIENT_CLOSE_CODE, "client HELLO send failed");
1596
1718
  }
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
1719
  };
1606
- this.ws.onmessage = (event) => {
1720
+ ws.onmessage = (event) => {
1721
+ if (!current()) return;
1722
+ this.touchLiveness();
1607
1723
  let message;
1608
1724
  try {
1609
1725
  message = JSON.parse(String(event.data));
@@ -1615,11 +1731,11 @@ var RealtimeClient = class {
1615
1731
  this.authenticated = true;
1616
1732
  const caps = message.capabilities;
1617
1733
  this.ackMode = Array.isArray(caps) && caps.includes("ack");
1734
+ this.clearHandshakeTimer();
1735
+ this.touchLiveness();
1618
1736
  this.startStabilityTimer();
1619
- if (this.helloAckTimer) {
1620
- clearTimeout(this.helloAckTimer);
1621
- this.helloAckTimer = null;
1622
- }
1737
+ this.blockedAnnounced = false;
1738
+ this.setState("ready");
1623
1739
  for (const handler of this.connectHandlers) {
1624
1740
  try {
1625
1741
  handler();
@@ -1637,42 +1753,42 @@ var RealtimeClient = class {
1637
1753
  return;
1638
1754
  }
1639
1755
  if (this.isMessageNew(message)) {
1756
+ if (this.options.ackOnReceipt) {
1757
+ const messageId = this.extractMessageId(message);
1758
+ if (messageId !== null) this.sendAckFrame(messageId);
1759
+ }
1640
1760
  this.processOrderedMessage(message);
1641
1761
  return;
1642
1762
  }
1763
+ if (this.isWake(message)) {
1764
+ this.dispatchWake(message);
1765
+ return;
1766
+ }
1643
1767
  this.dispatch(message);
1644
1768
  };
1645
- this.ws.onerror = () => {
1769
+ ws.onerror = () => {
1770
+ if (!current()) return;
1646
1771
  this.emitError(new ConnectionError("WebSocket error"));
1647
1772
  };
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();
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
+ });
1675
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
+ }
1676
1792
  }
1677
1793
  /**
1678
1794
  * Drain offline envelopes accumulated while the socket was disconnected.
@@ -1829,8 +1945,9 @@ var RealtimeClient = class {
1829
1945
  if (this.disposed || !this.authenticated) return;
1830
1946
  this.reconnectAttempts = 0;
1831
1947
  this.rapidReconnects = 0;
1948
+ this.longOutageAnnounced = false;
1832
1949
  }, STABLE_CONNECTION_MS);
1833
- this.stabilityTimer.unref?.();
1950
+ unref(this.stabilityTimer);
1834
1951
  }
1835
1952
  cancelStabilityTimer() {
1836
1953
  if (this.stabilityTimer) {
@@ -1842,6 +1959,8 @@ var RealtimeClient = class {
1842
1959
  * Track short-lived connections and warn once they form a pattern.
1843
1960
  * A flapping client looks healthy from the inside — every reconnect
1844
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.
1845
1964
  */
1846
1965
  noteConnectionEnded() {
1847
1966
  const started = this.lastConnectAt;
@@ -1853,43 +1972,252 @@ var RealtimeClient = class {
1853
1972
  }
1854
1973
  this.rapidReconnects++;
1855
1974
  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.`
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
+ )
1858
1979
  );
1859
1980
  }
1860
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
+ }
1861
2034
  scheduleReconnect() {
1862
2035
  if (this.disposed) return;
1863
- if (!this.options.reconnect) return;
1864
- if (this.reconnectAttempts >= this.options.maxReconnectAttempts) return;
1865
2036
  if (this.reconnectTimer) return;
2037
+ if (!this.options.reconnect) {
2038
+ this.setState("idle");
2039
+ return;
2040
+ }
1866
2041
  this.reconnectAttempts++;
1867
- 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");
1868
2053
  this.reconnectTimer = setTimeout(() => {
1869
2054
  this.reconnectTimer = null;
1870
- void this.connect().catch((err) => {
1871
- this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
1872
- });
2055
+ this.retryNow();
1873
2056
  }, delay);
1874
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
+ }
1875
2109
  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));
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
+ }
1880
2186
  }
1881
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
+ }
1882
2196
  let handlers = this.handlers.get(event);
1883
2197
  if (!handlers) {
1884
2198
  handlers = /* @__PURE__ */ new Set();
1885
2199
  this.handlers.set(event, handlers);
1886
2200
  }
1887
- handlers.add(handler);
2201
+ const stored = handler;
2202
+ handlers.add(stored);
1888
2203
  return () => {
1889
- handlers.delete(handler);
2204
+ handlers.delete(stored);
1890
2205
  if (handlers.size === 0) this.handlers.delete(event);
1891
2206
  };
1892
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
+ */
1893
2221
  onError(handler) {
1894
2222
  this.errorHandlers.add(handler);
1895
2223
  return () => this.errorHandlers.delete(handler);
@@ -1940,38 +2268,63 @@ var RealtimeClient = class {
1940
2268
  get isConnected() {
1941
2269
  return this.authenticated && this.ws?.readyState === 1;
1942
2270
  }
2271
+ /** Where the connection lifecycle is right now. See `RealtimeState`. */
2272
+ get state() {
2273
+ return this._state;
2274
+ }
2275
+ /**
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
+ }
1943
2284
  /**
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.
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.
1947
2290
  */
1948
2291
  disconnect() {
2292
+ if (this.disposed) return;
1949
2293
  this.disposed = true;
1950
2294
  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
- }
2295
+ this.clearReconnectTimer();
2296
+ this.clearWatchdogs();
1959
2297
  this.cancelStabilityTimer();
1960
- this.drainAllPendingForShutdown();
2298
+ this.flushParkedFrames("gap_fill_unavailable");
2299
+ const ws = this.ws;
2300
+ this.ws = null;
1961
2301
  try {
1962
- this.ws?.close();
2302
+ ws?.close(1e3, "client disconnect");
1963
2303
  } catch {
1964
2304
  }
1965
- this.ws = null;
1966
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
+ }
1967
2314
  this.handlers.clear();
1968
2315
  this.errorHandlers.clear();
1969
2316
  this.connectHandlers.clear();
1970
2317
  this.disconnectHandlers.clear();
2318
+ this.stateHandlers.clear();
2319
+ this.blockedHandlers.clear();
2320
+ this.stoppedHandlers.clear();
1971
2321
  }
1972
2322
  emitError(error) {
1973
2323
  for (const handler of this.errorHandlers) {
1974
- handler(error);
2324
+ try {
2325
+ handler(error);
2326
+ } catch {
2327
+ }
1975
2328
  }
1976
2329
  }
1977
2330
  dispatch(message) {
@@ -2012,10 +2365,11 @@ var RealtimeClient = class {
2012
2365
  dispatchMessageNew(message) {
2013
2366
  const isDrainRow = this.restDrainOrigin.has(message);
2014
2367
  const messageId = this.extractMessageId(message);
2368
+ const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt;
2015
2369
  let settlement;
2016
2370
  if (messageId !== null && this.dedupHit(messageId)) {
2017
2371
  settlement = Promise.resolve(true);
2018
- if (!isDrainRow) this.sendAckFrame(messageId);
2372
+ if (ackAfterDispatch) this.sendAckFrame(messageId);
2019
2373
  } else {
2020
2374
  const handlers = this.handlers.get("message.new");
2021
2375
  const pending = [];
@@ -2040,7 +2394,7 @@ var RealtimeClient = class {
2040
2394
  if (!ok) return false;
2041
2395
  if (messageId !== null) {
2042
2396
  this.dedupAdd(messageId);
2043
- if (!isDrainRow) this.sendAckFrame(messageId);
2397
+ if (ackAfterDispatch) this.sendAckFrame(messageId);
2044
2398
  }
2045
2399
  return true;
2046
2400
  });
@@ -2088,12 +2442,45 @@ var RealtimeClient = class {
2088
2442
  isMessageNew(message) {
2089
2443
  return message.type === "message.new";
2090
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
+ }
2091
2475
  // ─── Per-conversation seq ordering ───────────────────────────────────────
2092
2476
  //
2093
2477
  // 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).
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.
2097
2484
  //
2098
2485
  // Why per-conversation instead of global: seq numbers are minted per
2099
2486
  // conversation by send_message_atomic, so cross-conversation arrivals
@@ -2117,6 +2504,7 @@ var RealtimeClient = class {
2117
2504
  return;
2118
2505
  }
2119
2506
  if (seq < state.nextExpectedSeq) {
2507
+ this.dispatch(message);
2120
2508
  return;
2121
2509
  }
2122
2510
  if (seq === state.nextExpectedSeq) {
@@ -2190,10 +2578,15 @@ var RealtimeClient = class {
2190
2578
  const rowSeq = typeof row.seq === "number" ? row.seq : null;
2191
2579
  if (rowSeq === null || rowSeq < expectedSeq) continue;
2192
2580
  if (state.buffer.has(rowSeq)) continue;
2193
- state.buffer.set(rowSeq, {
2581
+ const envelope = {
2194
2582
  type: "message.new",
2195
2583
  payload: row
2196
- });
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);
2197
2590
  }
2198
2591
  const drainedThroughGap = this.drainConsecutive(conversationId, state);
2199
2592
  if (drainedThroughGap) {
@@ -2308,7 +2701,11 @@ var RealtimeClient = class {
2308
2701
  }
2309
2702
  this.orderStates.clear();
2310
2703
  }
2311
- 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) {
2312
2709
  for (const [conversationId, state] of this.orderStates) {
2313
2710
  if (state.gapTimer !== null) {
2314
2711
  clearTimeout(state.gapTimer);
@@ -2324,13 +2721,268 @@ var RealtimeClient = class {
2324
2721
  bufferedSeq: seqs[0] ?? null,
2325
2722
  gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,
2326
2723
  recovered: false,
2327
- reason: "gap_fill_unavailable"
2724
+ reason
2328
2725
  });
2329
2726
  }
2330
2727
  this.orderStates.clear();
2331
2728
  }
2332
2729
  };
2333
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
+
2334
2986
  // src/render.ts
2335
2987
  var SEC = 1e3;
2336
2988
  var MIN = 60 * SEC;
@@ -2382,6 +3034,11 @@ function renderMessageContext(message, opts = {}) {
2382
3034
  return lines.join("\n");
2383
3035
  }
2384
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
+
2385
3042
  // src/types/attachment.ts
2386
3043
  var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
2387
3044
  var ALLOWED_ATTACHMENT_MIME = [
@@ -2401,6 +3058,6 @@ var ALLOWED_ATTACHMENT_MIME = [
2401
3058
  "video/webm"
2402
3059
  ];
2403
3060
 
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 };
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 };
2405
3062
  //# sourceMappingURL=index.js.map
2406
3063
  //# sourceMappingURL=index.js.map