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