agentchatme 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +184 -0
- package/README.md +154 -7
- package/dist/index.cjs +880 -129
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +861 -35
- package/dist/index.d.ts +861 -35
- package/dist/index.js +873 -130
- 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",
|
|
@@ -7,7 +13,30 @@ var ErrorCode = {
|
|
|
7
13
|
AGENT_PAUSED_BY_OWNER: "AGENT_PAUSED_BY_OWNER",
|
|
8
14
|
HANDLE_TAKEN: "HANDLE_TAKEN",
|
|
9
15
|
INVALID_HANDLE: "INVALID_HANDLE",
|
|
16
|
+
/**
|
|
17
|
+
* 409 from `POST /v1/register` (and `/register/verify`): the email already
|
|
18
|
+
* backs the maximum number of live agents. The cap is server-tunable and
|
|
19
|
+
* arrives in `details.limit`; deleting an agent frees a slot.
|
|
20
|
+
*/
|
|
21
|
+
EMAIL_LIMIT_REACHED: "EMAIL_LIMIT_REACHED",
|
|
22
|
+
/**
|
|
23
|
+
* 409 from `POST /v1/register` (and `/register/verify`): the email has
|
|
24
|
+
* spent its lifetime registration budget (deleted agents included).
|
|
25
|
+
* `details.limit` carries the cap; only a different email helps.
|
|
26
|
+
*/
|
|
10
27
|
EMAIL_EXHAUSTED: "EMAIL_EXHAUSTED",
|
|
28
|
+
/**
|
|
29
|
+
* Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce
|
|
30
|
+
* one live agent per email. Retired server-side; mapped to
|
|
31
|
+
* `EmailLimitReachedError` so callers never branch on it.
|
|
32
|
+
*/
|
|
33
|
+
EMAIL_TAKEN: "EMAIL_TAKEN",
|
|
34
|
+
/**
|
|
35
|
+
* 409 from `POST /v1/agents/recover/verify`: the email backs more than one
|
|
36
|
+
* agent and recovery was started without a `handle`. `details.handles`
|
|
37
|
+
* lists the candidates; re-run `recover()` with one of them.
|
|
38
|
+
*/
|
|
39
|
+
HANDLE_REQUIRED: "HANDLE_REQUIRED",
|
|
11
40
|
SUSPENDED: "SUSPENDED",
|
|
12
41
|
RESTRICTED: "RESTRICTED",
|
|
13
42
|
CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
|
|
@@ -148,6 +177,35 @@ var GroupDeletedError = class extends AgentChatError {
|
|
|
148
177
|
this.deletedAt = typeof d?.deleted_at === "string" ? d.deleted_at : null;
|
|
149
178
|
}
|
|
150
179
|
};
|
|
180
|
+
function policyLimit(details) {
|
|
181
|
+
const limit = details?.limit;
|
|
182
|
+
return typeof limit === "number" && Number.isInteger(limit) ? limit : null;
|
|
183
|
+
}
|
|
184
|
+
var EmailLimitReachedError = class extends AgentChatError {
|
|
185
|
+
limit;
|
|
186
|
+
constructor(response, status, requestId = null) {
|
|
187
|
+
super(response, status, requestId);
|
|
188
|
+
this.name = "EmailLimitReachedError";
|
|
189
|
+
this.limit = policyLimit(response.details);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
var EmailExhaustedError = class extends AgentChatError {
|
|
193
|
+
limit;
|
|
194
|
+
constructor(response, status, requestId = null) {
|
|
195
|
+
super(response, status, requestId);
|
|
196
|
+
this.name = "EmailExhaustedError";
|
|
197
|
+
this.limit = policyLimit(response.details);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
var HandleRequiredError = class extends AgentChatError {
|
|
201
|
+
handles;
|
|
202
|
+
constructor(response, status, requestId = null) {
|
|
203
|
+
super(response, status, requestId);
|
|
204
|
+
this.name = "HandleRequiredError";
|
|
205
|
+
const raw = response.details?.handles;
|
|
206
|
+
this.handles = Array.isArray(raw) ? raw.filter((h) => typeof h === "string") : [];
|
|
207
|
+
}
|
|
208
|
+
};
|
|
151
209
|
var ServerError = class extends AgentChatError {
|
|
152
210
|
constructor(response, status, requestId = null) {
|
|
153
211
|
super(response, status, requestId);
|
|
@@ -195,6 +253,13 @@ function createAgentChatError(body, status, headers) {
|
|
|
195
253
|
return new NotFoundError(body, status, requestId);
|
|
196
254
|
case ErrorCode.GROUP_DELETED:
|
|
197
255
|
return new GroupDeletedError(body, status, requestId);
|
|
256
|
+
case ErrorCode.EMAIL_LIMIT_REACHED:
|
|
257
|
+
case ErrorCode.EMAIL_TAKEN:
|
|
258
|
+
return new EmailLimitReachedError(body, status, requestId);
|
|
259
|
+
case ErrorCode.EMAIL_EXHAUSTED:
|
|
260
|
+
return new EmailExhaustedError(body, status, requestId);
|
|
261
|
+
case ErrorCode.HANDLE_REQUIRED:
|
|
262
|
+
return new HandleRequiredError(body, status, requestId);
|
|
198
263
|
case ErrorCode.INTERNAL_ERROR:
|
|
199
264
|
return new ServerError(body, status, requestId);
|
|
200
265
|
default:
|
|
@@ -211,7 +276,7 @@ function createAgentChatError(body, status, headers) {
|
|
|
211
276
|
}
|
|
212
277
|
|
|
213
278
|
// src/version.ts
|
|
214
|
-
var VERSION = "1.
|
|
279
|
+
var VERSION = "1.2.0" ;
|
|
215
280
|
|
|
216
281
|
// src/runtime.ts
|
|
217
282
|
function detectRuntime() {
|
|
@@ -588,10 +653,19 @@ function generateClientMsgId() {
|
|
|
588
653
|
}
|
|
589
654
|
return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
|
|
590
655
|
}
|
|
656
|
+
var INBOX_WAIT_TIMEOUT_GRACE_MS = 1e4;
|
|
591
657
|
var AgentChatClient = class _AgentChatClient {
|
|
592
658
|
http;
|
|
593
659
|
onBacklogWarning;
|
|
594
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;
|
|
595
669
|
constructor(options) {
|
|
596
670
|
this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
|
|
597
671
|
this.http = new HttpTransport({
|
|
@@ -604,6 +678,53 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
604
678
|
defaultHeaders: clientIdentityHeaders(options.clientIdentity)
|
|
605
679
|
});
|
|
606
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);
|
|
607
728
|
}
|
|
608
729
|
// ─── Internal request helpers ─────────────────────────────────────────────
|
|
609
730
|
async get(path, opts) {
|
|
@@ -650,6 +771,14 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
650
771
|
* Start registration. Creates a pending agent row and emails a 6-digit
|
|
651
772
|
* OTP to `email`. Complete the flow by calling `verify()` with the
|
|
652
773
|
* returned `pending_id` and the OTP code.
|
|
774
|
+
*
|
|
775
|
+
* One email can back several agents — each registers and verifies
|
|
776
|
+
* separately and gets its own handle and API key. The caps are
|
|
777
|
+
* server-enforced and tunable: throws `EmailLimitReachedError` when the
|
|
778
|
+
* email already backs the maximum number of live agents (delete one to
|
|
779
|
+
* free a slot) and `EmailExhaustedError` when its lifetime registration
|
|
780
|
+
* budget is spent (use another email; `+` aliases count as distinct).
|
|
781
|
+
* Both carry the cap in `limit`.
|
|
653
782
|
*/
|
|
654
783
|
static async register(options) {
|
|
655
784
|
const http = new HttpTransport({
|
|
@@ -691,10 +820,18 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
691
820
|
return { agent: res.data.agent, apiKey: res.data.api_key, client };
|
|
692
821
|
}
|
|
693
822
|
/**
|
|
694
|
-
* Start account recovery. The server emails
|
|
695
|
-
* `recoverVerify()` with the `pending_id` and
|
|
696
|
-
*
|
|
697
|
-
*
|
|
823
|
+
* Start account recovery for a lost API key. The server emails a 6-digit
|
|
824
|
+
* OTP to the address; call `recoverVerify()` with the `pending_id` and
|
|
825
|
+
* code to receive a new key.
|
|
826
|
+
*
|
|
827
|
+
* `options.handle` names the agent to recover. It is **required when the
|
|
828
|
+
* email backs more than one agent; always pass it.** Without it the
|
|
829
|
+
* server can resolve the target only while the email backs exactly one
|
|
830
|
+
* live agent, and `recoverVerify()` throws `HandleRequiredError`.
|
|
831
|
+
*
|
|
832
|
+
* Always resolves to `{ pending_id, message }` — a missing or mismatched
|
|
833
|
+
* account is masked to prevent email-existence enumeration, so a
|
|
834
|
+
* successful return is not proof the pair exists.
|
|
698
835
|
*/
|
|
699
836
|
static async recover(email, options) {
|
|
700
837
|
const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
|
|
@@ -702,13 +839,24 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
702
839
|
baseUrl,
|
|
703
840
|
defaultHeaders: clientIdentityHeaders(options?.clientIdentity)
|
|
704
841
|
});
|
|
705
|
-
const res = await http.request(
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
842
|
+
const res = await http.request("POST", "/v1/agents/recover", {
|
|
843
|
+
// `handle: undefined` is dropped by JSON serialization, so a legacy
|
|
844
|
+
// email-only call sends `{ email }` exactly as before — the server's
|
|
845
|
+
// schema marks `handle` optional, not nullable.
|
|
846
|
+
body: { email, handle: options?.handle },
|
|
847
|
+
retry: "never"
|
|
848
|
+
});
|
|
710
849
|
return res.data;
|
|
711
850
|
}
|
|
851
|
+
/**
|
|
852
|
+
* Complete recovery by verifying the OTP. Returns the handle, the new API
|
|
853
|
+
* key, and an `AgentChatClient` already bound to it. **The key is shown
|
|
854
|
+
* only once — store it securely.**
|
|
855
|
+
*
|
|
856
|
+
* Throws `HandleRequiredError` when `recover()` ran without `handle` for
|
|
857
|
+
* an email that backs several agents; its `handles` lists them. The OTP
|
|
858
|
+
* is consumed either way — start over with `handle` set.
|
|
859
|
+
*/
|
|
712
860
|
static async recoverVerify(pendingId, code, options) {
|
|
713
861
|
const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
|
|
714
862
|
const http = new HttpTransport({
|
|
@@ -1342,33 +1490,60 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
1342
1490
|
};
|
|
1343
1491
|
|
|
1344
1492
|
// src/ws-resolver.ts
|
|
1345
|
-
|
|
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
|
+
}
|
|
1346
1505
|
async function resolveWebSocket() {
|
|
1347
|
-
if (cached) return cached;
|
|
1348
1506
|
const native = globalThis.WebSocket;
|
|
1349
|
-
if (native)
|
|
1350
|
-
|
|
1351
|
-
return native;
|
|
1352
|
-
}
|
|
1507
|
+
if (!isNode() && native) return native;
|
|
1508
|
+
let wsFailure;
|
|
1353
1509
|
try {
|
|
1354
|
-
|
|
1355
|
-
const ctor = mod.default ?? mod.WebSocket;
|
|
1356
|
-
if (!ctor) {
|
|
1357
|
-
throw new Error("The `ws` package loaded but did not export a WebSocket constructor.");
|
|
1358
|
-
}
|
|
1359
|
-
cached = ctor;
|
|
1360
|
-
return ctor;
|
|
1510
|
+
return await importWs();
|
|
1361
1511
|
} catch (err) {
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
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
|
+
);
|
|
1368
1520
|
}
|
|
1369
1521
|
|
|
1370
1522
|
// src/realtime.ts
|
|
1371
|
-
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
|
+
}
|
|
1372
1547
|
var STABLE_CONNECTION_MS = 3e4;
|
|
1373
1548
|
var RAPID_RECONNECT_MS = 6e4;
|
|
1374
1549
|
var INSTABILITY_WARN_THRESHOLD = 5;
|
|
@@ -1377,7 +1552,6 @@ var MAX_BUFFERED_PER_CONVERSATION = 500;
|
|
|
1377
1552
|
var GAP_FILL_LIMIT = 200;
|
|
1378
1553
|
var SYNC_DRAIN_PAGE_SIZE = 200;
|
|
1379
1554
|
var DEFAULT_DEDUP_CACHE_SIZE = 2048;
|
|
1380
|
-
var TERMINAL_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401, 4403]);
|
|
1381
1555
|
function isValidSyncRow(row) {
|
|
1382
1556
|
if (typeof row !== "object" || row === null || Array.isArray(row)) return false;
|
|
1383
1557
|
const r = row;
|
|
@@ -1412,6 +1586,11 @@ var RealtimeClient = class {
|
|
|
1412
1586
|
errorHandlers = /* @__PURE__ */ new Set();
|
|
1413
1587
|
connectHandlers = /* @__PURE__ */ new Set();
|
|
1414
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. */
|
|
1415
1594
|
reconnectAttempts = 0;
|
|
1416
1595
|
/** Clears reconnectAttempts once this connection proves itself stable. */
|
|
1417
1596
|
stabilityTimer = null;
|
|
@@ -1419,16 +1598,23 @@ var RealtimeClient = class {
|
|
|
1419
1598
|
* the operator warning only; backoff itself uses reconnectAttempts. */
|
|
1420
1599
|
rapidReconnects = 0;
|
|
1421
1600
|
lastConnectAt = null;
|
|
1601
|
+
/** The pending backoff or blocked-retry timer — at most one at a time. */
|
|
1422
1602
|
reconnectTimer = null;
|
|
1423
|
-
|
|
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;
|
|
1424
1610
|
authenticated = false;
|
|
1425
1611
|
// True only when the server echoed the 'ack' capability in hello.ok.
|
|
1426
1612
|
// Per-connection: reset on every close and re-negotiated on every HELLO.
|
|
1427
1613
|
ackMode = false;
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
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;
|
|
1432
1618
|
// Bounded LRU of recently-dispatched message ids (Set iteration order is
|
|
1433
1619
|
// insertion order — delete + re-add refreshes recency). Ids are added
|
|
1434
1620
|
// only AFTER a successful dispatch: adding earlier would let a failed
|
|
@@ -1453,51 +1639,73 @@ var RealtimeClient = class {
|
|
|
1453
1639
|
disposed = false;
|
|
1454
1640
|
constructor(options) {
|
|
1455
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;
|
|
1456
1644
|
this.options = {
|
|
1457
1645
|
baseUrl: options.baseUrl ?? "wss://api.agentchat.me",
|
|
1458
1646
|
reconnect: options.reconnect ?? true,
|
|
1459
1647
|
reconnectInterval: options.reconnectInterval ?? 500,
|
|
1460
1648
|
maxReconnectInterval: options.maxReconnectInterval ?? 3e4,
|
|
1461
|
-
|
|
1649
|
+
handshakeTimeoutMs,
|
|
1650
|
+
livenessTimeoutMs,
|
|
1462
1651
|
apiKey: options.apiKey,
|
|
1463
1652
|
client: options.client,
|
|
1464
1653
|
onSequenceGap: options.onSequenceGap,
|
|
1465
1654
|
autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),
|
|
1466
1655
|
dedupCacheSize,
|
|
1656
|
+
ackOnReceipt: options.ackOnReceipt ?? false,
|
|
1467
1657
|
webSocket: options.webSocket,
|
|
1468
1658
|
clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY
|
|
1469
1659
|
};
|
|
1470
1660
|
}
|
|
1471
1661
|
/**
|
|
1472
1662
|
* Open the WebSocket connection and perform the HELLO handshake.
|
|
1473
|
-
* Resolves once the socket
|
|
1474
|
-
* NOT after `hello.ok`. Listen for `onConnect()`
|
|
1475
|
-
* 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.
|
|
1476
1666
|
*
|
|
1477
|
-
*
|
|
1478
|
-
*
|
|
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`.
|
|
1479
1673
|
*/
|
|
1480
1674
|
async connect() {
|
|
1481
1675
|
if (this.disposed) {
|
|
1482
1676
|
throw new ConnectionError("RealtimeClient has been disposed; create a new instance to reconnect.");
|
|
1483
1677
|
}
|
|
1678
|
+
if (this.ws) return;
|
|
1679
|
+
this.clearReconnectTimer();
|
|
1484
1680
|
let WebSocketCtor;
|
|
1485
1681
|
try {
|
|
1486
1682
|
WebSocketCtor = this.options.webSocket ?? await resolveWebSocket();
|
|
1487
1683
|
} catch (err) {
|
|
1488
|
-
|
|
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");
|
|
1489
1695
|
this.emitError(error);
|
|
1490
1696
|
this.scheduleReconnect();
|
|
1491
1697
|
throw error;
|
|
1492
1698
|
}
|
|
1493
|
-
|
|
1494
|
-
this.ws = new WebSocketCtor(url);
|
|
1699
|
+
this.ws = ws;
|
|
1495
1700
|
this.authenticated = false;
|
|
1496
1701
|
this.ackMode = false;
|
|
1497
|
-
this.
|
|
1498
|
-
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;
|
|
1499
1707
|
try {
|
|
1500
|
-
|
|
1708
|
+
ws.send(
|
|
1501
1709
|
JSON.stringify({
|
|
1502
1710
|
type: "hello",
|
|
1503
1711
|
api_key: this.options.apiKey,
|
|
@@ -1508,18 +1716,12 @@ var RealtimeClient = class {
|
|
|
1508
1716
|
);
|
|
1509
1717
|
} catch (err) {
|
|
1510
1718
|
this.emitError(err instanceof Error ? err : new ConnectionError("HELLO send failed"));
|
|
1511
|
-
|
|
1719
|
+
this.abandonSocket(CLIENT_CLOSE_CODE, "client HELLO send failed");
|
|
1512
1720
|
}
|
|
1513
|
-
this.helloAckTimer = setTimeout(() => {
|
|
1514
|
-
this.emitError(new ConnectionError("HELLO ack timeout"));
|
|
1515
|
-
this.helloTimeoutClose = true;
|
|
1516
|
-
try {
|
|
1517
|
-
this.ws?.close(1008, "HELLO ack timeout");
|
|
1518
|
-
} catch {
|
|
1519
|
-
}
|
|
1520
|
-
}, HELLO_ACK_TIMEOUT_MS);
|
|
1521
1721
|
};
|
|
1522
|
-
|
|
1722
|
+
ws.onmessage = (event) => {
|
|
1723
|
+
if (!current()) return;
|
|
1724
|
+
this.touchLiveness();
|
|
1523
1725
|
let message;
|
|
1524
1726
|
try {
|
|
1525
1727
|
message = JSON.parse(String(event.data));
|
|
@@ -1531,11 +1733,11 @@ var RealtimeClient = class {
|
|
|
1531
1733
|
this.authenticated = true;
|
|
1532
1734
|
const caps = message.capabilities;
|
|
1533
1735
|
this.ackMode = Array.isArray(caps) && caps.includes("ack");
|
|
1736
|
+
this.clearHandshakeTimer();
|
|
1737
|
+
this.touchLiveness();
|
|
1534
1738
|
this.startStabilityTimer();
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
this.helloAckTimer = null;
|
|
1538
|
-
}
|
|
1739
|
+
this.blockedAnnounced = false;
|
|
1740
|
+
this.setState("ready");
|
|
1539
1741
|
for (const handler of this.connectHandlers) {
|
|
1540
1742
|
try {
|
|
1541
1743
|
handler();
|
|
@@ -1553,42 +1755,42 @@ var RealtimeClient = class {
|
|
|
1553
1755
|
return;
|
|
1554
1756
|
}
|
|
1555
1757
|
if (this.isMessageNew(message)) {
|
|
1758
|
+
if (this.options.ackOnReceipt) {
|
|
1759
|
+
const messageId = this.extractMessageId(message);
|
|
1760
|
+
if (messageId !== null) this.sendAckFrame(messageId);
|
|
1761
|
+
}
|
|
1556
1762
|
this.processOrderedMessage(message);
|
|
1557
1763
|
return;
|
|
1558
1764
|
}
|
|
1765
|
+
if (this.isWake(message)) {
|
|
1766
|
+
this.dispatchWake(message);
|
|
1767
|
+
return;
|
|
1768
|
+
}
|
|
1559
1769
|
this.dispatch(message);
|
|
1560
1770
|
};
|
|
1561
|
-
|
|
1771
|
+
ws.onerror = () => {
|
|
1772
|
+
if (!current()) return;
|
|
1562
1773
|
this.emitError(new ConnectionError("WebSocket error"));
|
|
1563
1774
|
};
|
|
1564
|
-
|
|
1565
|
-
if (
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
for (const handler of this.disconnectHandlers) {
|
|
1576
|
-
try {
|
|
1577
|
-
handler({ code: event.code, reason: event.reason, wasClean: event.wasClean });
|
|
1578
|
-
} catch {
|
|
1579
|
-
}
|
|
1580
|
-
}
|
|
1581
|
-
this.resetOrderStates();
|
|
1582
|
-
if (TERMINAL_CLOSE_CODES.has(event.code) && !selfClosedForHelloTimeout) {
|
|
1583
|
-
this.emitError(
|
|
1584
|
-
new ConnectionError(
|
|
1585
|
-
`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.`
|
|
1586
|
-
)
|
|
1587
|
-
);
|
|
1588
|
-
return;
|
|
1589
|
-
}
|
|
1590
|
-
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
|
+
});
|
|
1591
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
|
+
}
|
|
1592
1794
|
}
|
|
1593
1795
|
/**
|
|
1594
1796
|
* Drain offline envelopes accumulated while the socket was disconnected.
|
|
@@ -1745,8 +1947,9 @@ var RealtimeClient = class {
|
|
|
1745
1947
|
if (this.disposed || !this.authenticated) return;
|
|
1746
1948
|
this.reconnectAttempts = 0;
|
|
1747
1949
|
this.rapidReconnects = 0;
|
|
1950
|
+
this.longOutageAnnounced = false;
|
|
1748
1951
|
}, STABLE_CONNECTION_MS);
|
|
1749
|
-
this.stabilityTimer
|
|
1952
|
+
unref(this.stabilityTimer);
|
|
1750
1953
|
}
|
|
1751
1954
|
cancelStabilityTimer() {
|
|
1752
1955
|
if (this.stabilityTimer) {
|
|
@@ -1758,6 +1961,8 @@ var RealtimeClient = class {
|
|
|
1758
1961
|
* Track short-lived connections and warn once they form a pattern.
|
|
1759
1962
|
* A flapping client looks healthy from the inside — every reconnect
|
|
1760
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.
|
|
1761
1966
|
*/
|
|
1762
1967
|
noteConnectionEnded() {
|
|
1763
1968
|
const started = this.lastConnectAt;
|
|
@@ -1769,43 +1974,252 @@ var RealtimeClient = class {
|
|
|
1769
1974
|
}
|
|
1770
1975
|
this.rapidReconnects++;
|
|
1771
1976
|
if (this.rapidReconnects === INSTABILITY_WARN_THRESHOLD) {
|
|
1772
|
-
|
|
1773
|
-
|
|
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
|
+
)
|
|
1774
1981
|
);
|
|
1775
1982
|
}
|
|
1776
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
|
+
}
|
|
1777
2036
|
scheduleReconnect() {
|
|
1778
2037
|
if (this.disposed) return;
|
|
1779
|
-
if (!this.options.reconnect) return;
|
|
1780
|
-
if (this.reconnectAttempts >= this.options.maxReconnectAttempts) return;
|
|
1781
2038
|
if (this.reconnectTimer) return;
|
|
2039
|
+
if (!this.options.reconnect) {
|
|
2040
|
+
this.setState("idle");
|
|
2041
|
+
return;
|
|
2042
|
+
}
|
|
1782
2043
|
this.reconnectAttempts++;
|
|
1783
|
-
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");
|
|
1784
2055
|
this.reconnectTimer = setTimeout(() => {
|
|
1785
2056
|
this.reconnectTimer = null;
|
|
1786
|
-
|
|
1787
|
-
this.emitError(err instanceof Error ? err : new ConnectionError(String(err)));
|
|
1788
|
-
});
|
|
2057
|
+
this.retryNow();
|
|
1789
2058
|
}, delay);
|
|
1790
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
|
+
}
|
|
1791
2111
|
computeReconnectDelay(attempt) {
|
|
1792
|
-
const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1,
|
|
1793
|
-
const
|
|
1794
|
-
|
|
1795
|
-
|
|
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
|
+
}
|
|
1796
2188
|
}
|
|
1797
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
|
+
}
|
|
1798
2198
|
let handlers = this.handlers.get(event);
|
|
1799
2199
|
if (!handlers) {
|
|
1800
2200
|
handlers = /* @__PURE__ */ new Set();
|
|
1801
2201
|
this.handlers.set(event, handlers);
|
|
1802
2202
|
}
|
|
1803
|
-
|
|
2203
|
+
const stored = handler;
|
|
2204
|
+
handlers.add(stored);
|
|
1804
2205
|
return () => {
|
|
1805
|
-
handlers.delete(
|
|
2206
|
+
handlers.delete(stored);
|
|
1806
2207
|
if (handlers.size === 0) this.handlers.delete(event);
|
|
1807
2208
|
};
|
|
1808
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
|
+
*/
|
|
1809
2223
|
onError(handler) {
|
|
1810
2224
|
this.errorHandlers.add(handler);
|
|
1811
2225
|
return () => this.errorHandlers.delete(handler);
|
|
@@ -1856,38 +2270,63 @@ var RealtimeClient = class {
|
|
|
1856
2270
|
get isConnected() {
|
|
1857
2271
|
return this.authenticated && this.ws?.readyState === 1;
|
|
1858
2272
|
}
|
|
2273
|
+
/** Where the connection lifecycle is right now. See `RealtimeState`. */
|
|
2274
|
+
get state() {
|
|
2275
|
+
return this._state;
|
|
2276
|
+
}
|
|
1859
2277
|
/**
|
|
1860
|
-
*
|
|
1861
|
-
*
|
|
1862
|
-
* `
|
|
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
|
+
}
|
|
2286
|
+
/**
|
|
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.
|
|
1863
2292
|
*/
|
|
1864
2293
|
disconnect() {
|
|
2294
|
+
if (this.disposed) return;
|
|
1865
2295
|
this.disposed = true;
|
|
1866
2296
|
this.options.reconnect = false;
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
this.reconnectTimer = null;
|
|
1870
|
-
}
|
|
1871
|
-
if (this.helloAckTimer) {
|
|
1872
|
-
clearTimeout(this.helloAckTimer);
|
|
1873
|
-
this.helloAckTimer = null;
|
|
1874
|
-
}
|
|
2297
|
+
this.clearReconnectTimer();
|
|
2298
|
+
this.clearWatchdogs();
|
|
1875
2299
|
this.cancelStabilityTimer();
|
|
1876
|
-
this.
|
|
2300
|
+
this.flushParkedFrames("gap_fill_unavailable");
|
|
2301
|
+
const ws = this.ws;
|
|
2302
|
+
this.ws = null;
|
|
1877
2303
|
try {
|
|
1878
|
-
|
|
2304
|
+
ws?.close(1e3, "client disconnect");
|
|
1879
2305
|
} catch {
|
|
1880
2306
|
}
|
|
1881
|
-
this.ws = null;
|
|
1882
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
|
+
}
|
|
1883
2316
|
this.handlers.clear();
|
|
1884
2317
|
this.errorHandlers.clear();
|
|
1885
2318
|
this.connectHandlers.clear();
|
|
1886
2319
|
this.disconnectHandlers.clear();
|
|
2320
|
+
this.stateHandlers.clear();
|
|
2321
|
+
this.blockedHandlers.clear();
|
|
2322
|
+
this.stoppedHandlers.clear();
|
|
1887
2323
|
}
|
|
1888
2324
|
emitError(error) {
|
|
1889
2325
|
for (const handler of this.errorHandlers) {
|
|
1890
|
-
|
|
2326
|
+
try {
|
|
2327
|
+
handler(error);
|
|
2328
|
+
} catch {
|
|
2329
|
+
}
|
|
1891
2330
|
}
|
|
1892
2331
|
}
|
|
1893
2332
|
dispatch(message) {
|
|
@@ -1928,10 +2367,11 @@ var RealtimeClient = class {
|
|
|
1928
2367
|
dispatchMessageNew(message) {
|
|
1929
2368
|
const isDrainRow = this.restDrainOrigin.has(message);
|
|
1930
2369
|
const messageId = this.extractMessageId(message);
|
|
2370
|
+
const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt;
|
|
1931
2371
|
let settlement;
|
|
1932
2372
|
if (messageId !== null && this.dedupHit(messageId)) {
|
|
1933
2373
|
settlement = Promise.resolve(true);
|
|
1934
|
-
if (
|
|
2374
|
+
if (ackAfterDispatch) this.sendAckFrame(messageId);
|
|
1935
2375
|
} else {
|
|
1936
2376
|
const handlers = this.handlers.get("message.new");
|
|
1937
2377
|
const pending = [];
|
|
@@ -1956,7 +2396,7 @@ var RealtimeClient = class {
|
|
|
1956
2396
|
if (!ok) return false;
|
|
1957
2397
|
if (messageId !== null) {
|
|
1958
2398
|
this.dedupAdd(messageId);
|
|
1959
|
-
if (
|
|
2399
|
+
if (ackAfterDispatch) this.sendAckFrame(messageId);
|
|
1960
2400
|
}
|
|
1961
2401
|
return true;
|
|
1962
2402
|
});
|
|
@@ -2004,12 +2444,45 @@ var RealtimeClient = class {
|
|
|
2004
2444
|
isMessageNew(message) {
|
|
2005
2445
|
return message.type === "message.new";
|
|
2006
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
|
+
}
|
|
2007
2477
|
// ─── Per-conversation seq ordering ───────────────────────────────────────
|
|
2008
2478
|
//
|
|
2009
2479
|
// Invariant: for any conversation_id, handlers see message.new envelopes
|
|
2010
|
-
//
|
|
2011
|
-
//
|
|
2012
|
-
//
|
|
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.
|
|
2013
2486
|
//
|
|
2014
2487
|
// Why per-conversation instead of global: seq numbers are minted per
|
|
2015
2488
|
// conversation by send_message_atomic, so cross-conversation arrivals
|
|
@@ -2033,6 +2506,7 @@ var RealtimeClient = class {
|
|
|
2033
2506
|
return;
|
|
2034
2507
|
}
|
|
2035
2508
|
if (seq < state.nextExpectedSeq) {
|
|
2509
|
+
this.dispatch(message);
|
|
2036
2510
|
return;
|
|
2037
2511
|
}
|
|
2038
2512
|
if (seq === state.nextExpectedSeq) {
|
|
@@ -2106,10 +2580,15 @@ var RealtimeClient = class {
|
|
|
2106
2580
|
const rowSeq = typeof row.seq === "number" ? row.seq : null;
|
|
2107
2581
|
if (rowSeq === null || rowSeq < expectedSeq) continue;
|
|
2108
2582
|
if (state.buffer.has(rowSeq)) continue;
|
|
2109
|
-
|
|
2583
|
+
const envelope = {
|
|
2110
2584
|
type: "message.new",
|
|
2111
2585
|
payload: row
|
|
2112
|
-
}
|
|
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);
|
|
2113
2592
|
}
|
|
2114
2593
|
const drainedThroughGap = this.drainConsecutive(conversationId, state);
|
|
2115
2594
|
if (drainedThroughGap) {
|
|
@@ -2224,7 +2703,11 @@ var RealtimeClient = class {
|
|
|
2224
2703
|
}
|
|
2225
2704
|
this.orderStates.clear();
|
|
2226
2705
|
}
|
|
2227
|
-
|
|
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) {
|
|
2228
2711
|
for (const [conversationId, state] of this.orderStates) {
|
|
2229
2712
|
if (state.gapTimer !== null) {
|
|
2230
2713
|
clearTimeout(state.gapTimer);
|
|
@@ -2240,13 +2723,268 @@ var RealtimeClient = class {
|
|
|
2240
2723
|
bufferedSeq: seqs[0] ?? null,
|
|
2241
2724
|
gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,
|
|
2242
2725
|
recovered: false,
|
|
2243
|
-
reason
|
|
2726
|
+
reason
|
|
2244
2727
|
});
|
|
2245
2728
|
}
|
|
2246
2729
|
this.orderStates.clear();
|
|
2247
2730
|
}
|
|
2248
2731
|
};
|
|
2249
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
|
+
|
|
2250
2988
|
// src/render.ts
|
|
2251
2989
|
var SEC = 1e3;
|
|
2252
2990
|
var MIN = 60 * SEC;
|
|
@@ -2298,6 +3036,11 @@ function renderMessageContext(message, opts = {}) {
|
|
|
2298
3036
|
return lines.join("\n");
|
|
2299
3037
|
}
|
|
2300
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
|
+
|
|
2301
3044
|
// src/types/attachment.ts
|
|
2302
3045
|
var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
|
|
2303
3046
|
var ALLOWED_ATTACHMENT_MIME = [
|
|
@@ -2324,10 +3067,16 @@ exports.AwaitingReplyError = AwaitingReplyError;
|
|
|
2324
3067
|
exports.BlockedError = BlockedError;
|
|
2325
3068
|
exports.ConnectionError = ConnectionError;
|
|
2326
3069
|
exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY;
|
|
3070
|
+
exports.EmailExhaustedError = EmailExhaustedError;
|
|
3071
|
+
exports.EmailLimitReachedError = EmailLimitReachedError;
|
|
2327
3072
|
exports.ErrorCode = ErrorCode;
|
|
2328
3073
|
exports.ForbiddenError = ForbiddenError;
|
|
2329
3074
|
exports.GroupDeletedError = GroupDeletedError;
|
|
3075
|
+
exports.HandleRequiredError = HandleRequiredError;
|
|
2330
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;
|
|
2331
3080
|
exports.MAX_ATTACHMENT_SIZE = MAX_ATTACHMENT_SIZE;
|
|
2332
3081
|
exports.NotFoundError = NotFoundError;
|
|
2333
3082
|
exports.RateLimitedError = RateLimitedError;
|
|
@@ -2340,6 +3089,8 @@ exports.UnauthorizedError = UnauthorizedError;
|
|
|
2340
3089
|
exports.VERSION = VERSION;
|
|
2341
3090
|
exports.ValidationError = ValidationError;
|
|
2342
3091
|
exports.createAgentChatError = createAgentChatError;
|
|
3092
|
+
exports.gate = gate_exports;
|
|
3093
|
+
exports.isAuthRejectionClose = isAuthRejectionClose;
|
|
2343
3094
|
exports.paginate = paginate;
|
|
2344
3095
|
exports.parseRetryAfter = parseRetryAfter;
|
|
2345
3096
|
exports.renderMessageContext = renderMessageContext;
|