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/CHANGELOG.md +147 -0
- package/README.md +109 -6
- package/dist/index.cjs +782 -120
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +728 -24
- package/dist/index.d.ts +728 -24
- package/dist/index.js +778 -121
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __export = (target, all) => {
|
|
5
|
+
for (var name in all)
|
|
6
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
7
|
+
};
|
|
8
|
+
|
|
3
9
|
// src/types/errors.ts
|
|
4
10
|
var ErrorCode = {
|
|
5
11
|
AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
|
|
@@ -270,7 +276,7 @@ function createAgentChatError(body, status, headers) {
|
|
|
270
276
|
}
|
|
271
277
|
|
|
272
278
|
// src/version.ts
|
|
273
|
-
var VERSION = "1.
|
|
279
|
+
var VERSION = "1.2.0" ;
|
|
274
280
|
|
|
275
281
|
// src/runtime.ts
|
|
276
282
|
function detectRuntime() {
|
|
@@ -647,10 +653,19 @@ function generateClientMsgId() {
|
|
|
647
653
|
}
|
|
648
654
|
return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
|
|
649
655
|
}
|
|
656
|
+
var INBOX_WAIT_TIMEOUT_GRACE_MS = 1e4;
|
|
650
657
|
var AgentChatClient = class _AgentChatClient {
|
|
651
658
|
http;
|
|
652
659
|
onBacklogWarning;
|
|
653
660
|
baseUrl;
|
|
661
|
+
/** The tray (`GET /v1/inbox`). */
|
|
662
|
+
inbox;
|
|
663
|
+
/** Gate verdicts (`POST /v1/conversations/{id}/decisions`). */
|
|
664
|
+
decisions;
|
|
665
|
+
/** Conversation read state (`POST /v1/conversations/{id}/read`). */
|
|
666
|
+
conversations;
|
|
667
|
+
/** Served texts (`GET /v1/texts`). */
|
|
668
|
+
texts;
|
|
654
669
|
constructor(options) {
|
|
655
670
|
this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
|
|
656
671
|
this.http = new HttpTransport({
|
|
@@ -663,6 +678,53 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
663
678
|
defaultHeaders: clientIdentityHeaders(options.clientIdentity)
|
|
664
679
|
});
|
|
665
680
|
this.onBacklogWarning = options.onBacklogWarning;
|
|
681
|
+
this.inbox = {
|
|
682
|
+
tray: (opts) => this.getInboxTray(opts)
|
|
683
|
+
};
|
|
684
|
+
this.decisions = {
|
|
685
|
+
record: (conversationId, opts) => this.recordDecision(conversationId, opts)
|
|
686
|
+
};
|
|
687
|
+
this.conversations = {
|
|
688
|
+
markRead: (conversationId, throughMessageId, opts) => this.markConversationRead(conversationId, throughMessageId, opts)
|
|
689
|
+
};
|
|
690
|
+
this.texts = {
|
|
691
|
+
get: (opts) => this.getTexts(opts)
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
// ─── Engine resource implementations ──────────────────────────────────────
|
|
695
|
+
getInboxTray(options) {
|
|
696
|
+
const params = new URLSearchParams();
|
|
697
|
+
const waitMs = options?.waitMs ?? 0;
|
|
698
|
+
if (waitMs > 0) params.set("wait_ms", String(waitMs));
|
|
699
|
+
if (options?.limit !== void 0) params.set("limit", String(options.limit));
|
|
700
|
+
const qs = params.toString();
|
|
701
|
+
const timeoutMs = options?.timeoutMs !== void 0 ? options.timeoutMs : waitMs > 0 ? waitMs + INBOX_WAIT_TIMEOUT_GRACE_MS : void 0;
|
|
702
|
+
return this.get(`/v1/inbox${qs ? `?${qs}` : ""}`, { ...options, timeoutMs });
|
|
703
|
+
}
|
|
704
|
+
async recordDecision(conversationId, options) {
|
|
705
|
+
const body = {
|
|
706
|
+
decision: options.decision,
|
|
707
|
+
category: options.category,
|
|
708
|
+
through_message_id: options.throughMessageId
|
|
709
|
+
};
|
|
710
|
+
const res = await this.post(
|
|
711
|
+
`/v1/conversations/${encodeURIComponent(conversationId)}/decisions`,
|
|
712
|
+
body,
|
|
713
|
+
options
|
|
714
|
+
);
|
|
715
|
+
return res.decision;
|
|
716
|
+
}
|
|
717
|
+
markConversationRead(conversationId, throughMessageId, options) {
|
|
718
|
+
const body = { through_message_id: throughMessageId };
|
|
719
|
+
return this.post(
|
|
720
|
+
`/v1/conversations/${encodeURIComponent(conversationId)}/read`,
|
|
721
|
+
body,
|
|
722
|
+
options
|
|
723
|
+
);
|
|
724
|
+
}
|
|
725
|
+
getTexts(options) {
|
|
726
|
+
const params = new URLSearchParams({ runtime: options.runtime });
|
|
727
|
+
return this.get(`/v1/texts?${params.toString()}`, options);
|
|
666
728
|
}
|
|
667
729
|
// ─── Internal request helpers ─────────────────────────────────────────────
|
|
668
730
|
async get(path, opts) {
|
|
@@ -1428,33 +1490,60 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
1428
1490
|
};
|
|
1429
1491
|
|
|
1430
1492
|
// src/ws-resolver.ts
|
|
1431
|
-
|
|
1493
|
+
function isNode() {
|
|
1494
|
+
const versions = globalThis.process?.versions;
|
|
1495
|
+
return typeof versions?.node === "string";
|
|
1496
|
+
}
|
|
1497
|
+
async function importWs() {
|
|
1498
|
+
const mod = await import('ws');
|
|
1499
|
+
const ctor = mod.default ?? mod.WebSocket;
|
|
1500
|
+
if (!ctor) {
|
|
1501
|
+
throw new Error("The `ws` package loaded but did not export a WebSocket constructor.");
|
|
1502
|
+
}
|
|
1503
|
+
return ctor;
|
|
1504
|
+
}
|
|
1432
1505
|
async function resolveWebSocket() {
|
|
1433
|
-
if (cached) return cached;
|
|
1434
1506
|
const native = globalThis.WebSocket;
|
|
1435
|
-
if (native)
|
|
1436
|
-
|
|
1437
|
-
return native;
|
|
1438
|
-
}
|
|
1507
|
+
if (!isNode() && native) return native;
|
|
1508
|
+
let wsFailure;
|
|
1439
1509
|
try {
|
|
1440
|
-
|
|
1441
|
-
const ctor = mod.default ?? mod.WebSocket;
|
|
1442
|
-
if (!ctor) {
|
|
1443
|
-
throw new Error("The `ws` package loaded but did not export a WebSocket constructor.");
|
|
1444
|
-
}
|
|
1445
|
-
cached = ctor;
|
|
1446
|
-
return ctor;
|
|
1510
|
+
return await importWs();
|
|
1447
1511
|
} catch (err) {
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1512
|
+
wsFailure = err;
|
|
1513
|
+
}
|
|
1514
|
+
if (native) return native;
|
|
1515
|
+
const reason = wsFailure instanceof Error ? wsFailure.message : String(wsFailure);
|
|
1516
|
+
throw new Error(
|
|
1517
|
+
`AgentChat SDK: no WebSocket implementation available. ${reason}
|
|
1518
|
+
Install the \`ws\` package: Node 20 has no native WebSocket, and on Node 22+ \`ws\` also gives the realtime client ping-frame liveness.`
|
|
1519
|
+
);
|
|
1454
1520
|
}
|
|
1455
1521
|
|
|
1456
1522
|
// src/realtime.ts
|
|
1457
|
-
var
|
|
1523
|
+
var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15e3;
|
|
1524
|
+
var DEFAULT_LIVENESS_TIMEOUT_MS = 1e5;
|
|
1525
|
+
var CLIENT_CLOSE_CODE = 4e3;
|
|
1526
|
+
var LONG_OUTAGE_AFTER_ATTEMPTS = 60;
|
|
1527
|
+
var LONG_OUTAGE_MAX_INTERVAL_MS = 5 * 6e4;
|
|
1528
|
+
var RECONNECT_JITTER_RATIO = 0.25;
|
|
1529
|
+
var AUTH_RETRY_INTERVAL_MS = 75e4;
|
|
1530
|
+
var AUTH_RETRY_JITTER_RATIO = 0.2;
|
|
1531
|
+
var UNAMBIGUOUS_AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([4401, 4403]);
|
|
1532
|
+
var AMBIGUOUS_AUTH_CLOSE_CODE = 1008;
|
|
1533
|
+
var SERVER_AUTH_CLOSE_REASONS = ["invalid token"];
|
|
1534
|
+
function isAuthRejectionClose(code, reason) {
|
|
1535
|
+
if (UNAMBIGUOUS_AUTH_CLOSE_CODES.has(code)) return true;
|
|
1536
|
+
if (code !== AMBIGUOUS_AUTH_CLOSE_CODE) return false;
|
|
1537
|
+
if (typeof reason !== "string") return false;
|
|
1538
|
+
const lower = reason.toLowerCase();
|
|
1539
|
+
return SERVER_AUTH_CLOSE_REASONS.some((known) => lower.includes(known));
|
|
1540
|
+
}
|
|
1541
|
+
function isPingCapable(ws) {
|
|
1542
|
+
return typeof ws.on === "function";
|
|
1543
|
+
}
|
|
1544
|
+
function unref(timer) {
|
|
1545
|
+
timer.unref?.();
|
|
1546
|
+
}
|
|
1458
1547
|
var STABLE_CONNECTION_MS = 3e4;
|
|
1459
1548
|
var RAPID_RECONNECT_MS = 6e4;
|
|
1460
1549
|
var INSTABILITY_WARN_THRESHOLD = 5;
|
|
@@ -1463,7 +1552,6 @@ var MAX_BUFFERED_PER_CONVERSATION = 500;
|
|
|
1463
1552
|
var GAP_FILL_LIMIT = 200;
|
|
1464
1553
|
var SYNC_DRAIN_PAGE_SIZE = 200;
|
|
1465
1554
|
var DEFAULT_DEDUP_CACHE_SIZE = 2048;
|
|
1466
|
-
var TERMINAL_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401, 4403]);
|
|
1467
1555
|
function isValidSyncRow(row) {
|
|
1468
1556
|
if (typeof row !== "object" || row === null || Array.isArray(row)) return false;
|
|
1469
1557
|
const r = row;
|
|
@@ -1498,6 +1586,11 @@ var RealtimeClient = class {
|
|
|
1498
1586
|
errorHandlers = /* @__PURE__ */ new Set();
|
|
1499
1587
|
connectHandlers = /* @__PURE__ */ new Set();
|
|
1500
1588
|
disconnectHandlers = /* @__PURE__ */ new Set();
|
|
1589
|
+
stateHandlers = /* @__PURE__ */ new Set();
|
|
1590
|
+
blockedHandlers = /* @__PURE__ */ new Set();
|
|
1591
|
+
stoppedHandlers = /* @__PURE__ */ new Set();
|
|
1592
|
+
_state = "idle";
|
|
1593
|
+
/** Consecutive failed attempts; drives the backoff. Cleared by the stability timer only. */
|
|
1501
1594
|
reconnectAttempts = 0;
|
|
1502
1595
|
/** Clears reconnectAttempts once this connection proves itself stable. */
|
|
1503
1596
|
stabilityTimer = null;
|
|
@@ -1505,16 +1598,23 @@ var RealtimeClient = class {
|
|
|
1505
1598
|
* the operator warning only; backoff itself uses reconnectAttempts. */
|
|
1506
1599
|
rapidReconnects = 0;
|
|
1507
1600
|
lastConnectAt = null;
|
|
1601
|
+
/** The pending backoff or blocked-retry timer — at most one at a time. */
|
|
1508
1602
|
reconnectTimer = null;
|
|
1509
|
-
|
|
1603
|
+
/** Handshake deadline: armed by connect(), cleared by hello.ok or close. */
|
|
1604
|
+
handshakeTimer = null;
|
|
1605
|
+
/** Idle deadline: armed by hello.ok; inbound frames and pings refresh it. */
|
|
1606
|
+
livenessTimer = null;
|
|
1607
|
+
/** Idle deadline in effect for the current socket; 0 = off. */
|
|
1608
|
+
livenessMs = 0;
|
|
1609
|
+
lastInboundAt = 0;
|
|
1510
1610
|
authenticated = false;
|
|
1511
1611
|
// True only when the server echoed the 'ack' capability in hello.ok.
|
|
1512
1612
|
// Per-connection: reset on every close and re-negotiated on every HELLO.
|
|
1513
1613
|
ackMode = false;
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1614
|
+
/** One error per long outage, then silent until a stable connection. */
|
|
1615
|
+
longOutageAnnounced = false;
|
|
1616
|
+
/** One error per run of rejected handshakes, then silent until hello.ok. */
|
|
1617
|
+
blockedAnnounced = false;
|
|
1518
1618
|
// Bounded LRU of recently-dispatched message ids (Set iteration order is
|
|
1519
1619
|
// insertion order — delete + re-add refreshes recency). Ids are added
|
|
1520
1620
|
// only AFTER a successful dispatch: adding earlier would let a failed
|
|
@@ -1539,51 +1639,73 @@ var RealtimeClient = class {
|
|
|
1539
1639
|
disposed = false;
|
|
1540
1640
|
constructor(options) {
|
|
1541
1641
|
const dedupCacheSize = typeof options.dedupCacheSize === "number" && Number.isFinite(options.dedupCacheSize) && options.dedupCacheSize >= 1 ? Math.floor(options.dedupCacheSize) : DEFAULT_DEDUP_CACHE_SIZE;
|
|
1642
|
+
const handshakeTimeoutMs = typeof options.handshakeTimeoutMs === "number" && Number.isFinite(options.handshakeTimeoutMs) && options.handshakeTimeoutMs > 0 ? options.handshakeTimeoutMs : DEFAULT_HANDSHAKE_TIMEOUT_MS;
|
|
1643
|
+
const livenessTimeoutMs = typeof options.livenessTimeoutMs === "number" && Number.isFinite(options.livenessTimeoutMs) && options.livenessTimeoutMs >= 0 ? options.livenessTimeoutMs : null;
|
|
1542
1644
|
this.options = {
|
|
1543
1645
|
baseUrl: options.baseUrl ?? "wss://api.agentchat.me",
|
|
1544
1646
|
reconnect: options.reconnect ?? true,
|
|
1545
1647
|
reconnectInterval: options.reconnectInterval ?? 500,
|
|
1546
1648
|
maxReconnectInterval: options.maxReconnectInterval ?? 3e4,
|
|
1547
|
-
|
|
1649
|
+
handshakeTimeoutMs,
|
|
1650
|
+
livenessTimeoutMs,
|
|
1548
1651
|
apiKey: options.apiKey,
|
|
1549
1652
|
client: options.client,
|
|
1550
1653
|
onSequenceGap: options.onSequenceGap,
|
|
1551
1654
|
autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),
|
|
1552
1655
|
dedupCacheSize,
|
|
1656
|
+
ackOnReceipt: options.ackOnReceipt ?? false,
|
|
1553
1657
|
webSocket: options.webSocket,
|
|
1554
1658
|
clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY
|
|
1555
1659
|
};
|
|
1556
1660
|
}
|
|
1557
1661
|
/**
|
|
1558
1662
|
* Open the WebSocket connection and perform the HELLO handshake.
|
|
1559
|
-
* Resolves once the socket
|
|
1560
|
-
* NOT after `hello.ok`. Listen for `onConnect()`
|
|
1561
|
-
* completed handshake.
|
|
1663
|
+
* Resolves once the socket has been constructed and its handlers bound —
|
|
1664
|
+
* NOT after `hello.ok`. Listen for `onConnect()` or `on('state')` to react
|
|
1665
|
+
* to a completed handshake.
|
|
1562
1666
|
*
|
|
1563
|
-
*
|
|
1564
|
-
*
|
|
1667
|
+
* Also the way to retry at once: called while `backoff` or `blocked`, it
|
|
1668
|
+
* cancels the pending timer and opens a socket now. A no-op while a socket
|
|
1669
|
+
* is already connecting or connected. Throws after `disconnect()` — create
|
|
1670
|
+
* a fresh `RealtimeClient` instead. Rejects, without retrying, when no
|
|
1671
|
+
* WebSocket implementation exists (neither `ws` nor a native one): that is
|
|
1672
|
+
* a configuration error and the client stays `idle`.
|
|
1565
1673
|
*/
|
|
1566
1674
|
async connect() {
|
|
1567
1675
|
if (this.disposed) {
|
|
1568
1676
|
throw new ConnectionError("RealtimeClient has been disposed; create a new instance to reconnect.");
|
|
1569
1677
|
}
|
|
1678
|
+
if (this.ws) return;
|
|
1679
|
+
this.clearReconnectTimer();
|
|
1570
1680
|
let WebSocketCtor;
|
|
1571
1681
|
try {
|
|
1572
1682
|
WebSocketCtor = this.options.webSocket ?? await resolveWebSocket();
|
|
1573
1683
|
} catch (err) {
|
|
1574
|
-
|
|
1684
|
+
this.setState("idle");
|
|
1685
|
+
throw err instanceof Error ? err : new ConnectionError("Failed to resolve WebSocket");
|
|
1686
|
+
}
|
|
1687
|
+
if (this.disposed || this.ws) return;
|
|
1688
|
+
this.setState("connecting");
|
|
1689
|
+
const url = `${this.options.baseUrl}/v1/ws`;
|
|
1690
|
+
let ws;
|
|
1691
|
+
try {
|
|
1692
|
+
ws = new WebSocketCtor(url);
|
|
1693
|
+
} catch (err) {
|
|
1694
|
+
const error = err instanceof Error ? err : new ConnectionError("WebSocket constructor threw");
|
|
1575
1695
|
this.emitError(error);
|
|
1576
1696
|
this.scheduleReconnect();
|
|
1577
1697
|
throw error;
|
|
1578
1698
|
}
|
|
1579
|
-
|
|
1580
|
-
this.ws = new WebSocketCtor(url);
|
|
1699
|
+
this.ws = ws;
|
|
1581
1700
|
this.authenticated = false;
|
|
1582
1701
|
this.ackMode = false;
|
|
1583
|
-
this.
|
|
1584
|
-
this.
|
|
1702
|
+
this.livenessMs = this.options.livenessTimeoutMs ?? (isPingCapable(ws) ? DEFAULT_LIVENESS_TIMEOUT_MS : 0);
|
|
1703
|
+
this.armHandshakeDeadline();
|
|
1704
|
+
const current = () => this.ws === ws;
|
|
1705
|
+
ws.onopen = () => {
|
|
1706
|
+
if (!current()) return;
|
|
1585
1707
|
try {
|
|
1586
|
-
|
|
1708
|
+
ws.send(
|
|
1587
1709
|
JSON.stringify({
|
|
1588
1710
|
type: "hello",
|
|
1589
1711
|
api_key: this.options.apiKey,
|
|
@@ -1594,18 +1716,12 @@ var RealtimeClient = class {
|
|
|
1594
1716
|
);
|
|
1595
1717
|
} catch (err) {
|
|
1596
1718
|
this.emitError(err instanceof Error ? err : new ConnectionError("HELLO send failed"));
|
|
1597
|
-
|
|
1719
|
+
this.abandonSocket(CLIENT_CLOSE_CODE, "client HELLO send failed");
|
|
1598
1720
|
}
|
|
1599
|
-
this.helloAckTimer = setTimeout(() => {
|
|
1600
|
-
this.emitError(new ConnectionError("HELLO ack timeout"));
|
|
1601
|
-
this.helloTimeoutClose = true;
|
|
1602
|
-
try {
|
|
1603
|
-
this.ws?.close(1008, "HELLO ack timeout");
|
|
1604
|
-
} catch {
|
|
1605
|
-
}
|
|
1606
|
-
}, HELLO_ACK_TIMEOUT_MS);
|
|
1607
1721
|
};
|
|
1608
|
-
|
|
1722
|
+
ws.onmessage = (event) => {
|
|
1723
|
+
if (!current()) return;
|
|
1724
|
+
this.touchLiveness();
|
|
1609
1725
|
let message;
|
|
1610
1726
|
try {
|
|
1611
1727
|
message = JSON.parse(String(event.data));
|
|
@@ -1617,11 +1733,11 @@ var RealtimeClient = class {
|
|
|
1617
1733
|
this.authenticated = true;
|
|
1618
1734
|
const caps = message.capabilities;
|
|
1619
1735
|
this.ackMode = Array.isArray(caps) && caps.includes("ack");
|
|
1736
|
+
this.clearHandshakeTimer();
|
|
1737
|
+
this.touchLiveness();
|
|
1620
1738
|
this.startStabilityTimer();
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
this.helloAckTimer = null;
|
|
1624
|
-
}
|
|
1739
|
+
this.blockedAnnounced = false;
|
|
1740
|
+
this.setState("ready");
|
|
1625
1741
|
for (const handler of this.connectHandlers) {
|
|
1626
1742
|
try {
|
|
1627
1743
|
handler();
|
|
@@ -1639,42 +1755,42 @@ var RealtimeClient = class {
|
|
|
1639
1755
|
return;
|
|
1640
1756
|
}
|
|
1641
1757
|
if (this.isMessageNew(message)) {
|
|
1758
|
+
if (this.options.ackOnReceipt) {
|
|
1759
|
+
const messageId = this.extractMessageId(message);
|
|
1760
|
+
if (messageId !== null) this.sendAckFrame(messageId);
|
|
1761
|
+
}
|
|
1642
1762
|
this.processOrderedMessage(message);
|
|
1643
1763
|
return;
|
|
1644
1764
|
}
|
|
1765
|
+
if (this.isWake(message)) {
|
|
1766
|
+
this.dispatchWake(message);
|
|
1767
|
+
return;
|
|
1768
|
+
}
|
|
1645
1769
|
this.dispatch(message);
|
|
1646
1770
|
};
|
|
1647
|
-
|
|
1771
|
+
ws.onerror = () => {
|
|
1772
|
+
if (!current()) return;
|
|
1648
1773
|
this.emitError(new ConnectionError("WebSocket error"));
|
|
1649
1774
|
};
|
|
1650
|
-
|
|
1651
|
-
if (
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
for (const handler of this.disconnectHandlers) {
|
|
1662
|
-
try {
|
|
1663
|
-
handler({ code: event.code, reason: event.reason, wasClean: event.wasClean });
|
|
1664
|
-
} catch {
|
|
1665
|
-
}
|
|
1666
|
-
}
|
|
1667
|
-
this.resetOrderStates();
|
|
1668
|
-
if (TERMINAL_CLOSE_CODES.has(event.code) && !selfClosedForHelloTimeout) {
|
|
1669
|
-
this.emitError(
|
|
1670
|
-
new ConnectionError(
|
|
1671
|
-
`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.`
|
|
1672
|
-
)
|
|
1673
|
-
);
|
|
1674
|
-
return;
|
|
1675
|
-
}
|
|
1676
|
-
this.scheduleReconnect();
|
|
1775
|
+
ws.onclose = (event) => {
|
|
1776
|
+
if (!current()) return;
|
|
1777
|
+
this.ws = null;
|
|
1778
|
+
this.handleClose({
|
|
1779
|
+
code: event.code,
|
|
1780
|
+
// A polyfilled socket may omit the reason; the rejection rule
|
|
1781
|
+
// lowercases it, so it must be a string here.
|
|
1782
|
+
reason: String(event.reason ?? ""),
|
|
1783
|
+
wasClean: event.wasClean,
|
|
1784
|
+
initiator: "server"
|
|
1785
|
+
});
|
|
1677
1786
|
};
|
|
1787
|
+
if (isPingCapable(ws)) {
|
|
1788
|
+
const alive = () => {
|
|
1789
|
+
if (current()) this.touchLiveness();
|
|
1790
|
+
};
|
|
1791
|
+
ws.on("ping", alive);
|
|
1792
|
+
ws.on("pong", alive);
|
|
1793
|
+
}
|
|
1678
1794
|
}
|
|
1679
1795
|
/**
|
|
1680
1796
|
* Drain offline envelopes accumulated while the socket was disconnected.
|
|
@@ -1831,8 +1947,9 @@ var RealtimeClient = class {
|
|
|
1831
1947
|
if (this.disposed || !this.authenticated) return;
|
|
1832
1948
|
this.reconnectAttempts = 0;
|
|
1833
1949
|
this.rapidReconnects = 0;
|
|
1950
|
+
this.longOutageAnnounced = false;
|
|
1834
1951
|
}, STABLE_CONNECTION_MS);
|
|
1835
|
-
this.stabilityTimer
|
|
1952
|
+
unref(this.stabilityTimer);
|
|
1836
1953
|
}
|
|
1837
1954
|
cancelStabilityTimer() {
|
|
1838
1955
|
if (this.stabilityTimer) {
|
|
@@ -1844,6 +1961,8 @@ var RealtimeClient = class {
|
|
|
1844
1961
|
* Track short-lived connections and warn once they form a pattern.
|
|
1845
1962
|
* A flapping client looks healthy from the inside — every reconnect
|
|
1846
1963
|
* succeeds — so without this the operator has no local signal at all.
|
|
1964
|
+
* The notice goes through `onError` like every other signal: an SDK
|
|
1965
|
+
* that runs as a guest inside a host process does not own its console.
|
|
1847
1966
|
*/
|
|
1848
1967
|
noteConnectionEnded() {
|
|
1849
1968
|
const started = this.lastConnectAt;
|
|
@@ -1855,43 +1974,252 @@ var RealtimeClient = class {
|
|
|
1855
1974
|
}
|
|
1856
1975
|
this.rapidReconnects++;
|
|
1857
1976
|
if (this.rapidReconnects === INSTABILITY_WARN_THRESHOLD) {
|
|
1858
|
-
|
|
1859
|
-
|
|
1977
|
+
this.emitError(
|
|
1978
|
+
new ConnectionError(
|
|
1979
|
+
`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.`
|
|
1980
|
+
)
|
|
1860
1981
|
);
|
|
1861
1982
|
}
|
|
1862
1983
|
}
|
|
1984
|
+
// ─── Lifecycle: close funnel, backoff, blocked, watchdogs ───────────────
|
|
1985
|
+
//
|
|
1986
|
+
// Invariant: the client never parks itself. Every close leads to a timer
|
|
1987
|
+
// (backoff or blocked retry) or, with `reconnect: false`, to `idle` where
|
|
1988
|
+
// the application's next connect() picks up. Only disconnect() ends it.
|
|
1989
|
+
/**
|
|
1990
|
+
* The single funnel for "this socket is over", whoever ended it. Runs
|
|
1991
|
+
* after `this.ws` has been let go of, so nothing here touches the socket
|
|
1992
|
+
* again. Decides what comes next — backoff, blocked or idle, never nothing.
|
|
1993
|
+
*/
|
|
1994
|
+
handleClose(info) {
|
|
1995
|
+
const duringHandshake = !this.authenticated;
|
|
1996
|
+
this.clearWatchdogs();
|
|
1997
|
+
this.cancelStabilityTimer();
|
|
1998
|
+
this.noteConnectionEnded();
|
|
1999
|
+
this.authenticated = false;
|
|
2000
|
+
this.ackMode = false;
|
|
2001
|
+
for (const handler of this.disconnectHandlers) {
|
|
2002
|
+
try {
|
|
2003
|
+
handler(info);
|
|
2004
|
+
} catch {
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
if (this.options.ackOnReceipt) this.flushParkedFrames("connection_closed");
|
|
2008
|
+
this.resetOrderStates();
|
|
2009
|
+
if (this.disposed) return;
|
|
2010
|
+
if (info.initiator === "server" && duringHandshake && isAuthRejectionClose(info.code, info.reason)) {
|
|
2011
|
+
this.enterBlocked(info.code, info.reason);
|
|
2012
|
+
return;
|
|
2013
|
+
}
|
|
2014
|
+
this.scheduleReconnect();
|
|
2015
|
+
}
|
|
2016
|
+
/**
|
|
2017
|
+
* End the current socket on the client's own decision (a watchdog trip,
|
|
2018
|
+
* a HELLO that could not be sent) and move on at once, without waiting for
|
|
2019
|
+
* the socket's close event: on a dead pipe a polite close waits for a
|
|
2020
|
+
* reply that never comes. Terminated where the API allows it (Node `ws`),
|
|
2021
|
+
* closed otherwise; its own late events are ignored because it is no
|
|
2022
|
+
* longer `this.ws`.
|
|
2023
|
+
*/
|
|
2024
|
+
abandonSocket(code, reason) {
|
|
2025
|
+
const ws = this.ws;
|
|
2026
|
+
if (!ws) return;
|
|
2027
|
+
this.ws = null;
|
|
2028
|
+
const terminate = ws.terminate;
|
|
2029
|
+
try {
|
|
2030
|
+
if (typeof terminate === "function") terminate.call(ws);
|
|
2031
|
+
else ws.close(code, reason);
|
|
2032
|
+
} catch {
|
|
2033
|
+
}
|
|
2034
|
+
this.handleClose({ code, reason, wasClean: false, initiator: "client" });
|
|
2035
|
+
}
|
|
1863
2036
|
scheduleReconnect() {
|
|
1864
2037
|
if (this.disposed) return;
|
|
1865
|
-
if (!this.options.reconnect) return;
|
|
1866
|
-
if (this.reconnectAttempts >= this.options.maxReconnectAttempts) return;
|
|
1867
2038
|
if (this.reconnectTimer) return;
|
|
2039
|
+
if (!this.options.reconnect) {
|
|
2040
|
+
this.setState("idle");
|
|
2041
|
+
return;
|
|
2042
|
+
}
|
|
1868
2043
|
this.reconnectAttempts++;
|
|
1869
|
-
const
|
|
2044
|
+
const attempt = this.reconnectAttempts;
|
|
2045
|
+
if (attempt > LONG_OUTAGE_AFTER_ATTEMPTS && !this.longOutageAnnounced) {
|
|
2046
|
+
this.longOutageAnnounced = true;
|
|
2047
|
+
this.emitError(
|
|
2048
|
+
new ConnectionError(
|
|
2049
|
+
`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`
|
|
2050
|
+
)
|
|
2051
|
+
);
|
|
2052
|
+
}
|
|
2053
|
+
const delay = this.computeReconnectDelay(attempt);
|
|
2054
|
+
this.setState("backoff");
|
|
1870
2055
|
this.reconnectTimer = setTimeout(() => {
|
|
1871
2056
|
this.reconnectTimer = null;
|
|
1872
|
-
|
|
1873
|
-
this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
|
|
1874
|
-
});
|
|
2057
|
+
this.retryNow();
|
|
1875
2058
|
}, delay);
|
|
1876
2059
|
}
|
|
2060
|
+
/**
|
|
2061
|
+
* The server rejected the credential. `blocked` is not the end: a fresh
|
|
2062
|
+
* HELLO goes out every AUTH_RETRY_INTERVAL_MS (jittered) until one is
|
|
2063
|
+
* accepted — keys get rotated back and accounts get reinstated, and the
|
|
2064
|
+
* running client has no other way to learn it. The first rejection of a
|
|
2065
|
+
* run is an error; the following ones only fire `blocked`, so an operator
|
|
2066
|
+
* sees one line per incident rather than one every quarter hour.
|
|
2067
|
+
*/
|
|
2068
|
+
enterBlocked(code, reason) {
|
|
2069
|
+
const retryInMs = this.options.reconnect ? this.jittered(AUTH_RETRY_INTERVAL_MS, AUTH_RETRY_JITTER_RATIO) : null;
|
|
2070
|
+
this.setState("blocked");
|
|
2071
|
+
if (!this.blockedAnnounced) {
|
|
2072
|
+
this.blockedAnnounced = true;
|
|
2073
|
+
this.emitError(
|
|
2074
|
+
new ConnectionError(
|
|
2075
|
+
`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")
|
|
2076
|
+
)
|
|
2077
|
+
);
|
|
2078
|
+
}
|
|
2079
|
+
const info = { code, reason, retryInMs };
|
|
2080
|
+
for (const handler of this.blockedHandlers) {
|
|
2081
|
+
try {
|
|
2082
|
+
handler(info);
|
|
2083
|
+
} catch {
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
if (retryInMs === null) return;
|
|
2087
|
+
this.reconnectTimer = setTimeout(() => {
|
|
2088
|
+
this.reconnectTimer = null;
|
|
2089
|
+
this.retryNow();
|
|
2090
|
+
}, retryInMs);
|
|
2091
|
+
}
|
|
2092
|
+
/**
|
|
2093
|
+
* The timer-driven attempt. connect() emits and re-arms on its own for
|
|
2094
|
+
* every failure it retries (a throwing constructor, a close); the one
|
|
2095
|
+
* failure it does not retry — no WebSocket implementation at all — left
|
|
2096
|
+
* nothing armed, so it is announced here: the operator should see why the
|
|
2097
|
+
* client went quiet.
|
|
2098
|
+
*/
|
|
2099
|
+
retryNow() {
|
|
2100
|
+
void this.connect().catch((err) => {
|
|
2101
|
+
if (this.disposed || this.ws || this.reconnectTimer) return;
|
|
2102
|
+
this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
|
|
2103
|
+
});
|
|
2104
|
+
}
|
|
2105
|
+
clearReconnectTimer() {
|
|
2106
|
+
if (this.reconnectTimer) {
|
|
2107
|
+
clearTimeout(this.reconnectTimer);
|
|
2108
|
+
this.reconnectTimer = null;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
1877
2111
|
computeReconnectDelay(attempt) {
|
|
1878
|
-
const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1,
|
|
1879
|
-
const
|
|
1880
|
-
|
|
1881
|
-
|
|
2112
|
+
const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 20));
|
|
2113
|
+
const cap = attempt > LONG_OUTAGE_AFTER_ATTEMPTS ? this.longOutageCap() : this.options.maxReconnectInterval;
|
|
2114
|
+
return this.jitteredBelow(Math.min(exp, cap), RECONNECT_JITTER_RATIO);
|
|
2115
|
+
}
|
|
2116
|
+
longOutageCap() {
|
|
2117
|
+
return Math.max(this.options.maxReconnectInterval, LONG_OUTAGE_MAX_INTERVAL_MS);
|
|
2118
|
+
}
|
|
2119
|
+
/** Symmetric ±ratio jitter around `ms` — for the blocked retry, a range (10–15 min), not a cap. */
|
|
2120
|
+
jittered(ms, ratio) {
|
|
2121
|
+
const factor = 1 - ratio + Math.random() * 2 * ratio;
|
|
2122
|
+
return Math.max(0, Math.floor(ms * factor));
|
|
2123
|
+
}
|
|
2124
|
+
/** Jitter in [ms × (1 − ratio), ms]: `ms` is a ceiling. Thundering-herd-safe across a fleet. */
|
|
2125
|
+
jitteredBelow(ms, ratio) {
|
|
2126
|
+
const factor = 1 - Math.random() * ratio;
|
|
2127
|
+
return Math.max(0, Math.floor(ms * factor));
|
|
2128
|
+
}
|
|
2129
|
+
armHandshakeDeadline() {
|
|
2130
|
+
this.clearHandshakeTimer();
|
|
2131
|
+
const ms = this.options.handshakeTimeoutMs;
|
|
2132
|
+
this.handshakeTimer = setTimeout(() => {
|
|
2133
|
+
this.handshakeTimer = null;
|
|
2134
|
+
this.emitError(new ConnectionError(`handshake timeout: no hello.ok within ${ms}ms`));
|
|
2135
|
+
this.abandonSocket(CLIENT_CLOSE_CODE, "client handshake timeout");
|
|
2136
|
+
}, ms);
|
|
2137
|
+
unref(this.handshakeTimer);
|
|
2138
|
+
}
|
|
2139
|
+
/**
|
|
2140
|
+
* Note proof of life (any inbound frame, or a ping/pong on a socket that
|
|
2141
|
+
* shows them). The timer itself is lazy: it is armed once per connection
|
|
2142
|
+
* and, when it fires early because traffic arrived meanwhile, re-arms for
|
|
2143
|
+
* the remainder — one `Date.now()` per frame instead of a timer churn.
|
|
2144
|
+
*/
|
|
2145
|
+
touchLiveness() {
|
|
2146
|
+
this.lastInboundAt = Date.now();
|
|
2147
|
+
if (this.livenessTimer === null) this.armLiveness(this.livenessMs);
|
|
2148
|
+
}
|
|
2149
|
+
armLiveness(ms) {
|
|
2150
|
+
if (this.livenessMs <= 0 || !this.ws || !this.authenticated) return;
|
|
2151
|
+
this.livenessTimer = setTimeout(() => {
|
|
2152
|
+
this.livenessTimer = null;
|
|
2153
|
+
const quietFor = Date.now() - this.lastInboundAt;
|
|
2154
|
+
if (quietFor < this.livenessMs) {
|
|
2155
|
+
this.armLiveness(this.livenessMs - quietFor);
|
|
2156
|
+
return;
|
|
2157
|
+
}
|
|
2158
|
+
this.emitError(
|
|
2159
|
+
new ConnectionError(`liveness timeout: nothing received for ${this.livenessMs}ms`)
|
|
2160
|
+
);
|
|
2161
|
+
this.abandonSocket(CLIENT_CLOSE_CODE, "client liveness timeout");
|
|
2162
|
+
}, Math.max(1, ms));
|
|
2163
|
+
unref(this.livenessTimer);
|
|
2164
|
+
}
|
|
2165
|
+
clearHandshakeTimer() {
|
|
2166
|
+
if (this.handshakeTimer) {
|
|
2167
|
+
clearTimeout(this.handshakeTimer);
|
|
2168
|
+
this.handshakeTimer = null;
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
clearWatchdogs() {
|
|
2172
|
+
this.clearHandshakeTimer();
|
|
2173
|
+
if (this.livenessTimer) {
|
|
2174
|
+
clearTimeout(this.livenessTimer);
|
|
2175
|
+
this.livenessTimer = null;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
setState(next) {
|
|
2179
|
+
const previous = this._state;
|
|
2180
|
+
if (previous === next) return;
|
|
2181
|
+
this._state = next;
|
|
2182
|
+
for (const handler of this.stateHandlers) {
|
|
2183
|
+
try {
|
|
2184
|
+
handler(next, previous);
|
|
2185
|
+
} catch {
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
1882
2188
|
}
|
|
1883
2189
|
on(event, handler) {
|
|
2190
|
+
switch (event) {
|
|
2191
|
+
case "state":
|
|
2192
|
+
return this.subscribe(this.stateHandlers, handler);
|
|
2193
|
+
case "blocked":
|
|
2194
|
+
return this.subscribe(this.blockedHandlers, handler);
|
|
2195
|
+
case "stopped":
|
|
2196
|
+
return this.subscribe(this.stoppedHandlers, handler);
|
|
2197
|
+
}
|
|
1884
2198
|
let handlers = this.handlers.get(event);
|
|
1885
2199
|
if (!handlers) {
|
|
1886
2200
|
handlers = /* @__PURE__ */ new Set();
|
|
1887
2201
|
this.handlers.set(event, handlers);
|
|
1888
2202
|
}
|
|
1889
|
-
|
|
2203
|
+
const stored = handler;
|
|
2204
|
+
handlers.add(stored);
|
|
1890
2205
|
return () => {
|
|
1891
|
-
handlers.delete(
|
|
2206
|
+
handlers.delete(stored);
|
|
1892
2207
|
if (handlers.size === 0) this.handlers.delete(event);
|
|
1893
2208
|
};
|
|
1894
2209
|
}
|
|
2210
|
+
subscribe(set, handler) {
|
|
2211
|
+
set.add(handler);
|
|
2212
|
+
return () => {
|
|
2213
|
+
set.delete(handler);
|
|
2214
|
+
};
|
|
2215
|
+
}
|
|
2216
|
+
/**
|
|
2217
|
+
* Every signal the client has for its operator comes through here:
|
|
2218
|
+
* transport errors, handler failures, the watchdog and backoff notices
|
|
2219
|
+
* (`handshake timeout`, `liveness timeout`, `still reconnecting after
|
|
2220
|
+
* 60 …`, `server rejected the credential …`, `connection is unstable`).
|
|
2221
|
+
* The SDK never writes to the console.
|
|
2222
|
+
*/
|
|
1895
2223
|
onError(handler) {
|
|
1896
2224
|
this.errorHandlers.add(handler);
|
|
1897
2225
|
return () => this.errorHandlers.delete(handler);
|
|
@@ -1942,38 +2270,63 @@ var RealtimeClient = class {
|
|
|
1942
2270
|
get isConnected() {
|
|
1943
2271
|
return this.authenticated && this.ws?.readyState === 1;
|
|
1944
2272
|
}
|
|
2273
|
+
/** Where the connection lifecycle is right now. See `RealtimeState`. */
|
|
2274
|
+
get state() {
|
|
2275
|
+
return this._state;
|
|
2276
|
+
}
|
|
2277
|
+
/**
|
|
2278
|
+
* `true` when the current connection's `hello.ok` echoed the `ack`
|
|
2279
|
+
* capability: the server keeps each envelope `stored` until this client
|
|
2280
|
+
* acknowledges it. `false` before `hello.ok`, after a close, and against
|
|
2281
|
+
* a legacy server (which marks envelopes delivered on push).
|
|
2282
|
+
*/
|
|
2283
|
+
get ackNegotiated() {
|
|
2284
|
+
return this.ackMode;
|
|
2285
|
+
}
|
|
1945
2286
|
/**
|
|
1946
|
-
* Close the socket,
|
|
1947
|
-
*
|
|
1948
|
-
* `
|
|
2287
|
+
* Close the socket, cancel every timer, and release all handlers. The
|
|
2288
|
+
* only way into `stopped`, and the only way the client ever stops on
|
|
2289
|
+
* purpose: works from any state (`blocked` and a pending backoff
|
|
2290
|
+
* included). `stopped` fires once. After this, `connect()` throws —
|
|
2291
|
+
* create a fresh `RealtimeClient` if you want to reopen.
|
|
1949
2292
|
*/
|
|
1950
2293
|
disconnect() {
|
|
2294
|
+
if (this.disposed) return;
|
|
1951
2295
|
this.disposed = true;
|
|
1952
2296
|
this.options.reconnect = false;
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
this.reconnectTimer = null;
|
|
1956
|
-
}
|
|
1957
|
-
if (this.helloAckTimer) {
|
|
1958
|
-
clearTimeout(this.helloAckTimer);
|
|
1959
|
-
this.helloAckTimer = null;
|
|
1960
|
-
}
|
|
2297
|
+
this.clearReconnectTimer();
|
|
2298
|
+
this.clearWatchdogs();
|
|
1961
2299
|
this.cancelStabilityTimer();
|
|
1962
|
-
this.
|
|
2300
|
+
this.flushParkedFrames("gap_fill_unavailable");
|
|
2301
|
+
const ws = this.ws;
|
|
2302
|
+
this.ws = null;
|
|
1963
2303
|
try {
|
|
1964
|
-
|
|
2304
|
+
ws?.close(1e3, "client disconnect");
|
|
1965
2305
|
} catch {
|
|
1966
2306
|
}
|
|
1967
|
-
this.ws = null;
|
|
1968
2307
|
this.authenticated = false;
|
|
2308
|
+
this.ackMode = false;
|
|
2309
|
+
this.setState("stopped");
|
|
2310
|
+
for (const handler of this.stoppedHandlers) {
|
|
2311
|
+
try {
|
|
2312
|
+
handler();
|
|
2313
|
+
} catch {
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
1969
2316
|
this.handlers.clear();
|
|
1970
2317
|
this.errorHandlers.clear();
|
|
1971
2318
|
this.connectHandlers.clear();
|
|
1972
2319
|
this.disconnectHandlers.clear();
|
|
2320
|
+
this.stateHandlers.clear();
|
|
2321
|
+
this.blockedHandlers.clear();
|
|
2322
|
+
this.stoppedHandlers.clear();
|
|
1973
2323
|
}
|
|
1974
2324
|
emitError(error) {
|
|
1975
2325
|
for (const handler of this.errorHandlers) {
|
|
1976
|
-
|
|
2326
|
+
try {
|
|
2327
|
+
handler(error);
|
|
2328
|
+
} catch {
|
|
2329
|
+
}
|
|
1977
2330
|
}
|
|
1978
2331
|
}
|
|
1979
2332
|
dispatch(message) {
|
|
@@ -2014,10 +2367,11 @@ var RealtimeClient = class {
|
|
|
2014
2367
|
dispatchMessageNew(message) {
|
|
2015
2368
|
const isDrainRow = this.restDrainOrigin.has(message);
|
|
2016
2369
|
const messageId = this.extractMessageId(message);
|
|
2370
|
+
const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt;
|
|
2017
2371
|
let settlement;
|
|
2018
2372
|
if (messageId !== null && this.dedupHit(messageId)) {
|
|
2019
2373
|
settlement = Promise.resolve(true);
|
|
2020
|
-
if (
|
|
2374
|
+
if (ackAfterDispatch) this.sendAckFrame(messageId);
|
|
2021
2375
|
} else {
|
|
2022
2376
|
const handlers = this.handlers.get("message.new");
|
|
2023
2377
|
const pending = [];
|
|
@@ -2042,7 +2396,7 @@ var RealtimeClient = class {
|
|
|
2042
2396
|
if (!ok) return false;
|
|
2043
2397
|
if (messageId !== null) {
|
|
2044
2398
|
this.dedupAdd(messageId);
|
|
2045
|
-
if (
|
|
2399
|
+
if (ackAfterDispatch) this.sendAckFrame(messageId);
|
|
2046
2400
|
}
|
|
2047
2401
|
return true;
|
|
2048
2402
|
});
|
|
@@ -2090,12 +2444,45 @@ var RealtimeClient = class {
|
|
|
2090
2444
|
isMessageNew(message) {
|
|
2091
2445
|
return message.type === "message.new";
|
|
2092
2446
|
}
|
|
2447
|
+
isWake(message) {
|
|
2448
|
+
return message.type === "wake";
|
|
2449
|
+
}
|
|
2450
|
+
/**
|
|
2451
|
+
* A `wake` frame is a content-free signal: validate the payload shape
|
|
2452
|
+
* (so `wake` handlers can trust the `WakeFrame` type), then dispatch. A
|
|
2453
|
+
* frame the server sent malformed is surfaced through `onError` rather
|
|
2454
|
+
* than handed to handlers as something it is not. Never acked — there is
|
|
2455
|
+
* no message to deliver.
|
|
2456
|
+
*/
|
|
2457
|
+
dispatchWake(message) {
|
|
2458
|
+
const payload = message.payload;
|
|
2459
|
+
const reason = this.wakePayloadProblem(payload);
|
|
2460
|
+
if (reason !== null) {
|
|
2461
|
+
this.emitError(new ConnectionError(`wake frame failed validation: ${reason}`));
|
|
2462
|
+
return;
|
|
2463
|
+
}
|
|
2464
|
+
this.dispatch(message);
|
|
2465
|
+
}
|
|
2466
|
+
wakePayloadProblem(payload) {
|
|
2467
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
|
|
2468
|
+
return "payload is not an object";
|
|
2469
|
+
}
|
|
2470
|
+
const p = payload;
|
|
2471
|
+
for (const key of ["reason", "conversation_id", "anchor_message_id", "at"]) {
|
|
2472
|
+
if (typeof p[key] !== "string" || p[key] === "") return `${key} is not a non-empty string`;
|
|
2473
|
+
}
|
|
2474
|
+
if (typeof p.step !== "number" || !Number.isInteger(p.step)) return "step is not an integer";
|
|
2475
|
+
return null;
|
|
2476
|
+
}
|
|
2093
2477
|
// ─── Per-conversation seq ordering ───────────────────────────────────────
|
|
2094
2478
|
//
|
|
2095
2479
|
// Invariant: for any conversation_id, handlers see message.new envelopes
|
|
2096
|
-
//
|
|
2097
|
-
//
|
|
2098
|
-
//
|
|
2480
|
+
// in seq-ascending order with no skipped or repeated seqs — except that a
|
|
2481
|
+
// frame older than this connection's anchor (a stored row the drain brings
|
|
2482
|
+
// after a live frame anchored the conversation, or a seq a failed gap-fill
|
|
2483
|
+
// skipped) is dispatched late rather than dropped: never lost beats
|
|
2484
|
+
// strictly ordered, since the ack would otherwise bury it for good. The
|
|
2485
|
+
// dedup cache alone decides what is a repeat.
|
|
2099
2486
|
//
|
|
2100
2487
|
// Why per-conversation instead of global: seq numbers are minted per
|
|
2101
2488
|
// conversation by send_message_atomic, so cross-conversation arrivals
|
|
@@ -2119,6 +2506,7 @@ var RealtimeClient = class {
|
|
|
2119
2506
|
return;
|
|
2120
2507
|
}
|
|
2121
2508
|
if (seq < state.nextExpectedSeq) {
|
|
2509
|
+
this.dispatch(message);
|
|
2122
2510
|
return;
|
|
2123
2511
|
}
|
|
2124
2512
|
if (seq === state.nextExpectedSeq) {
|
|
@@ -2192,10 +2580,15 @@ var RealtimeClient = class {
|
|
|
2192
2580
|
const rowSeq = typeof row.seq === "number" ? row.seq : null;
|
|
2193
2581
|
if (rowSeq === null || rowSeq < expectedSeq) continue;
|
|
2194
2582
|
if (state.buffer.has(rowSeq)) continue;
|
|
2195
|
-
|
|
2583
|
+
const envelope = {
|
|
2196
2584
|
type: "message.new",
|
|
2197
2585
|
payload: row
|
|
2198
|
-
}
|
|
2586
|
+
};
|
|
2587
|
+
if (this.options.ackOnReceipt) {
|
|
2588
|
+
const messageId = this.extractMessageId(envelope);
|
|
2589
|
+
if (messageId !== null) this.sendAckFrame(messageId);
|
|
2590
|
+
}
|
|
2591
|
+
state.buffer.set(rowSeq, envelope);
|
|
2199
2592
|
}
|
|
2200
2593
|
const drainedThroughGap = this.drainConsecutive(conversationId, state);
|
|
2201
2594
|
if (drainedThroughGap) {
|
|
@@ -2310,7 +2703,11 @@ var RealtimeClient = class {
|
|
|
2310
2703
|
}
|
|
2311
2704
|
this.orderStates.clear();
|
|
2312
2705
|
}
|
|
2313
|
-
|
|
2706
|
+
// Hand every parked frame to the handlers in seq order per conversation,
|
|
2707
|
+
// cancel the gap timers and clear the ordering state. Used when frames
|
|
2708
|
+
// must not be dropped: on disconnect() (the caller is leaving) and, under
|
|
2709
|
+
// ackOnReceipt, on every socket close (the frames are already acked).
|
|
2710
|
+
flushParkedFrames(reason) {
|
|
2314
2711
|
for (const [conversationId, state] of this.orderStates) {
|
|
2315
2712
|
if (state.gapTimer !== null) {
|
|
2316
2713
|
clearTimeout(state.gapTimer);
|
|
@@ -2326,13 +2723,268 @@ var RealtimeClient = class {
|
|
|
2326
2723
|
bufferedSeq: seqs[0] ?? null,
|
|
2327
2724
|
gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,
|
|
2328
2725
|
recovered: false,
|
|
2329
|
-
reason
|
|
2726
|
+
reason
|
|
2330
2727
|
});
|
|
2331
2728
|
}
|
|
2332
2729
|
this.orderStates.clear();
|
|
2333
2730
|
}
|
|
2334
2731
|
};
|
|
2335
2732
|
|
|
2733
|
+
// src/gate.ts
|
|
2734
|
+
var gate_exports = {};
|
|
2735
|
+
__export(gate_exports, {
|
|
2736
|
+
BARE_TOOL_NAMER: () => BARE_TOOL_NAMER,
|
|
2737
|
+
anchorOf: () => anchorOf,
|
|
2738
|
+
buildPrompt: () => buildPrompt,
|
|
2739
|
+
canonicalJson: () => canonicalJson,
|
|
2740
|
+
cardsOf: () => cardsOf,
|
|
2741
|
+
mcpToolNamer: () => mcpToolNamer,
|
|
2742
|
+
normalizeDecision: () => normalizeDecision,
|
|
2743
|
+
parseVerdicts: () => parseVerdicts,
|
|
2744
|
+
run: () => run
|
|
2745
|
+
});
|
|
2746
|
+
var BARE_TOOL_NAMER = (tool) => tool;
|
|
2747
|
+
function mcpToolNamer(serverName) {
|
|
2748
|
+
return (tool) => `mcp__${serverName}__${tool}`;
|
|
2749
|
+
}
|
|
2750
|
+
var HOSTED_TOOL_TOKEN = /\bagentchat_[a-z0-9_]+\b/g;
|
|
2751
|
+
var DECIDE_TOOL = "agentchat_decide";
|
|
2752
|
+
var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "respond", "answer", "yes", "true"]);
|
|
2753
|
+
var DISMISS_TOKENS = /* @__PURE__ */ new Set([
|
|
2754
|
+
"dismiss",
|
|
2755
|
+
"dismissed",
|
|
2756
|
+
"no_reply",
|
|
2757
|
+
"no-reply",
|
|
2758
|
+
"noreply",
|
|
2759
|
+
"silent",
|
|
2760
|
+
"silence",
|
|
2761
|
+
"skip",
|
|
2762
|
+
"ignore",
|
|
2763
|
+
"no",
|
|
2764
|
+
"false"
|
|
2765
|
+
]);
|
|
2766
|
+
var DEFER_TOKENS = /* @__PURE__ */ new Set(["defer", "deferred", "later", "wait", "postpone"]);
|
|
2767
|
+
var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
|
|
2768
|
+
function cardsOf(tray) {
|
|
2769
|
+
const raw = tray.conversations;
|
|
2770
|
+
if (!Array.isArray(raw)) return [];
|
|
2771
|
+
return raw.filter(
|
|
2772
|
+
(card) => typeof card === "object" && card !== null && !Array.isArray(card) && typeof card.conversation_id === "string" && card.conversation_id.length > 0
|
|
2773
|
+
);
|
|
2774
|
+
}
|
|
2775
|
+
function categoriesOf(tray) {
|
|
2776
|
+
const raw = tray.categories;
|
|
2777
|
+
if (!Array.isArray(raw)) return [];
|
|
2778
|
+
return raw.filter((item) => typeof item === "string" && item.length > 0);
|
|
2779
|
+
}
|
|
2780
|
+
function anchorOf(card) {
|
|
2781
|
+
const preview = card.preview?.message_id;
|
|
2782
|
+
if (typeof preview === "string" && preview.length > 0) return preview;
|
|
2783
|
+
const last = card.last_message_id;
|
|
2784
|
+
if (typeof last === "string" && last.length > 0) return last;
|
|
2785
|
+
return void 0;
|
|
2786
|
+
}
|
|
2787
|
+
function canonicalJson(value) {
|
|
2788
|
+
return JSON.stringify(sortKeysDeep(value), null, 2);
|
|
2789
|
+
}
|
|
2790
|
+
function sortKeysDeep(value) {
|
|
2791
|
+
if (Array.isArray(value)) return value.map(sortKeysDeep);
|
|
2792
|
+
if (typeof value === "object" && value !== null) {
|
|
2793
|
+
const source = value;
|
|
2794
|
+
const out = {};
|
|
2795
|
+
for (const key of Object.keys(source).sort()) {
|
|
2796
|
+
if (source[key] !== void 0) out[key] = sortKeysDeep(source[key]);
|
|
2797
|
+
}
|
|
2798
|
+
return out;
|
|
2799
|
+
}
|
|
2800
|
+
return value;
|
|
2801
|
+
}
|
|
2802
|
+
function buildPrompt(tray, options) {
|
|
2803
|
+
const question = tray.question;
|
|
2804
|
+
if (typeof question !== "string" || question.trim().length === 0) {
|
|
2805
|
+
throw new Error("gate: tray carries no question");
|
|
2806
|
+
}
|
|
2807
|
+
const namer = options?.toolNamer ?? BARE_TOOL_NAMER;
|
|
2808
|
+
const cards = cardsOf(tray);
|
|
2809
|
+
const categories = categoriesOf(tray);
|
|
2810
|
+
const sections = [];
|
|
2811
|
+
sections.push(
|
|
2812
|
+
`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.`
|
|
2813
|
+
);
|
|
2814
|
+
sections.push(question.trim().replace(HOSTED_TOOL_TOKEN, (token) => namer(token)));
|
|
2815
|
+
if (categories.length > 0) {
|
|
2816
|
+
sections.push(`Categories: ${categories.join(", ")}`);
|
|
2817
|
+
}
|
|
2818
|
+
const you = typeof tray.you === "string" && tray.you.length > 0 ? `You are ${tray.you}. ` : "";
|
|
2819
|
+
const count = cards.length;
|
|
2820
|
+
sections.push(
|
|
2821
|
+
`${you}Your tray, as the server built it: ${count} conversation${count === 1 ? "" : "s"}.`
|
|
2822
|
+
);
|
|
2823
|
+
cards.forEach((card, index) => {
|
|
2824
|
+
sections.push(`Card ${index + 1} of ${count}
|
|
2825
|
+
${canonicalJson(card)}`);
|
|
2826
|
+
});
|
|
2827
|
+
let shape = '{"decisions": [{"conversation_id": "<conversation_id from a card>", "decision": "reply" | "dismiss" | "defer"';
|
|
2828
|
+
if (categories.length > 0) {
|
|
2829
|
+
shape += `, "category": "<one of: ${categories.join(", ")}>"`;
|
|
2830
|
+
}
|
|
2831
|
+
shape += "}]}";
|
|
2832
|
+
sections.push(
|
|
2833
|
+
"Answer with ONLY a JSON object, no prose and no code fences, in this shape: " + shape + " \u2014 one entry per card, every card decided."
|
|
2834
|
+
);
|
|
2835
|
+
return sections.join("\n\n");
|
|
2836
|
+
}
|
|
2837
|
+
function parseVerdicts(text, tray) {
|
|
2838
|
+
const raw = extractJson(text);
|
|
2839
|
+
if (raw === null) return null;
|
|
2840
|
+
let parsed;
|
|
2841
|
+
try {
|
|
2842
|
+
parsed = JSON.parse(raw);
|
|
2843
|
+
} catch {
|
|
2844
|
+
return null;
|
|
2845
|
+
}
|
|
2846
|
+
let items;
|
|
2847
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
2848
|
+
const record = parsed;
|
|
2849
|
+
items = record.decisions ?? record.verdicts;
|
|
2850
|
+
if (items === void 0 && "conversation_id" in record) items = [record];
|
|
2851
|
+
} else {
|
|
2852
|
+
items = parsed;
|
|
2853
|
+
}
|
|
2854
|
+
if (!Array.isArray(items)) return null;
|
|
2855
|
+
const known = new Set(cardsOf(tray).map((card) => card.conversation_id));
|
|
2856
|
+
const allowed = new Set(categoriesOf(tray).map((c) => c.toLowerCase()));
|
|
2857
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2858
|
+
const out = [];
|
|
2859
|
+
for (const item of items) {
|
|
2860
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) continue;
|
|
2861
|
+
const entry = item;
|
|
2862
|
+
const id = entry.conversation_id;
|
|
2863
|
+
if (typeof id !== "string" || !known.has(id) || seen.has(id)) continue;
|
|
2864
|
+
const decision = normalizeDecision(entry.decision);
|
|
2865
|
+
if (decision === null) continue;
|
|
2866
|
+
seen.add(id);
|
|
2867
|
+
out.push({
|
|
2868
|
+
conversation_id: id,
|
|
2869
|
+
decision,
|
|
2870
|
+
category: normalizeCategory(entry.category, allowed)
|
|
2871
|
+
});
|
|
2872
|
+
}
|
|
2873
|
+
return out;
|
|
2874
|
+
}
|
|
2875
|
+
function extractJson(text) {
|
|
2876
|
+
if (typeof text !== "string" || text.trim().length === 0) return null;
|
|
2877
|
+
let s = text.trim();
|
|
2878
|
+
const fence = FENCE_RE.exec(s);
|
|
2879
|
+
if (fence?.[1]) s = fence[1].trim();
|
|
2880
|
+
const starts = [s.indexOf("{"), s.indexOf("[")].filter((i) => i !== -1);
|
|
2881
|
+
if (starts.length === 0) return null;
|
|
2882
|
+
const start = Math.min(...starts);
|
|
2883
|
+
const closer = s[start] === "{" ? "}" : "]";
|
|
2884
|
+
const end = s.lastIndexOf(closer);
|
|
2885
|
+
if (end <= start) return null;
|
|
2886
|
+
return s.slice(start, end + 1);
|
|
2887
|
+
}
|
|
2888
|
+
function normalizeDecision(value) {
|
|
2889
|
+
if (typeof value !== "string") return null;
|
|
2890
|
+
const token = value.trim().toLowerCase().replace(/\s+/g, "_");
|
|
2891
|
+
if (REPLY_TOKENS.has(token)) return "reply";
|
|
2892
|
+
if (DISMISS_TOKENS.has(token)) return "dismiss";
|
|
2893
|
+
if (DEFER_TOKENS.has(token)) return "defer";
|
|
2894
|
+
return null;
|
|
2895
|
+
}
|
|
2896
|
+
function normalizeCategory(value, allowed) {
|
|
2897
|
+
if (allowed.size === 0 || typeof value !== "string") return null;
|
|
2898
|
+
const token = value.trim().toLowerCase();
|
|
2899
|
+
return allowed.has(token) ? token : null;
|
|
2900
|
+
}
|
|
2901
|
+
async function run(options) {
|
|
2902
|
+
const cards = cardsOf(options.tray);
|
|
2903
|
+
const ids = cards.map((card) => card.conversation_id);
|
|
2904
|
+
if (ids.length === 0) return emptyResult("empty", [], null);
|
|
2905
|
+
let text;
|
|
2906
|
+
try {
|
|
2907
|
+
const prompt = buildPrompt(options.tray, { toolNamer: options.toolNamer });
|
|
2908
|
+
text = await options.callModel(prompt);
|
|
2909
|
+
} catch (err) {
|
|
2910
|
+
return emptyResult("fail_closed", ids, `model call failed: ${describe(err)}`);
|
|
2911
|
+
}
|
|
2912
|
+
const verdicts = parseVerdicts(text, options.tray);
|
|
2913
|
+
if (verdicts === null || verdicts.length === 0) {
|
|
2914
|
+
return emptyResult("fail_closed", ids, "no usable verdicts in the answer");
|
|
2915
|
+
}
|
|
2916
|
+
const byId = new Map(cards.map((card) => [card.conversation_id, card]));
|
|
2917
|
+
const decided = new Set(verdicts.map((v) => v.conversation_id));
|
|
2918
|
+
const reply = [];
|
|
2919
|
+
const recordFailures = [];
|
|
2920
|
+
let recorded = 0;
|
|
2921
|
+
for (const verdict of verdicts) {
|
|
2922
|
+
const card = byId.get(verdict.conversation_id);
|
|
2923
|
+
if (!card) continue;
|
|
2924
|
+
if (verdict.decision === "reply") {
|
|
2925
|
+
reply.push(deferredReply(options.client, card, verdict.category));
|
|
2926
|
+
continue;
|
|
2927
|
+
}
|
|
2928
|
+
try {
|
|
2929
|
+
await options.client.decisions.record(verdict.conversation_id, {
|
|
2930
|
+
decision: verdict.decision,
|
|
2931
|
+
category: verdict.category ?? void 0,
|
|
2932
|
+
throughMessageId: anchorOf(card)
|
|
2933
|
+
});
|
|
2934
|
+
recorded += 1;
|
|
2935
|
+
} catch (err) {
|
|
2936
|
+
recordFailures.push({ conversation_id: verdict.conversation_id, error: toError2(err) });
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
return {
|
|
2940
|
+
outcome: "decided",
|
|
2941
|
+
reply,
|
|
2942
|
+
verdicts,
|
|
2943
|
+
undecided: ids.filter((id) => !decided.has(id)),
|
|
2944
|
+
recorded,
|
|
2945
|
+
recordFailures,
|
|
2946
|
+
failure: null
|
|
2947
|
+
};
|
|
2948
|
+
}
|
|
2949
|
+
function deferredReply(client, card, category) {
|
|
2950
|
+
let inFlight = null;
|
|
2951
|
+
return {
|
|
2952
|
+
conversationId: card.conversation_id,
|
|
2953
|
+
card,
|
|
2954
|
+
category,
|
|
2955
|
+
record: () => {
|
|
2956
|
+
if (inFlight === null) {
|
|
2957
|
+
inFlight = client.decisions.record(card.conversation_id, {
|
|
2958
|
+
decision: "reply",
|
|
2959
|
+
category: category ?? void 0,
|
|
2960
|
+
throughMessageId: anchorOf(card)
|
|
2961
|
+
}).catch((err) => {
|
|
2962
|
+
inFlight = null;
|
|
2963
|
+
throw err;
|
|
2964
|
+
});
|
|
2965
|
+
}
|
|
2966
|
+
return inFlight;
|
|
2967
|
+
}
|
|
2968
|
+
};
|
|
2969
|
+
}
|
|
2970
|
+
function emptyResult(outcome, undecided, failure) {
|
|
2971
|
+
return {
|
|
2972
|
+
outcome,
|
|
2973
|
+
reply: [],
|
|
2974
|
+
verdicts: [],
|
|
2975
|
+
undecided,
|
|
2976
|
+
recorded: 0,
|
|
2977
|
+
recordFailures: [],
|
|
2978
|
+
failure
|
|
2979
|
+
};
|
|
2980
|
+
}
|
|
2981
|
+
function toError2(err) {
|
|
2982
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
2983
|
+
}
|
|
2984
|
+
function describe(err) {
|
|
2985
|
+
return err instanceof Error ? err.message : String(err);
|
|
2986
|
+
}
|
|
2987
|
+
|
|
2336
2988
|
// src/render.ts
|
|
2337
2989
|
var SEC = 1e3;
|
|
2338
2990
|
var MIN = 60 * SEC;
|
|
@@ -2384,6 +3036,11 @@ function renderMessageContext(message, opts = {}) {
|
|
|
2384
3036
|
return lines.join("\n");
|
|
2385
3037
|
}
|
|
2386
3038
|
|
|
3039
|
+
// src/types/inbox-tray.ts
|
|
3040
|
+
var INBOX_TRAY_DEFAULT_LIMIT = 20;
|
|
3041
|
+
var INBOX_TRAY_MAX_LIMIT = 50;
|
|
3042
|
+
var INBOX_WAIT_MAX_MS = 5e4;
|
|
3043
|
+
|
|
2387
3044
|
// src/types/attachment.ts
|
|
2388
3045
|
var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
|
|
2389
3046
|
var ALLOWED_ATTACHMENT_MIME = [
|
|
@@ -2417,6 +3074,9 @@ exports.ForbiddenError = ForbiddenError;
|
|
|
2417
3074
|
exports.GroupDeletedError = GroupDeletedError;
|
|
2418
3075
|
exports.HandleRequiredError = HandleRequiredError;
|
|
2419
3076
|
exports.HttpTransport = HttpTransport;
|
|
3077
|
+
exports.INBOX_TRAY_DEFAULT_LIMIT = INBOX_TRAY_DEFAULT_LIMIT;
|
|
3078
|
+
exports.INBOX_TRAY_MAX_LIMIT = INBOX_TRAY_MAX_LIMIT;
|
|
3079
|
+
exports.INBOX_WAIT_MAX_MS = INBOX_WAIT_MAX_MS;
|
|
2420
3080
|
exports.MAX_ATTACHMENT_SIZE = MAX_ATTACHMENT_SIZE;
|
|
2421
3081
|
exports.NotFoundError = NotFoundError;
|
|
2422
3082
|
exports.RateLimitedError = RateLimitedError;
|
|
@@ -2429,6 +3089,8 @@ exports.UnauthorizedError = UnauthorizedError;
|
|
|
2429
3089
|
exports.VERSION = VERSION;
|
|
2430
3090
|
exports.ValidationError = ValidationError;
|
|
2431
3091
|
exports.createAgentChatError = createAgentChatError;
|
|
3092
|
+
exports.gate = gate_exports;
|
|
3093
|
+
exports.isAuthRejectionClose = isAuthRejectionClose;
|
|
2432
3094
|
exports.paginate = paginate;
|
|
2433
3095
|
exports.parseRetryAfter = parseRetryAfter;
|
|
2434
3096
|
exports.renderMessageContext = renderMessageContext;
|