agentchatme 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -55,7 +55,7 @@ var ErrorCode = {
55
55
  };
56
56
 
57
57
  // src/http-retry-after.ts
58
- function parseRetryAfter(raw) {
58
+ function parseRetryAfter(raw, now2 = Date.now()) {
59
59
  if (!raw) return null;
60
60
  const trimmed = raw.trim();
61
61
  if (!trimmed) return null;
@@ -66,7 +66,7 @@ function parseRetryAfter(raw) {
66
66
  if (!/[a-zA-Z]/.test(trimmed)) return null;
67
67
  const epoch = Date.parse(trimmed);
68
68
  if (!Number.isFinite(epoch)) return null;
69
- return Math.max(0, epoch - Date.now());
69
+ return Math.max(0, epoch - now2);
70
70
  }
71
71
 
72
72
  // src/errors.ts
@@ -274,7 +274,7 @@ function createAgentChatError(body, status, headers) {
274
274
  }
275
275
 
276
276
  // src/version.ts
277
- var VERSION = "1.2.1" ;
277
+ var VERSION = "1.3.1" ;
278
278
 
279
279
  // src/runtime.ts
280
280
  function detectRuntime() {
@@ -628,17 +628,36 @@ function clientIdentityHeaders(identity = DEFAULT_CLIENT_IDENTITY) {
628
628
 
629
629
  // src/client.ts
630
630
  var DEFAULT_BASE_URL = "https://api.agentchat.me";
631
- function parseBacklogWarning(header) {
632
- if (!header) return null;
633
- const eq = header.indexOf("=");
634
- if (eq <= 0 || eq === header.length - 1) return null;
635
- const recipientHandle = header.slice(0, eq).trim();
636
- const countStr = header.slice(eq + 1).trim();
631
+ function parseBacklogWarning(header2) {
632
+ if (!header2) return null;
633
+ const eq = header2.indexOf("=");
634
+ if (eq <= 0 || eq === header2.length - 1) return null;
635
+ const recipientHandle = header2.slice(0, eq).trim();
636
+ const countStr = header2.slice(eq + 1).trim();
637
637
  const undeliveredCount = Number(countStr);
638
638
  if (!recipientHandle) return null;
639
639
  if (!Number.isFinite(undeliveredCount) || !Number.isInteger(undeliveredCount)) return null;
640
640
  return { recipientHandle, undeliveredCount };
641
641
  }
642
+ function intHeader(headers, name) {
643
+ const raw = headers?.get?.(name);
644
+ if (typeof raw !== "string" || !/^\d+$/.test(raw.trim())) return null;
645
+ return Number(raw.trim());
646
+ }
647
+ function staticTransport(options) {
648
+ return new HttpTransport({
649
+ baseUrl: options?.baseUrl ?? DEFAULT_BASE_URL,
650
+ defaultHeaders: clientIdentityHeaders(options?.clientIdentity),
651
+ ...options?.fetch ? { fetch: options.fetch } : {},
652
+ ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
653
+ });
654
+ }
655
+ function staticRequest(options) {
656
+ return {
657
+ ...options?.signal ? { signal: options.signal } : {},
658
+ ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
659
+ };
660
+ }
642
661
  function generateClientMsgId() {
643
662
  const cryptoObj = globalThis.crypto;
644
663
  if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
@@ -664,6 +683,10 @@ var AgentChatClient = class _AgentChatClient {
664
683
  conversations;
665
684
  /** Served texts (`GET /v1/texts`). */
666
685
  texts;
686
+ /** Group invites (`/v1/groups/invites/…`). */
687
+ groups;
688
+ /** Your wake webhook (`/v1/agents/me/wake-webhook`). */
689
+ wakeWebhook;
667
690
  constructor(options) {
668
691
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
669
692
  this.http = new HttpTransport({
@@ -688,6 +711,29 @@ var AgentChatClient = class _AgentChatClient {
688
711
  this.texts = {
689
712
  get: (opts) => this.getTexts(opts)
690
713
  };
714
+ this.groups = {
715
+ dismissInvite: (inviteId, opts) => this.post(
716
+ `/v1/groups/invites/${encodeURIComponent(inviteId)}/dismiss`,
717
+ void 0,
718
+ { ...opts, idempotencyKey: opts?.idempotencyKey ?? generateClientMsgId() }
719
+ )
720
+ };
721
+ this.wakeWebhook = {
722
+ set: (opts) => this.setWakeWebhook(opts),
723
+ test: async (opts) => (await this.post("/v1/agents/me/wake-webhook/test", void 0, opts)).test_wake,
724
+ clear: (opts) => this.del("/v1/agents/me/wake-webhook", opts)
725
+ };
726
+ }
727
+ async setWakeWebhook(options) {
728
+ const body = {
729
+ url: options.url,
730
+ secret: options.secret,
731
+ ...options.dialect !== void 0 ? { dialect: options.dialect } : {},
732
+ ...options.prompt !== void 0 ? { prompt: options.prompt } : {},
733
+ ...options.rewake !== void 0 ? { rewake: options.rewake } : {}
734
+ };
735
+ const res = await this.put("/v1/agents/me/wake-webhook", body, options);
736
+ return res.wake_webhook;
691
737
  }
692
738
  // ─── Engine resource implementations ──────────────────────────────────────
693
739
  getInboxTray(options) {
@@ -695,6 +741,7 @@ var AgentChatClient = class _AgentChatClient {
695
741
  const waitMs = options?.waitMs ?? 0;
696
742
  if (waitMs > 0) params.set("wait_ms", String(waitMs));
697
743
  if (options?.limit !== void 0) params.set("limit", String(options.limit));
744
+ if (options?.includeInvites === true) params.set("invites", "1");
698
745
  const qs = params.toString();
699
746
  const timeoutMs = options?.timeoutMs !== void 0 ? options.timeoutMs : waitMs > 0 ? waitMs + INBOX_WAIT_TIMEOUT_GRACE_MS : void 0;
700
747
  return this.get(`/v1/inbox${qs ? `?${qs}` : ""}`, { ...options, timeoutMs });
@@ -710,7 +757,18 @@ var AgentChatClient = class _AgentChatClient {
710
757
  body,
711
758
  options
712
759
  );
713
- return res.decision;
760
+ const echoed = res !== null && typeof res === "object" ? res.decision : void 0;
761
+ const d = echoed !== null && typeof echoed === "object" ? echoed : {};
762
+ return {
763
+ ...d,
764
+ id: typeof d.id === "string" ? d.id : null,
765
+ conversation_id: typeof d.conversation_id === "string" ? d.conversation_id : conversationId,
766
+ decision: d.decision ?? options.decision,
767
+ category: d.category !== void 0 ? d.category : options.category ?? null,
768
+ through_message_id: d.through_message_id !== void 0 ? d.through_message_id : options.throughMessageId ?? null,
769
+ defer_until: d.defer_until ?? null,
770
+ created_at: typeof d.created_at === "string" ? d.created_at : null
771
+ };
714
772
  }
715
773
  markConversationRead(conversationId, throughMessageId, options) {
716
774
  const body = { through_message_id: throughMessageId };
@@ -735,14 +793,14 @@ var AgentChatClient = class _AgentChatClient {
735
793
  }
736
794
  async post(path, body, opts) {
737
795
  const res = await this.http.request("POST", path, {
738
- ...this.toRequestOpts(opts),
796
+ ...this.toRequestOpts(opts, { idempotent: false }),
739
797
  body
740
798
  });
741
799
  return res.data;
742
800
  }
743
801
  async patch(path, body, opts) {
744
802
  const res = await this.http.request("PATCH", path, {
745
- ...this.toRequestOpts(opts),
803
+ ...this.toRequestOpts(opts, { idempotent: false }),
746
804
  body
747
805
  });
748
806
  return res.data;
@@ -757,11 +815,21 @@ var AgentChatClient = class _AgentChatClient {
757
815
  });
758
816
  return res.data;
759
817
  }
760
- toRequestOpts(opts) {
818
+ /**
819
+ * Call options for the transport. A per-call `retry` never makes a
820
+ * non-idempotent request (POST, PATCH) without an Idempotency-Key
821
+ * retryable: a retried verdict would be recorded twice (a `defer` would
822
+ * climb the reminder ladder twice). `'never'` always applies.
823
+ */
824
+ toRequestOpts(opts, kind = { idempotent: true }) {
825
+ const retry = opts?.retry;
826
+ const keyed = typeof opts?.idempotencyKey === "string" && opts.idempotencyKey.length > 0;
827
+ const applies = retry !== void 0 && (retry === "never" || kind.idempotent || keyed);
761
828
  return {
762
829
  signal: opts?.signal,
763
830
  timeoutMs: opts?.timeoutMs,
764
- idempotencyKey: opts?.idempotencyKey
831
+ idempotencyKey: opts?.idempotencyKey,
832
+ ...applies ? { retry } : {}
765
833
  };
766
834
  }
767
835
  // ─── Static, unauthenticated endpoints ────────────────────────────────────
@@ -779,10 +847,7 @@ var AgentChatClient = class _AgentChatClient {
779
847
  * Both carry the cap in `limit`.
780
848
  */
781
849
  static async register(options) {
782
- const http = new HttpTransport({
783
- baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
784
- defaultHeaders: clientIdentityHeaders(options.clientIdentity)
785
- });
850
+ const http = staticTransport(options);
786
851
  const res = await http.request("POST", "/v1/register", {
787
852
  body: {
788
853
  email: options.email,
@@ -790,7 +855,8 @@ var AgentChatClient = class _AgentChatClient {
790
855
  display_name: options.display_name,
791
856
  description: options.description
792
857
  },
793
- retry: "never"
858
+ retry: "never",
859
+ ...staticRequest(options)
794
860
  });
795
861
  return res.data;
796
862
  }
@@ -802,18 +868,17 @@ var AgentChatClient = class _AgentChatClient {
802
868
  */
803
869
  static async verify(pendingId, code, options) {
804
870
  const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
805
- const http = new HttpTransport({
806
- baseUrl,
807
- defaultHeaders: clientIdentityHeaders(options?.clientIdentity)
808
- });
871
+ const http = staticTransport(options);
809
872
  const res = await http.request("POST", "/v1/register/verify", {
810
873
  body: { pending_id: pendingId, code },
811
- retry: "never"
874
+ retry: "never",
875
+ ...staticRequest(options)
812
876
  });
813
877
  const client = new _AgentChatClient({
814
878
  apiKey: res.data.api_key,
815
879
  baseUrl,
816
- clientIdentity: options?.clientIdentity
880
+ clientIdentity: options?.clientIdentity,
881
+ ...options?.fetch ? { fetch: options.fetch } : {}
817
882
  });
818
883
  return { agent: res.data.agent, apiKey: res.data.api_key, client };
819
884
  }
@@ -832,17 +897,14 @@ var AgentChatClient = class _AgentChatClient {
832
897
  * successful return is not proof the pair exists.
833
898
  */
834
899
  static async recover(email, options) {
835
- const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
836
- const http = new HttpTransport({
837
- baseUrl,
838
- defaultHeaders: clientIdentityHeaders(options?.clientIdentity)
839
- });
900
+ const http = staticTransport(options);
840
901
  const res = await http.request("POST", "/v1/agents/recover", {
841
902
  // `handle: undefined` is dropped by JSON serialization, so a legacy
842
903
  // email-only call sends `{ email }` exactly as before — the server's
843
904
  // schema marks `handle` optional, not nullable.
844
905
  body: { email, handle: options?.handle },
845
- retry: "never"
906
+ retry: "never",
907
+ ...staticRequest(options)
846
908
  });
847
909
  return res.data;
848
910
  }
@@ -857,19 +919,17 @@ var AgentChatClient = class _AgentChatClient {
857
919
  */
858
920
  static async recoverVerify(pendingId, code, options) {
859
921
  const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
860
- const http = new HttpTransport({
861
- baseUrl,
862
- defaultHeaders: clientIdentityHeaders(options?.clientIdentity)
863
- });
922
+ const http = staticTransport(options);
864
923
  const res = await http.request(
865
924
  "POST",
866
925
  "/v1/agents/recover/verify",
867
- { body: { pending_id: pendingId, code }, retry: "never" }
926
+ { body: { pending_id: pendingId, code }, retry: "never", ...staticRequest(options) }
868
927
  );
869
928
  const client = new _AgentChatClient({
870
929
  apiKey: res.data.api_key,
871
930
  baseUrl,
872
- clientIdentity: options?.clientIdentity
931
+ clientIdentity: options?.clientIdentity,
932
+ ...options?.fetch ? { fetch: options.fetch } : {}
873
933
  });
874
934
  return { handle: res.data.handle, apiKey: res.data.api_key, client };
875
935
  }
@@ -1464,12 +1524,35 @@ var AgentChatClient = class _AgentChatClient {
1464
1524
  * The WebSocket client drives this automatically on reconnect; most
1465
1525
  * callers never need it directly.
1466
1526
  */
1467
- sync(opts) {
1527
+ async sync(opts) {
1528
+ return (await this.syncPage(opts)).rows;
1529
+ }
1530
+ /**
1531
+ * `sync()` with the response facts a poller needs: how long the server
1532
+ * held a long-poll (`waitedMs`) and its idle poll hint
1533
+ * (`pollIntervalSeconds`). With `waitMs` > 0 this is the long-poll body
1534
+ * pull; pass `retry: 'never'` when the caller has a deadline.
1535
+ */
1536
+ async syncPage(opts) {
1468
1537
  const params = new URLSearchParams();
1469
1538
  if (opts?.limit) params.set("limit", String(opts.limit));
1470
1539
  if (opts?.after !== void 0) params.set("after", opts.after);
1540
+ const waitMs = opts?.waitMs ?? 0;
1541
+ if (waitMs > 0) params.set("wait_ms", String(Math.floor(waitMs)));
1471
1542
  const qs = params.toString();
1472
- return this.get(`/v1/messages/sync${qs ? `?${qs}` : ""}`, opts);
1543
+ const timeoutMs = opts?.timeoutMs !== void 0 ? opts.timeoutMs : waitMs > 0 ? waitMs + INBOX_WAIT_TIMEOUT_GRACE_MS : void 0;
1544
+ const res = await this.http.request(
1545
+ "GET",
1546
+ `/v1/messages/sync${qs ? `?${qs}` : ""}`,
1547
+ this.toRequestOpts({ ...opts, timeoutMs })
1548
+ );
1549
+ return {
1550
+ rows: res.data,
1551
+ waitedMs: intHeader(res.headers, "x-agentchat-waited-ms"),
1552
+ pollIntervalSeconds: intHeader(res.headers, "x-agentchat-poll-interval-seconds"),
1553
+ requestId: res.requestId,
1554
+ headers: res.headers
1555
+ };
1473
1556
  }
1474
1557
  /**
1475
1558
  * Commit every delivery at-or-before the cursor as delivered.
@@ -1487,6 +1570,20 @@ var AgentChatClient = class _AgentChatClient {
1487
1570
  }
1488
1571
  };
1489
1572
 
1573
+ // src/connect-budget.ts
1574
+ var CONNECT_BUDGET_CLOSE_CODE = 1013;
1575
+ var CONNECT_BUDGET_MIN_DELAY_MS = 1e3;
1576
+ var CONNECT_BUDGET_MAX_DELAY_MS = 36e5;
1577
+ var HINT_RE = /retry[_-]after(?:\s*[=:]\s*|\s+)(\d+)/i;
1578
+ function connectBudgetDelayMs(close) {
1579
+ if (close.code !== CONNECT_BUDGET_CLOSE_CODE) return null;
1580
+ const match = HINT_RE.exec(typeof close.reason === "string" ? close.reason : "");
1581
+ if (match?.[1] === void 0) return null;
1582
+ const ms = Number(match[1]) * 1e3;
1583
+ if (!Number.isFinite(ms)) return null;
1584
+ return Math.min(CONNECT_BUDGET_MAX_DELAY_MS, Math.max(CONNECT_BUDGET_MIN_DELAY_MS, Math.round(ms)));
1585
+ }
1586
+
1490
1587
  // src/ws-resolver.ts
1491
1588
  function isNode() {
1492
1589
  const versions = globalThis.process?.versions;
@@ -1518,17 +1615,23 @@ Install the \`ws\` package: Node 20 has no native WebSocket, and on Node 22+ \`w
1518
1615
  }
1519
1616
 
1520
1617
  // src/realtime.ts
1618
+ var DEFAULT_MAX_QUEUED_MESSAGES = 1e3;
1619
+ var DEFAULT_IN_FLIGHT_ADOPT_MS = 15 * 6e4;
1521
1620
  var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15e3;
1522
1621
  var DEFAULT_LIVENESS_TIMEOUT_MS = 1e5;
1523
1622
  var CLIENT_CLOSE_CODE = 4e3;
1524
1623
  var LONG_OUTAGE_AFTER_ATTEMPTS = 60;
1525
1624
  var LONG_OUTAGE_MAX_INTERVAL_MS = 5 * 6e4;
1526
1625
  var RECONNECT_JITTER_RATIO = 0.25;
1626
+ var BUDGET_JITTER_RATIO = 0.1;
1527
1627
  var AUTH_RETRY_INTERVAL_MS = 75e4;
1528
1628
  var AUTH_RETRY_JITTER_RATIO = 0.2;
1529
1629
  var UNAMBIGUOUS_AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([4401, 4403]);
1530
1630
  var AMBIGUOUS_AUTH_CLOSE_CODE = 1008;
1531
1631
  var SERVER_AUTH_CLOSE_REASONS = ["invalid token"];
1632
+ function wakePayloadOf(frame) {
1633
+ return frame.payload;
1634
+ }
1532
1635
  function isAuthRejectionClose(code, reason) {
1533
1636
  if (UNAMBIGUOUS_AUTH_CLOSE_CODES.has(code)) return true;
1534
1637
  if (code !== AMBIGUOUS_AUTH_CLOSE_CODE) return false;
@@ -1609,6 +1712,16 @@ var RealtimeClient = class {
1609
1712
  // True only when the server echoed the 'ack' capability in hello.ok.
1610
1713
  // Per-connection: reset on every close and re-negotiated on every HELLO.
1611
1714
  ackMode = false;
1715
+ // Every capability the server echoed in this connection's hello.ok.
1716
+ negotiated = /* @__PURE__ */ new Set();
1717
+ // What this connection's HELLO offered, and whether it has been sent.
1718
+ offeredThisHello = [];
1719
+ helloSent = false;
1720
+ // The current socket is being closed for a quiet reconnect (maybeRenegotiateAck, jobDone).
1721
+ quietReconnect = null;
1722
+ // The current socket's upgrade was answered with an HTTP status instead of
1723
+ // 101 (Node `ws` only; a browser-shaped socket cannot see it): ordinary backoff.
1724
+ upgradeRejection = null;
1612
1725
  /** One error per long outage, then silent until a stable connection. */
1613
1726
  longOutageAnnounced = false;
1614
1727
  /** One error per run of rejected handshakes, then silent until hello.ok. */
@@ -1619,19 +1732,20 @@ var RealtimeClient = class {
1619
1732
  // dispatch suppress its own redelivery.
1620
1733
  dedupSeen = /* @__PURE__ */ new Set();
1621
1734
  // Dispatches still running, by message id. A second copy of an id that is
1622
- // here on the same connection (the server's reconnect backlog and the REST
1623
- // drain bring the same stored rows; a slow handler is still on the first)
1624
- // is not handed to the handlers again: it takes the first copy's outcome,
1625
- // and nothing ever waits for it. An entry lives exactly as long as its
1626
- // handlers run, so the map is bounded by the dispatches in flight.
1735
+ // here (the server's reconnect backlog and the REST drain bring the same
1736
+ // stored rows; a lost ack makes the server re-offer it after a reconnect;
1737
+ // a slow handler is still on the first) is not handed to the handlers
1738
+ // again: it takes the first copy's outcome, and nothing ever waits for it.
1739
+ // On the same connection always; on a later one while the first copy has
1740
+ // run less than `inFlightAdoptMs` — past that a re-offer is dispatched
1741
+ // afresh, so a handler that never finishes cannot hold its message for
1742
+ // good. An entry lives exactly as long as its handlers run, so the map is
1743
+ // bounded by the dispatches in flight.
1627
1744
  inFlight = /* @__PURE__ */ new Map();
1628
1745
  // Drain rows that adopted an in-flight copy instead of being dispatched.
1629
1746
  // The cursor reads that copy's outcome; it never waits for it.
1630
1747
  drainAdopted = /* @__PURE__ */ new WeakMap();
1631
- // Bumped on every socket close. Copies adopt an in-flight first copy only
1632
- // on the same connection; a re-offer on a later one is dispatched afresh
1633
- // even while the first copy runs (a handler that never finishes must not
1634
- // swallow every re-offer).
1748
+ // Bumped on every socket close; recorded on each dispatch for diagnostics.
1635
1749
  generation = 0;
1636
1750
  // Envelopes injected by the REST drain, as opposed to live WS frames.
1637
1751
  // Drain rows are acknowledged via the REST sync/ack cursor, never via a
@@ -1649,6 +1763,20 @@ var RealtimeClient = class {
1649
1763
  // reason about than interleaved read cursors.
1650
1764
  drainInFlight = false;
1651
1765
  orderStates = /* @__PURE__ */ new Map();
1766
+ // Per-conversation serial lanes for message.new handlers (promise 2: one
1767
+ // message at a time per conversation, in seq order). The tail of each
1768
+ // lane; an idle lane has no entry, so the map holds busy lanes only.
1769
+ lanes = /* @__PURE__ */ new Map();
1770
+ // Handler runs queued or running across all lanes (backpressure).
1771
+ queuedJobs = 0;
1772
+ // Messages were left un-taken because the queue was full; fetched again once it drains.
1773
+ shedding = false;
1774
+ // A backpressure refetch reconnect is under way: intake stays refused until
1775
+ // the new socket's hello.ok (a frame read off the closing socket could
1776
+ // overtake one the server is about to re-offer).
1777
+ refetchPending = false;
1778
+ // A drain was asked for while one ran: run once more when it ends.
1779
+ drainAgain = false;
1652
1780
  disposed = false;
1653
1781
  constructor(options) {
1654
1782
  const dedupCacheSize = typeof options.dedupCacheSize === "number" && Number.isFinite(options.dedupCacheSize) && options.dedupCacheSize >= 1 ? Math.floor(options.dedupCacheSize) : DEFAULT_DEDUP_CACHE_SIZE;
@@ -1668,7 +1796,14 @@ var RealtimeClient = class {
1668
1796
  dedupCacheSize,
1669
1797
  ackOnReceipt: options.ackOnReceipt ?? false,
1670
1798
  webSocket: options.webSocket,
1671
- clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY
1799
+ clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY,
1800
+ maxQueuedMessages: typeof options.maxQueuedMessages === "number" && Number.isInteger(options.maxQueuedMessages) && options.maxQueuedMessages >= 1 ? options.maxQueuedMessages : DEFAULT_MAX_QUEUED_MESSAGES,
1801
+ inFlightAdoptMs: typeof options.inFlightAdoptMs === "number" && Number.isFinite(options.inFlightAdoptMs) && options.inFlightAdoptMs >= 0 ? options.inFlightAdoptMs : DEFAULT_IN_FLIGHT_ADOPT_MS,
1802
+ offeredCapabilities: [
1803
+ "ack",
1804
+ ...options.capabilities?.heartbeat === false ? [] : ["heartbeat"],
1805
+ ...options.capabilities?.rewake === true ? ["rewake"] : []
1806
+ ]
1672
1807
  };
1673
1808
  }
1674
1809
  /**
@@ -1712,6 +1847,10 @@ var RealtimeClient = class {
1712
1847
  this.ws = ws;
1713
1848
  this.authenticated = false;
1714
1849
  this.ackMode = false;
1850
+ this.negotiated = /* @__PURE__ */ new Set();
1851
+ this.offeredThisHello = [];
1852
+ this.helloSent = false;
1853
+ this.upgradeRejection = null;
1715
1854
  this.livenessMs = this.options.livenessTimeoutMs ?? (isPingCapable(ws) ? DEFAULT_LIVENESS_TIMEOUT_MS : 0);
1716
1855
  this.armHandshakeDeadline();
1717
1856
  const current = () => this.ws === ws;
@@ -1722,7 +1861,7 @@ var RealtimeClient = class {
1722
1861
  JSON.stringify({
1723
1862
  type: "hello",
1724
1863
  api_key: this.options.apiKey,
1725
- capabilities: ["ack"],
1864
+ capabilities: this.helloCapabilities(),
1726
1865
  client: this.options.clientIdentity.name,
1727
1866
  ...this.options.clientIdentity.version ? { client_version: this.options.clientIdentity.version } : {}
1728
1867
  })
@@ -1745,7 +1884,15 @@ var RealtimeClient = class {
1745
1884
  if (message.type === "hello.ok") {
1746
1885
  this.authenticated = true;
1747
1886
  const caps = message.capabilities;
1748
- this.ackMode = Array.isArray(caps) && caps.includes("ack");
1887
+ const offered = new Set(this.offeredThisHello);
1888
+ this.negotiated = new Set(
1889
+ Array.isArray(caps) ? caps.filter((c) => typeof c === "string" && offered.has(c)) : []
1890
+ );
1891
+ this.ackMode = this.negotiated.has("ack");
1892
+ this.refetchPending = false;
1893
+ if (this.negotiated.has("heartbeat") && this.livenessMs === 0 && this.options.livenessTimeoutMs === null) {
1894
+ this.livenessMs = DEFAULT_LIVENESS_TIMEOUT_MS;
1895
+ }
1749
1896
  this.clearHandshakeTimer();
1750
1897
  this.touchLiveness();
1751
1898
  this.startStabilityTimer();
@@ -1768,7 +1915,8 @@ var RealtimeClient = class {
1768
1915
  return;
1769
1916
  }
1770
1917
  if (this.isMessageNew(message)) {
1771
- if (this.options.ackOnReceipt) {
1918
+ if (this.refuseIntake()) return;
1919
+ if (this.options.ackOnReceipt && this.hasMessageHandler()) {
1772
1920
  const messageId = this.extractMessageId(message);
1773
1921
  if (messageId !== null) this.sendAckFrame(messageId);
1774
1922
  }
@@ -1794,7 +1942,8 @@ var RealtimeClient = class {
1794
1942
  // lowercases it, so it must be a string here.
1795
1943
  reason: String(event.reason ?? ""),
1796
1944
  wasClean: event.wasClean,
1797
- initiator: "server"
1945
+ // A quiet reconnect's polite close was this client's own decision.
1946
+ initiator: this.quietReconnect !== null ? "client" : "server"
1798
1947
  });
1799
1948
  };
1800
1949
  if (isPingCapable(ws)) {
@@ -1803,6 +1952,22 @@ var RealtimeClient = class {
1803
1952
  };
1804
1953
  ws.on("ping", alive);
1805
1954
  ws.on("pong", alive);
1955
+ ws.on("unexpected-response", ((req, res) => {
1956
+ const response = res;
1957
+ if (current()) {
1958
+ this.upgradeRejection = { status: typeof response.statusCode === "number" ? response.statusCode : 0 };
1959
+ }
1960
+ try {
1961
+ response.resume?.();
1962
+ } catch {
1963
+ }
1964
+ try {
1965
+ const terminate = ws.terminate;
1966
+ if (typeof terminate === "function") terminate.call(ws);
1967
+ else req.destroy?.();
1968
+ } catch {
1969
+ }
1970
+ }));
1806
1971
  }
1807
1972
  }
1808
1973
  /**
@@ -1850,10 +2015,16 @@ var RealtimeClient = class {
1850
2015
  async drainOfflineEnvelopes() {
1851
2016
  const client = this.options.client;
1852
2017
  if (!client) return;
1853
- if (this.drainInFlight) return;
2018
+ if (this.drainInFlight) {
2019
+ this.drainAgain = true;
2020
+ return;
2021
+ }
1854
2022
  this.drainInFlight = true;
1855
2023
  try {
1856
- await this.runDrain(client);
2024
+ do {
2025
+ this.drainAgain = false;
2026
+ await this.runDrain(client);
2027
+ } while (this.drainAgain && !this.disposed && !this.shedding);
1857
2028
  } finally {
1858
2029
  this.drainInFlight = false;
1859
2030
  }
@@ -1896,9 +2067,15 @@ var RealtimeClient = class {
1896
2067
  this.restDrainOrigin.add(envelope);
1897
2068
  return envelope;
1898
2069
  });
1899
- for (const envelope of envelopes) {
2070
+ let injected = envelopes.length;
2071
+ for (const [index, envelope] of envelopes.entries()) {
2072
+ if (this.refuseIntake()) {
2073
+ injected = index;
2074
+ break;
2075
+ }
1900
2076
  this.processOrderedMessage(envelope);
1901
2077
  }
2078
+ const shed = injected < envelopes.length;
1902
2079
  if (!acksFrozen) {
1903
2080
  let ackCursor = null;
1904
2081
  for (let i = 0; i < rows.length; i++) {
@@ -1938,6 +2115,7 @@ var RealtimeClient = class {
1938
2115
  }
1939
2116
  }
1940
2117
  }
2118
+ if (shed) return;
1941
2119
  if (invalidIndex >= 0) {
1942
2120
  this.emitError(
1943
2121
  new ConnectionError(
@@ -2015,9 +2193,14 @@ var RealtimeClient = class {
2015
2193
  */
2016
2194
  handleClose(info) {
2017
2195
  const duringHandshake = !this.authenticated;
2196
+ const rejection = this.upgradeRejection;
2197
+ const quietReconnect = this.quietReconnect;
2198
+ this.quietReconnect = null;
2199
+ this.upgradeRejection = null;
2200
+ this.negotiated = /* @__PURE__ */ new Set();
2018
2201
  this.clearWatchdogs();
2019
2202
  this.cancelStabilityTimer();
2020
- this.noteConnectionEnded();
2203
+ if (quietReconnect === null) this.noteConnectionEnded();
2021
2204
  this.authenticated = false;
2022
2205
  this.ackMode = false;
2023
2206
  for (const handler of this.disconnectHandlers) {
@@ -2026,10 +2209,30 @@ var RealtimeClient = class {
2026
2209
  } catch {
2027
2210
  }
2028
2211
  }
2029
- if (this.options.ackOnReceipt) this.flushParkedFrames("connection_closed");
2212
+ if (this.options.ackOnReceipt || quietReconnect === "renegotiate") this.flushParkedFrames("connection_closed");
2030
2213
  this.resetOrderStates();
2031
2214
  this.generation++;
2032
2215
  if (this.disposed) return;
2216
+ if (quietReconnect !== null) {
2217
+ this.retryNow();
2218
+ return;
2219
+ }
2220
+ if (rejection !== null) {
2221
+ this.scheduleReconnect();
2222
+ return;
2223
+ }
2224
+ if (info.initiator === "server") {
2225
+ const budgetDelay = connectBudgetDelayMs({ code: info.code, reason: info.reason });
2226
+ if (budgetDelay !== null) {
2227
+ this.emitError(
2228
+ new ConnectionError(
2229
+ `the server refused the connection: connect budget exceeded (close ${info.code}); retrying in ${Math.round(budgetDelay / 1e3)}s`
2230
+ )
2231
+ );
2232
+ this.scheduleReconnect(this.jitteredAbove(budgetDelay, BUDGET_JITTER_RATIO));
2233
+ return;
2234
+ }
2235
+ }
2033
2236
  if (info.initiator === "server" && duringHandshake && isAuthRejectionClose(info.code, info.reason)) {
2034
2237
  this.enterBlocked(info.code, info.reason);
2035
2238
  return;
@@ -2056,7 +2259,8 @@ var RealtimeClient = class {
2056
2259
  }
2057
2260
  this.handleClose({ code, reason, wasClean: false, initiator: "client" });
2058
2261
  }
2059
- scheduleReconnect() {
2262
+ /** `serverDelayMs`: the server said how long to wait (connect budget); it replaces the backoff step. */
2263
+ scheduleReconnect(serverDelayMs) {
2060
2264
  if (this.disposed) return;
2061
2265
  if (this.reconnectTimer) return;
2062
2266
  if (!this.options.reconnect) {
@@ -2073,7 +2277,7 @@ var RealtimeClient = class {
2073
2277
  )
2074
2278
  );
2075
2279
  }
2076
- const delay = this.computeReconnectDelay(attempt);
2280
+ const delay = serverDelayMs ?? this.computeReconnectDelay(attempt);
2077
2281
  this.setState("backoff");
2078
2282
  this.reconnectTimer = setTimeout(() => {
2079
2283
  this.reconnectTimer = null;
@@ -2144,6 +2348,10 @@ var RealtimeClient = class {
2144
2348
  const factor = 1 - ratio + Math.random() * 2 * ratio;
2145
2349
  return Math.max(0, Math.floor(ms * factor));
2146
2350
  }
2351
+ /** Jitter in [ms, ms × (1 + ratio)]: `ms` is a floor (a server-given delay is never shortened). */
2352
+ jitteredAbove(ms, ratio) {
2353
+ return Math.max(0, Math.floor(ms * (1 + Math.random() * ratio)));
2354
+ }
2147
2355
  /** Jitter in [ms × (1 − ratio), ms]: `ms` is a ceiling. Thundering-herd-safe across a fleet. */
2148
2356
  jitteredBelow(ms, ratio) {
2149
2357
  const factor = 1 - Math.random() * ratio;
@@ -2224,7 +2432,9 @@ var RealtimeClient = class {
2224
2432
  this.handlers.set(event, handlers);
2225
2433
  }
2226
2434
  const stored = handler;
2435
+ const firstMessageHandler = event === "message.new" && handlers.size === 0;
2227
2436
  handlers.add(stored);
2437
+ if (firstMessageHandler) this.maybeRenegotiateAck();
2228
2438
  return () => {
2229
2439
  handlers.delete(stored);
2230
2440
  if (handlers.size === 0) this.handlers.delete(event);
@@ -2306,6 +2516,22 @@ var RealtimeClient = class {
2306
2516
  get ackNegotiated() {
2307
2517
  return this.ackMode;
2308
2518
  }
2519
+ /**
2520
+ * `true` while backpressure refuses new messages: from the moment the
2521
+ * handler queue filled (`maxQueuedMessages`) until it is back to half and,
2522
+ * without a REST client, the reconnect that fetches what was left is up.
2523
+ * A host can alarm when it stays true (handlers that hang).
2524
+ */
2525
+ get intakePaused() {
2526
+ return this.shedding || this.refetchPending;
2527
+ }
2528
+ /**
2529
+ * The capabilities this connection's `hello.ok` accepted (`ack`,
2530
+ * `heartbeat`, `rewake`, …). Empty before `hello.ok` and after a close.
2531
+ */
2532
+ get capabilities() {
2533
+ return this.negotiated;
2534
+ }
2309
2535
  /**
2310
2536
  * Close the socket, cancel every timer, and release all handlers. The
2311
2537
  * only way into `stopped`, and the only way the client ever stops on
@@ -2329,6 +2555,8 @@ var RealtimeClient = class {
2329
2555
  }
2330
2556
  this.authenticated = false;
2331
2557
  this.ackMode = false;
2558
+ this.negotiated = /* @__PURE__ */ new Set();
2559
+ this.refetchPending = false;
2332
2560
  this.setState("stopped");
2333
2561
  for (const handler of this.stoppedHandlers) {
2334
2562
  try {
@@ -2396,9 +2624,14 @@ var RealtimeClient = class {
2396
2624
  const messageId = this.extractMessageId(message);
2397
2625
  const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt;
2398
2626
  let settlement;
2399
- const inFlight = messageId !== null ? this.inFlight.get(messageId) : void 0;
2400
- const first = inFlight?.generation === this.generation ? inFlight : void 0;
2401
- if (messageId !== null && this.dedupHit(messageId)) {
2627
+ const running = messageId !== null ? this.inFlight.get(messageId) : void 0;
2628
+ const first = running !== void 0 && (running.generation === this.generation || // Still waiting in its lane: always the one to take; running: only
2629
+ // within the bound, counted from when the handler started.
2630
+ running.startedAt === null || Date.now() - running.startedAt < this.options.inFlightAdoptMs) ? running : void 0;
2631
+ const handlers = this.handlers.get("message.new");
2632
+ if (first === void 0 && (handlers === void 0 || handlers.size === 0)) {
2633
+ settlement = Promise.resolve(false);
2634
+ } else if (messageId !== null && this.dedupHit(messageId)) {
2402
2635
  settlement = Promise.resolve(true);
2403
2636
  if (ackAfterDispatch) this.sendAckFrame(messageId);
2404
2637
  } else if (messageId !== null && first !== void 0) {
@@ -2408,32 +2641,19 @@ var RealtimeClient = class {
2408
2641
  return ok;
2409
2642
  });
2410
2643
  } else {
2411
- const handlers = this.handlers.get("message.new");
2412
- const pending = [];
2413
- if (handlers) {
2414
- for (const handler of handlers) {
2415
- try {
2416
- const result = handler(message);
2417
- if (isThenable(result)) pending.push(result);
2418
- } catch (err) {
2419
- pending.push(Promise.reject(err));
2420
- }
2421
- }
2422
- }
2644
+ const snapshot = handlers ? [...handlers] : [];
2423
2645
  const entry = {
2424
2646
  promise: Promise.resolve(false),
2425
2647
  generation: this.generation,
2648
+ startedAt: null,
2426
2649
  settled: false,
2427
2650
  ok: false
2428
2651
  };
2429
- const own = Promise.allSettled(pending).then((outcomes) => {
2430
- let ok = true;
2431
- for (const outcome of outcomes) {
2432
- if (outcome.status === "rejected") {
2433
- ok = false;
2434
- this.emitError(toError(outcome.reason, "message.new"));
2435
- }
2436
- }
2652
+ const handled = this.runInLane(this.laneOf(message), () => {
2653
+ entry.startedAt = Date.now();
2654
+ return this.invokeMessageHandlers(message, snapshot);
2655
+ });
2656
+ const own = handled.then((ok) => {
2437
2657
  if (messageId !== null && this.inFlight.get(messageId) === entry) {
2438
2658
  this.inFlight.delete(messageId);
2439
2659
  }
@@ -2453,6 +2673,143 @@ var RealtimeClient = class {
2453
2673
  if (isDrainRow) this.drainSettlements.set(message, settlement);
2454
2674
  return settlement;
2455
2675
  }
2676
+ /**
2677
+ * Invoke one message's handlers (in registration order, synchronously),
2678
+ * then wait for every one of them. `true` when all finished without
2679
+ * throwing. Synchronous when every handler is (so a lane of plain
2680
+ * handlers never waits a tick); a promise otherwise. Never rejects.
2681
+ */
2682
+ invokeMessageHandlers(message, handlers) {
2683
+ if (handlers.length === 0) return false;
2684
+ const pending = [];
2685
+ let ok = true;
2686
+ for (const handler of handlers) {
2687
+ try {
2688
+ const result = handler(message);
2689
+ if (isThenable(result)) pending.push(result);
2690
+ } catch (err) {
2691
+ ok = false;
2692
+ this.emitError(toError(err, "message.new"));
2693
+ }
2694
+ }
2695
+ if (pending.length === 0) return ok;
2696
+ return Promise.allSettled(pending).then((outcomes) => {
2697
+ for (const outcome of outcomes) {
2698
+ if (outcome.status === "rejected") {
2699
+ ok = false;
2700
+ this.emitError(toError(outcome.reason, "message.new"));
2701
+ }
2702
+ }
2703
+ return ok;
2704
+ });
2705
+ }
2706
+ /** A message's serial lane: its conversation, or one lane for messages that name none. */
2707
+ laneOf(message) {
2708
+ const id = message.payload?.conversation_id;
2709
+ return typeof id === "string" && id.length > 0 ? `c:${id}` : "-";
2710
+ }
2711
+ /**
2712
+ * Run `task` when the lane is free: at once (synchronously) on an idle
2713
+ * lane, else after the task before it has finished. At most one task per
2714
+ * lane runs at a time; lanes run concurrently with each other.
2715
+ */
2716
+ runInLane(key, task) {
2717
+ const previous = this.lanes.get(key);
2718
+ this.queuedJobs += 1;
2719
+ if (previous === void 0) {
2720
+ const now2 = task();
2721
+ if (!isThenable(now2)) {
2722
+ this.jobDone();
2723
+ return Promise.resolve(now2);
2724
+ }
2725
+ void now2.then(
2726
+ () => this.jobDone(),
2727
+ () => this.jobDone()
2728
+ );
2729
+ this.setLaneTail(key, this.heldAtMost(now2));
2730
+ return now2;
2731
+ }
2732
+ const result = previous.then(task);
2733
+ void result.then(
2734
+ () => this.jobDone(),
2735
+ () => this.jobDone()
2736
+ );
2737
+ this.setLaneTail(key, previous.then(() => this.heldAtMost(result)));
2738
+ return result;
2739
+ }
2740
+ /**
2741
+ * New messages are not taken in: the queue is full, or a shedding episode
2742
+ * is under way (until the queue is back to half — a frame accepted in
2743
+ * between could overtake one left with the server in its conversation).
2744
+ */
2745
+ queueFull() {
2746
+ return this.shedding || this.queuedJobs >= this.options.maxQueuedMessages;
2747
+ }
2748
+ /**
2749
+ * Whether a new message is refused at intake. A full queue (or an episode
2750
+ * under way) refuses and starts/continues the episode; a refetch reconnect
2751
+ * under way refuses quietly — the new socket re-offers everything stored.
2752
+ */
2753
+ refuseIntake() {
2754
+ if (this.queueFull()) {
2755
+ this.startShedding();
2756
+ return true;
2757
+ }
2758
+ return this.refetchPending;
2759
+ }
2760
+ /** The queue is full: messages are left with the server from here (one notice per episode). */
2761
+ startShedding() {
2762
+ if (this.shedding) return;
2763
+ this.shedding = true;
2764
+ this.emitError(
2765
+ new ConnectionError(
2766
+ `message handlers are behind: ${this.queuedJobs} messages queued (maxQueuedMessages ${this.options.maxQueuedMessages}); new messages stay on the server, unacknowledged, and are fetched again once the handlers catch up`
2767
+ )
2768
+ );
2769
+ }
2770
+ /** One handler run finished; once the queue is back to half, fetch what was left with the server. */
2771
+ jobDone() {
2772
+ this.queuedJobs = Math.max(0, this.queuedJobs - 1);
2773
+ if (!this.shedding || this.queuedJobs > Math.floor(this.options.maxQueuedMessages / 2)) return;
2774
+ this.shedding = false;
2775
+ if (this.disposed) return;
2776
+ if (this.options.client) {
2777
+ void this.drainOfflineEnvelopes().catch((err) => {
2778
+ this.emitError(err instanceof Error ? err : new ConnectionError("sync drain failed"));
2779
+ });
2780
+ } else if (this.ws !== null && this.authenticated) {
2781
+ this.refetchPending = true;
2782
+ this.closePolitely("refetch", "client reconnects to fetch messages it left with the server");
2783
+ }
2784
+ }
2785
+ /**
2786
+ * How long one handler run holds its lane: until it finishes, or
2787
+ * `inFlightAdoptMs` at most — a handler that never finishes must not stop
2788
+ * its conversation for good (it keeps running; the next message goes on).
2789
+ */
2790
+ heldAtMost(run2) {
2791
+ const ms = this.options.inFlightAdoptMs;
2792
+ return new Promise((resolve) => {
2793
+ const timer = setTimeout(resolve, ms);
2794
+ unref(timer);
2795
+ run2.then(
2796
+ () => {
2797
+ clearTimeout(timer);
2798
+ resolve();
2799
+ },
2800
+ () => {
2801
+ clearTimeout(timer);
2802
+ resolve();
2803
+ }
2804
+ );
2805
+ });
2806
+ }
2807
+ setLaneTail(key, tail) {
2808
+ this.lanes.set(key, tail);
2809
+ void tail.then(() => {
2810
+ if (this.lanes.get(key) === tail) this.lanes.delete(key);
2811
+ });
2812
+ }
2456
2813
  /**
2457
2814
  * Best-effort delivery ack for one processed message. No-op unless the
2458
2815
  * server negotiated ack-mode on this connection. Send failures are
@@ -2486,6 +2843,56 @@ var RealtimeClient = class {
2486
2843
  this.dedupSeen.delete(oldest);
2487
2844
  }
2488
2845
  }
2846
+ /**
2847
+ * The capabilities this HELLO offers. `ack` only while a `message.new`
2848
+ * handler is attached: with no handler nothing on this machine receives a
2849
+ * message, and an ack-mode socket that never acks would leave every
2850
+ * envelope `stored` until the recipient backlog cap. Without `ack` the
2851
+ * server marks envelopes delivered as it sends them, which is what a
2852
+ * handler-less 1.2 client effectively got (it acked frames no handler saw).
2853
+ * The next HELLO, after a handler is attached, offers it again.
2854
+ */
2855
+ helloCapabilities() {
2856
+ const withAck = this.hasMessageHandler();
2857
+ this.offeredThisHello = this.options.offeredCapabilities.filter((c) => c !== "ack" || withAck);
2858
+ this.helloSent = true;
2859
+ return this.offeredThisHello;
2860
+ }
2861
+ /**
2862
+ * The first `message.new` handler was attached after this socket's HELLO
2863
+ * went out without `ack`: reconnect once, quietly (no error, no backoff
2864
+ * step), so the next HELLO negotiates delivery acks. Frames parked on a
2865
+ * seq gap are handed to the handlers first — this socket was marked on
2866
+ * send, so nothing would re-offer them.
2867
+ */
2868
+ maybeRenegotiateAck() {
2869
+ if (this.disposed || this.ws === null || !this.helloSent) return;
2870
+ if (this.offeredThisHello.includes("ack")) return;
2871
+ const ws = this.ws;
2872
+ queueMicrotask(() => {
2873
+ if (this.ws !== ws || this.disposed || !this.hasMessageHandler()) return;
2874
+ this.closePolitely("renegotiate", "client reconnects to negotiate delivery acks");
2875
+ });
2876
+ }
2877
+ /**
2878
+ * A quiet reconnect: close the socket politely and keep reading its frames
2879
+ * until it has closed; the close then reconnects at once (no backoff step,
2880
+ * no notice). Its liveness watchdog still ends a pipe that never answers.
2881
+ */
2882
+ closePolitely(kind, reason) {
2883
+ const ws = this.ws;
2884
+ if (ws === null || this.quietReconnect !== null) return;
2885
+ this.quietReconnect = kind;
2886
+ try {
2887
+ ws.close(1e3, reason);
2888
+ } catch {
2889
+ }
2890
+ }
2891
+ /** A `message.new` handler is attached: only then has this machine received a message. */
2892
+ hasMessageHandler() {
2893
+ const handlers = this.handlers.get("message.new");
2894
+ return handlers !== void 0 && handlers.size > 0;
2895
+ }
2489
2896
  extractMessageId(message) {
2490
2897
  const id = message.payload?.id;
2491
2898
  return typeof id === "string" && id.length > 0 ? id : null;
@@ -2517,11 +2924,26 @@ var RealtimeClient = class {
2517
2924
  return "payload is not an object";
2518
2925
  }
2519
2926
  const p = payload;
2520
- for (const key of ["reason", "conversation_id", "anchor_message_id", "at"]) {
2521
- if (typeof p[key] !== "string" || p[key] === "") return `${key} is not a non-empty string`;
2927
+ const text = (key) => typeof p[key] !== "string" || p[key] === "" ? `${key} is not a non-empty string` : null;
2928
+ const integerStep = typeof p.step === "number" && Number.isInteger(p.step);
2929
+ if (!this.negotiated.has("rewake")) {
2930
+ return text("reason") ?? text("conversation_id") ?? text("anchor_message_id") ?? text("at") ?? (integerStep ? null : "step is not an integer");
2931
+ }
2932
+ const reasonProblem = text("reason") ?? text("at");
2933
+ if (reasonProblem !== null) return reasonProblem;
2934
+ switch (p.reason) {
2935
+ case "reminder":
2936
+ return text("conversation_id") ?? text("anchor_message_id") ?? (integerStep ? null : "step is not an integer");
2937
+ case "unanswered": {
2938
+ const ids = p.conversation_ids;
2939
+ if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) {
2940
+ return "conversation_ids is not a list of ids";
2941
+ }
2942
+ return integerStep ? null : "step is not an integer";
2943
+ }
2944
+ default:
2945
+ return p.step === void 0 || integerStep ? null : "step is not an integer";
2522
2946
  }
2523
- if (typeof p.step !== "number" || !Number.isInteger(p.step)) return "step is not an integer";
2524
- return null;
2525
2947
  }
2526
2948
  // ─── Per-conversation seq ordering ───────────────────────────────────────
2527
2949
  //
@@ -2633,7 +3055,7 @@ var RealtimeClient = class {
2633
3055
  type: "message.new",
2634
3056
  payload: row
2635
3057
  };
2636
- if (this.options.ackOnReceipt) {
3058
+ if (this.options.ackOnReceipt && this.hasMessageHandler()) {
2637
3059
  const messageId = this.extractMessageId(envelope);
2638
3060
  if (messageId !== null) this.sendAckFrame(messageId);
2639
3061
  }
@@ -2783,6 +3205,8 @@ var RealtimeClient = class {
2783
3205
  var gate_exports = {};
2784
3206
  __export(gate_exports, {
2785
3207
  BARE_TOOL_NAMER: () => BARE_TOOL_NAMER,
3208
+ LEGACY_GATE_CALL_ANSWER_FORMAT: () => LEGACY_GATE_CALL_ANSWER_FORMAT,
3209
+ LEGACY_GATE_CALL_PREAMBLE: () => LEGACY_GATE_CALL_PREAMBLE,
2786
3210
  anchorOf: () => anchorOf,
2787
3211
  buildPrompt: () => buildPrompt,
2788
3212
  canonicalJson: () => canonicalJson,
@@ -2797,7 +3221,18 @@ function mcpToolNamer(serverName) {
2797
3221
  return (tool) => `mcp__${serverName}__${tool}`;
2798
3222
  }
2799
3223
  var HOSTED_TOOL_TOKEN = /\bagentchat_[a-z0-9_]+\b/g;
2800
- var DECIDE_TOOL = "agentchat_decide";
3224
+ var LEGACY_DECIDE_TOOL = "agentchat_decide";
3225
+ function LEGACY_GATE_CALL_PREAMBLE(namer = BARE_TOOL_NAMER) {
3226
+ return `You are triaging your AgentChat tray before any turn starts. This call has NO tools: do not call ${namer(LEGACY_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.`;
3227
+ }
3228
+ function LEGACY_GATE_CALL_ANSWER_FORMAT(categories) {
3229
+ let shape = '{"decisions": [{"conversation_id": "<conversation_id from a card>", "decision": "reply" | "dismiss" | "defer"';
3230
+ if (categories.length > 0) {
3231
+ shape += `, "category": "<one of: ${categories.join(", ")}>"`;
3232
+ }
3233
+ shape += "}]}";
3234
+ return "Answer with ONLY a JSON object, no prose and no code fences, in this shape: " + shape + " \u2014 one entry per card, every card decided.";
3235
+ }
2801
3236
  var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "respond", "answer", "yes", "true"]);
2802
3237
  var DISMISS_TOKENS = /* @__PURE__ */ new Set([
2803
3238
  "dismiss",
@@ -2856,10 +3291,9 @@ function buildPrompt(tray, options) {
2856
3291
  const namer = options?.toolNamer ?? BARE_TOOL_NAMER;
2857
3292
  const cards = cardsOf(tray);
2858
3293
  const categories = categoriesOf(tray);
2859
- const sections = [];
2860
- sections.push(
2861
- `You are triaging your AgentChat tray before any turn starts. This call has NO tools: do not call ${namer(DECIDE_TOOL)}, do not open or send anything, and do not write a reply. Answer the question below for every card, in JSON only; the host records your verdicts from that JSON. Where the question says to record a verdict or to send, that happens later: for each conversation you mark "reply", a turn will be started in which you open it and reply.`
2862
- );
3294
+ const preamble = servedText(options?.texts?.gate_call_preamble) ?? LEGACY_GATE_CALL_PREAMBLE(namer);
3295
+ const answerFormat = servedText(options?.texts?.gate_call_answer_format) ?? LEGACY_GATE_CALL_ANSWER_FORMAT(categories);
3296
+ const sections = [preamble];
2863
3297
  sections.push(question.trim().replace(HOSTED_TOOL_TOKEN, (token) => namer(token)));
2864
3298
  if (categories.length > 0) {
2865
3299
  sections.push(`Categories: ${categories.join(", ")}`);
@@ -2873,16 +3307,12 @@ function buildPrompt(tray, options) {
2873
3307
  sections.push(`Card ${index + 1} of ${count}
2874
3308
  ${canonicalJson(card)}`);
2875
3309
  });
2876
- let shape = '{"decisions": [{"conversation_id": "<conversation_id from a card>", "decision": "reply" | "dismiss" | "defer"';
2877
- if (categories.length > 0) {
2878
- shape += `, "category": "<one of: ${categories.join(", ")}>"`;
2879
- }
2880
- shape += "}]}";
2881
- sections.push(
2882
- "Answer with ONLY a JSON object, no prose and no code fences, in this shape: " + shape + " \u2014 one entry per card, every card decided."
2883
- );
3310
+ sections.push(answerFormat);
2884
3311
  return sections.join("\n\n");
2885
3312
  }
3313
+ function servedText(value) {
3314
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
3315
+ }
2886
3316
  function parseVerdicts(text, tray) {
2887
3317
  const raw = extractJson(text);
2888
3318
  if (raw === null) return null;
@@ -2951,13 +3381,20 @@ async function run(options) {
2951
3381
  const cards = cardsOf(options.tray);
2952
3382
  const ids = cards.map((card) => card.conversation_id);
2953
3383
  if (ids.length === 0) return emptyResult("empty", [], null);
3384
+ let prompt;
2954
3385
  let text;
2955
3386
  try {
2956
- const prompt = buildPrompt(options.tray, { toolNamer: options.toolNamer });
2957
- text = await options.callModel(prompt);
3387
+ prompt = buildPrompt(options.tray, { texts: options.texts, toolNamer: options.toolNamer });
3388
+ } catch (err) {
3389
+ return emptyResult("fail_closed", ids, describe(err));
3390
+ }
3391
+ if (options.signal?.aborted) return emptyResult("fail_closed", ids, "the gate was stopped");
3392
+ try {
3393
+ text = options.signal ? await options.callModel(prompt, { signal: options.signal }) : await options.callModel(prompt);
2958
3394
  } catch (err) {
2959
3395
  return emptyResult("fail_closed", ids, `model call failed: ${describe(err)}`);
2960
3396
  }
3397
+ if (options.signal?.aborted) return emptyResult("fail_closed", ids, "the gate was stopped");
2961
3398
  const verdicts = parseVerdicts(text, options.tray);
2962
3399
  if (verdicts === null || verdicts.length === 0) {
2963
3400
  return emptyResult("fail_closed", ids, "no usable verdicts in the answer");
@@ -2970,6 +3407,10 @@ async function run(options) {
2970
3407
  for (const verdict of verdicts) {
2971
3408
  const card = byId.get(verdict.conversation_id);
2972
3409
  if (!card) continue;
3410
+ if (options.signal?.aborted) {
3411
+ decided.delete(verdict.conversation_id);
3412
+ continue;
3413
+ }
2973
3414
  if (verdict.decision === "reply") {
2974
3415
  reply.push(deferredReply(options.client, card, verdict.category));
2975
3416
  continue;
@@ -2985,6 +3426,10 @@ async function run(options) {
2985
3426
  recordFailures.push({ conversation_id: verdict.conversation_id, error: toError2(err) });
2986
3427
  }
2987
3428
  }
3429
+ if (options.signal?.aborted) {
3430
+ reply.length = 0;
3431
+ for (const v of verdicts) if (v.decision === "reply") decided.delete(v.conversation_id);
3432
+ }
2988
3433
  return {
2989
3434
  outcome: "decided",
2990
3435
  reply,
@@ -3034,6 +3479,2293 @@ function describe(err) {
3034
3479
  return err instanceof Error ? err.message : String(err);
3035
3480
  }
3036
3481
 
3482
+ // src/integration/index.ts
3483
+ var integration_exports = {};
3484
+ __export(integration_exports, {
3485
+ DEFAULT_MAX_MS: () => DEFAULT_MAX_MS,
3486
+ DEFAULT_QUIET_MS: () => DEFAULT_QUIET_MS,
3487
+ HOSTED_MCP_PATH: () => HOSTED_MCP_PATH,
3488
+ MANUAL_FETCH_TIMEOUT_MS: () => MANUAL_FETCH_TIMEOUT_MS,
3489
+ MANUAL_MAX_BYTES: () => MANUAL_MAX_BYTES,
3490
+ MANUAL_MAX_REDIRECTS: () => MANUAL_MAX_REDIRECTS,
3491
+ MANUAL_SKILL_NAME: () => MANUAL_SKILL_NAME,
3492
+ ManualSync: () => ManualSync,
3493
+ REQUIRED_HOSTED_TOOLS: () => REQUIRED_HOSTED_TOOLS,
3494
+ ReceiveLoop: () => ReceiveLoop,
3495
+ TEXTS_FETCH_TIMEOUT_MS: () => TEXTS_FETCH_TIMEOUT_MS,
3496
+ TEXTS_REFRESH_MS: () => TEXTS_REFRESH_MS,
3497
+ TEXTS_RETRY_MAX_MS: () => TEXTS_RETRY_MAX_MS,
3498
+ TEXTS_RETRY_MS: () => TEXTS_RETRY_MS,
3499
+ TextsCache: () => TextsCache,
3500
+ TurnTracker: () => TurnTracker,
3501
+ WakeCoalescer: () => WakeCoalescer,
3502
+ anchor: () => anchor_exports,
3503
+ applyInviteOutcome: () => applyInviteOutcome,
3504
+ applyOutcome: () => applyOutcome,
3505
+ hostedMcpUrl: () => hostedMcpUrl,
3506
+ inviteOutcome: () => inviteOutcome,
3507
+ isTexts: () => isTexts,
3508
+ manualFrontMatter: () => manualFrontMatter,
3509
+ manualVersion: () => manualVersion,
3510
+ probeHostedTools: () => probeHostedTools,
3511
+ renameWithRetry: () => renameWithRetry,
3512
+ replyPrompt: () => replyPrompt,
3513
+ syncManual: () => syncManual,
3514
+ turnOutcome: () => turnOutcome,
3515
+ writeAtomic: () => writeAtomic
3516
+ });
3517
+
3518
+ // src/integration/coalescer.ts
3519
+ var DEFAULT_QUIET_MS = 2e3;
3520
+ var DEFAULT_MAX_MS = 6e3;
3521
+ var WakeCoalescer = class {
3522
+ onCycle;
3523
+ onError;
3524
+ quietMs;
3525
+ maxMs;
3526
+ now;
3527
+ _setTimeout;
3528
+ _clearTimeout;
3529
+ timer = null;
3530
+ /** First wake of the burst the armed timer belongs to. */
3531
+ burstStartedAt = null;
3532
+ running = false;
3533
+ /** Wakes that arrived while the cycle ran: first and last. */
3534
+ pendingFirstAt = null;
3535
+ pendingLastAt = null;
3536
+ stopped = false;
3537
+ current = null;
3538
+ wakeCount = 0;
3539
+ absorbedCount = 0;
3540
+ cycleCount = 0;
3541
+ constructor(options) {
3542
+ const quiet = options.quietMs ?? DEFAULT_QUIET_MS;
3543
+ const max = options.maxMs ?? DEFAULT_MAX_MS;
3544
+ if (!(quiet >= 0) || !Number.isFinite(quiet)) throw new RangeError("quietMs must be a finite number >= 0");
3545
+ if (!(max >= quiet) || !Number.isFinite(max)) throw new RangeError("maxMs must be a finite number >= quietMs");
3546
+ this.onCycle = options.onCycle;
3547
+ this.onError = options.onError ?? (() => void 0);
3548
+ this.quietMs = quiet;
3549
+ this.maxMs = max;
3550
+ this.now = options.now ?? Date.now;
3551
+ this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
3552
+ this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle));
3553
+ }
3554
+ get state() {
3555
+ if (this.stopped) return "stopped";
3556
+ if (this.running) return "running";
3557
+ return this.timer !== null ? "waiting" : "idle";
3558
+ }
3559
+ /** True while a wake that arrived during the running cycle is waiting for it to end. */
3560
+ get pending() {
3561
+ return this.pendingFirstAt !== null;
3562
+ }
3563
+ counters() {
3564
+ return { wakes: this.wakeCount, absorbed: this.absorbedCount, cycles: this.cycleCount };
3565
+ }
3566
+ /** A wake. Starts a window, joins the open one, or earns one more cycle after the running one. */
3567
+ wake() {
3568
+ if (this.stopped) return;
3569
+ this.wakeCount += 1;
3570
+ const now2 = this.now();
3571
+ if (this.running) {
3572
+ if (this.pendingFirstAt === null) this.pendingFirstAt = now2;
3573
+ else this.absorbedCount += 1;
3574
+ this.pendingLastAt = now2;
3575
+ return;
3576
+ }
3577
+ if (this.timer === null) {
3578
+ this.burstStartedAt = now2;
3579
+ this.arm(this.quietMs);
3580
+ return;
3581
+ }
3582
+ this.absorbedCount += 1;
3583
+ const capAt = (this.burstStartedAt ?? now2) + this.maxMs;
3584
+ this.arm(Math.max(0, Math.min(now2 + this.quietMs, capAt) - now2));
3585
+ }
3586
+ /** Cancel the window and drop pending wakes; a running cycle finishes on its own. Later wakes are ignored. */
3587
+ stop() {
3588
+ this.stopped = true;
3589
+ this.clearTimer();
3590
+ this.pendingFirstAt = null;
3591
+ this.pendingLastAt = null;
3592
+ }
3593
+ /** Resolves when the running cycle (if any) has ended. */
3594
+ idle() {
3595
+ return this.current ?? Promise.resolve();
3596
+ }
3597
+ arm(delayMs) {
3598
+ this.clearTimer();
3599
+ this.timer = this._setTimeout(() => {
3600
+ this.timer = null;
3601
+ this.startCycle();
3602
+ }, delayMs);
3603
+ }
3604
+ clearTimer() {
3605
+ if (this.timer !== null) {
3606
+ this._clearTimeout(this.timer);
3607
+ this.timer = null;
3608
+ }
3609
+ }
3610
+ startCycle() {
3611
+ if (this.stopped || this.running) return;
3612
+ this.burstStartedAt = null;
3613
+ this.running = true;
3614
+ this.cycleCount += 1;
3615
+ let result;
3616
+ try {
3617
+ result = this.onCycle();
3618
+ } catch (err) {
3619
+ this.report(err);
3620
+ result = void 0;
3621
+ }
3622
+ const done = Promise.resolve(result).then(
3623
+ () => void 0,
3624
+ (err) => this.report(err)
3625
+ );
3626
+ this.current = done.then(() => this.endCycle());
3627
+ }
3628
+ endCycle() {
3629
+ this.running = false;
3630
+ this.current = null;
3631
+ const first = this.pendingFirstAt;
3632
+ const last = this.pendingLastAt;
3633
+ this.pendingFirstAt = null;
3634
+ this.pendingLastAt = null;
3635
+ if (this.stopped || first === null || last === null) return;
3636
+ const now2 = this.now();
3637
+ const dueAt = Math.max(now2, Math.min(last + this.quietMs, first + this.maxMs));
3638
+ this.burstStartedAt = first;
3639
+ this.arm(dueAt - now2);
3640
+ }
3641
+ report(err) {
3642
+ try {
3643
+ this.onError(err);
3644
+ } catch {
3645
+ }
3646
+ }
3647
+ };
3648
+
3649
+ // src/integration/outcome.ts
3650
+ function turnOutcome(input) {
3651
+ const conversationId = input.gateCard.conversation_id;
3652
+ const none = (reason) => ({
3653
+ action: "none",
3654
+ reason,
3655
+ conversationId
3656
+ });
3657
+ const turn = input.turn;
3658
+ if (turn.status === "still_running") return none("turn_running");
3659
+ const failed = turn.status !== "completed";
3660
+ const tray = input.freshTray;
3661
+ if (tray === null || tray === void 0) return none(failed ? "turn_failed" : "card_unknown");
3662
+ const fresh = cardsOf(tray).find((card) => card.conversation_id === conversationId);
3663
+ if (!fresh) return none(tray.truncated === true ? "card_unknown" : "card_left_tray");
3664
+ if (verdictRecordedSince(input.gateCard, fresh)) return none("turn_recorded_verdict");
3665
+ const anchor = anchorOf(input.gateCard) ?? null;
3666
+ if (answerWentOut(input.gateCard, fresh)) {
3667
+ return {
3668
+ action: "record_reply",
3669
+ reason: "answer_sent",
3670
+ conversationId,
3671
+ throughMessageId: anchor,
3672
+ category: input.category ?? null
3673
+ };
3674
+ }
3675
+ if (failed) return none("turn_failed");
3676
+ const calls = turn.status === "completed" ? turn.agentchatCalls : null;
3677
+ if (couldNotLook(calls)) return none("could_not_look");
3678
+ if ((input.silentBefore ?? 0) <= 0) return none("silent_first");
3679
+ if (callsAllSucceeded(calls)) {
3680
+ return {
3681
+ action: "record_dismiss",
3682
+ reason: "silent_again",
3683
+ conversationId,
3684
+ throughMessageId: anchor,
3685
+ category: "no_action_needed"
3686
+ };
3687
+ }
3688
+ return { action: "record_defer", reason: "silent_again", conversationId, throughMessageId: anchor, category: null };
3689
+ }
3690
+ function callsAllSucceeded(calls) {
3691
+ if (!calls || typeof calls !== "object") return false;
3692
+ const made = Number(calls.made);
3693
+ const failed = Number(calls.failed);
3694
+ return Number.isFinite(made) && made > 0 && Number.isFinite(failed) && failed === 0;
3695
+ }
3696
+ function inviteOutcome(input) {
3697
+ const inviteId = input.invite.invite_id;
3698
+ const none = (reason) => ({
3699
+ action: "none",
3700
+ reason,
3701
+ inviteId
3702
+ });
3703
+ const turn = input.turn;
3704
+ if (turn.status === "still_running") return none("turn_running");
3705
+ if (turn.status !== "completed") return none("turn_failed");
3706
+ const tray = input.freshTray;
3707
+ if (tray === null || tray === void 0) return none("invite_unknown");
3708
+ const invites = Array.isArray(tray.invites) ? tray.invites : [];
3709
+ const still = invites.some((invite) => invite?.invite_id === inviteId);
3710
+ if (!still) return none(tray.invites_truncated === true ? "invite_unknown" : "invite_answered");
3711
+ if (couldNotLook(turn.agentchatCalls)) return none("could_not_look");
3712
+ if ((input.silentBefore ?? 0) <= 0) return none("silent_first");
3713
+ if (input.requireKnownCalls !== false && !callsAllSucceeded(turn.agentchatCalls)) return none("silent_unconfirmed");
3714
+ return { action: "dismiss_invite", reason: "silent_again", inviteId };
3715
+ }
3716
+ async function applyOutcome(client, outcome) {
3717
+ if (outcome.action === "none") return false;
3718
+ await client.decisions.record(outcome.conversationId, {
3719
+ decision: outcome.action === "record_reply" ? "reply" : outcome.action === "record_defer" ? "defer" : "dismiss",
3720
+ ...outcome.category ? { category: outcome.category } : {},
3721
+ ...outcome.throughMessageId ? { throughMessageId: outcome.throughMessageId } : {}
3722
+ });
3723
+ return true;
3724
+ }
3725
+ async function applyInviteOutcome(client, outcome) {
3726
+ if (outcome.action !== "dismiss_invite") return false;
3727
+ await client.groups.dismissInvite(outcome.inviteId);
3728
+ return true;
3729
+ }
3730
+ function instant(value) {
3731
+ if (value instanceof Date) return value.getTime();
3732
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3733
+ if (typeof value !== "string" || value.length === 0) return null;
3734
+ const ms = Date.parse(value);
3735
+ return Number.isFinite(ms) ? ms : null;
3736
+ }
3737
+ function decisionKey(card) {
3738
+ const last = card.your_last_decision;
3739
+ if (!last || typeof last !== "object") return null;
3740
+ return `${String(last.decision)}|${String(last.category ?? "")}|${String(last.at ?? "")}`;
3741
+ }
3742
+ function verdictRecordedSince(gate, fresh) {
3743
+ const now2 = decisionKey(fresh);
3744
+ return now2 !== null && now2 !== decisionKey(gate);
3745
+ }
3746
+ function answerWentOut(gate, fresh) {
3747
+ const before = instant(gate.your_last_message_at);
3748
+ const after = instant(fresh.your_last_message_at);
3749
+ if (after !== null && (before === null || after > before)) return true;
3750
+ return gate.you_owe_reply === true && fresh.you_owe_reply === false;
3751
+ }
3752
+ function couldNotLook(calls) {
3753
+ if (!calls || typeof calls !== "object") return false;
3754
+ const made = Number(calls.made);
3755
+ const failed = Number(calls.failed);
3756
+ if (!Number.isFinite(made)) return false;
3757
+ return made <= 0 || Number.isFinite(failed) && failed >= made;
3758
+ }
3759
+
3760
+ // src/integration/anchor.ts
3761
+ var anchor_exports = {};
3762
+ __export(anchor_exports, {
3763
+ END_MARKER: () => END_MARKER,
3764
+ LEGACY_END_MARKER: () => LEGACY_END_MARKER,
3765
+ LEGACY_START_MARKER: () => LEGACY_START_MARKER,
3766
+ START_MARKER: () => START_MARKER,
3767
+ find: () => find,
3768
+ handleLine: () => handleLine,
3769
+ normalizeHandle: () => normalizeHandle,
3770
+ remove: () => remove,
3771
+ render: () => render,
3772
+ replace: () => replace
3773
+ });
3774
+ var START_MARKER = "<!-- agentchat:start -->";
3775
+ var END_MARKER = "<!-- agentchat:end -->";
3776
+ var LEGACY_START_MARKER = "<!-- agentchat-skill:start -->";
3777
+ var LEGACY_END_MARKER = "<!-- agentchat-skill:end -->";
3778
+ var HANDLE_PLACEHOLDER = "<handle>";
3779
+ var HANDLE_LINE_RE = /^<!-- agentchat:handle @?([A-Za-z0-9][A-Za-z0-9_-]*) -->$/;
3780
+ var HANDLE_CAPTURE = "@?([A-Za-z0-9][A-Za-z0-9_-]*)";
3781
+ var OLD_WORDINGS = [
3782
+ new RegExp(`I am ${HANDLE_CAPTURE} on AgentChat`),
3783
+ new RegExp(`You are \\*\\*${HANDLE_CAPTURE}\\*\\* on AgentChat`)
3784
+ ];
3785
+ function normalizeHandle(handle) {
3786
+ return handle.trim().replace(/^@/, "").trim().toLowerCase();
3787
+ }
3788
+ function handleLine(handle) {
3789
+ return `<!-- agentchat:handle ${normalizeHandle(handle)} -->`;
3790
+ }
3791
+ function render(texts, handle) {
3792
+ const bare = normalizeHandle(handle);
3793
+ if (bare.length === 0) throw new Error("anchor.render: the handle is empty");
3794
+ let line = typeof texts.identity_line === "string" ? texts.identity_line.trim() : "";
3795
+ if (!namesHandle(line, bare)) {
3796
+ const template = typeof texts.identity_line_template === "string" ? texts.identity_line_template : "";
3797
+ line = template.includes(HANDLE_PLACEHOLDER) ? template.split(HANDLE_PLACEHOLDER).join(bare).trim() : "";
3798
+ }
3799
+ if (!namesHandle(line, bare)) {
3800
+ throw new Error(`anchor.render: no served identity text names @${bare}`);
3801
+ }
3802
+ return [START_MARKER, handleLine(bare), line, END_MARKER].join("\n");
3803
+ }
3804
+ function find(text, options = {}) {
3805
+ const spans = blocksOf(text);
3806
+ const span = spans.find((s) => !s.legacy) ?? spans[0];
3807
+ if (!span) return null;
3808
+ const inner = text.slice(span.innerStart, span.innerEnd).replace(/\r\n/g, "\n");
3809
+ let handle = null;
3810
+ let marked = false;
3811
+ const kept = [];
3812
+ for (const line of inner.split("\n")) {
3813
+ const match = !marked ? HANDLE_LINE_RE.exec(line.trim()) : null;
3814
+ if (match) {
3815
+ marked = true;
3816
+ handle = (match[1] ?? "").toLowerCase();
3817
+ continue;
3818
+ }
3819
+ kept.push(line);
3820
+ }
3821
+ const body = kept.join("\n").trim();
3822
+ if (handle === null) handle = handleFromWording(body, options.template ?? null);
3823
+ return { start: span.start, end: span.end, handle, marked, legacy: span.legacy, body };
3824
+ }
3825
+ function replace(text, block) {
3826
+ const spans = blocksOf(text);
3827
+ if (spans.length === 0) {
3828
+ const trimmed = text.replace(/\n+$/, "");
3829
+ return trimmed.length === 0 ? `${block}
3830
+ ` : `${trimmed}
3831
+
3832
+ ${block}
3833
+ `;
3834
+ }
3835
+ return rebuild(text, spans, block);
3836
+ }
3837
+ function remove(text) {
3838
+ const spans = blocksOf(text);
3839
+ if (spans.length === 0) return text;
3840
+ return rebuild(text, spans, null);
3841
+ }
3842
+ function linesOf(text) {
3843
+ const lines = [];
3844
+ let at = 0;
3845
+ while (at <= text.length) {
3846
+ const nl = text.indexOf("\n", at);
3847
+ const end = nl === -1 ? text.length : nl;
3848
+ lines.push({ start: at, end, next: nl === -1 ? text.length + 1 : nl + 1, trimmed: text.slice(at, end).trim() });
3849
+ if (nl === -1) break;
3850
+ at = nl + 1;
3851
+ }
3852
+ return lines;
3853
+ }
3854
+ function blocksOf(text) {
3855
+ const spans = [];
3856
+ let open = null;
3857
+ for (const line of linesOf(text)) {
3858
+ if (line.trimmed === START_MARKER || line.trimmed === LEGACY_START_MARKER) {
3859
+ open = { line, legacy: line.trimmed === LEGACY_START_MARKER };
3860
+ continue;
3861
+ }
3862
+ const closes = open !== null && line.trimmed === (open.legacy ? LEGACY_END_MARKER : END_MARKER);
3863
+ if (open !== null && closes) {
3864
+ spans.push({
3865
+ start: open.line.start,
3866
+ end: line.end,
3867
+ innerStart: Math.min(open.line.next, line.start),
3868
+ innerEnd: line.start,
3869
+ legacy: open.legacy
3870
+ });
3871
+ open = null;
3872
+ }
3873
+ }
3874
+ return spans;
3875
+ }
3876
+ function rebuild(text, spans, replacement) {
3877
+ const parts = [];
3878
+ const first = spans[0];
3879
+ const last = spans[spans.length - 1];
3880
+ if (!first || !last) return text;
3881
+ parts.push(text.slice(0, first.start).replace(/\n+$/, ""));
3882
+ if (replacement !== null) parts.push(replacement);
3883
+ for (let i = 1; i < spans.length; i++) {
3884
+ const previous = spans[i - 1];
3885
+ const current = spans[i];
3886
+ if (!previous || !current) continue;
3887
+ parts.push(text.slice(previous.end, current.start).replace(/^\n+/, "").replace(/\n+$/, ""));
3888
+ }
3889
+ parts.push(text.slice(last.end).replace(/^\n+/, ""));
3890
+ const kept = parts.filter((part) => part.length > 0);
3891
+ if (kept.length === 0) return "";
3892
+ const out = kept.join("\n\n");
3893
+ return out.endsWith("\n") ? out : `${out}
3894
+ `;
3895
+ }
3896
+ function escapeRegExp(value) {
3897
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3898
+ }
3899
+ function namesHandle(line, bare) {
3900
+ if (line.length === 0) return false;
3901
+ return new RegExp(`@${escapeRegExp(bare)}(?![A-Za-z0-9_-])`).test(line);
3902
+ }
3903
+ function templatePattern(template) {
3904
+ if (!template || !template.includes(HANDLE_PLACEHOLDER)) return null;
3905
+ const index = template.indexOf(HANDLE_PLACEHOLDER);
3906
+ const head = template.slice(0, index).split(/\s+/).filter(Boolean);
3907
+ const tail = template.slice(index + HANDLE_PLACEHOLDER.length).split(/\s+/).filter(Boolean);
3908
+ if (head.length > 0) {
3909
+ const words = head.map(escapeRegExp).join("\\s+");
3910
+ return new RegExp(`${words.replace(/@$/, "")}\\s*${HANDLE_CAPTURE}`);
3911
+ }
3912
+ if (tail.length > 0) {
3913
+ const words = tail.slice(0, 3).map(escapeRegExp).join("\\s+");
3914
+ return new RegExp(`${HANDLE_CAPTURE}\\s*${words}`);
3915
+ }
3916
+ return null;
3917
+ }
3918
+ function handleFromWording(body, template) {
3919
+ const patterns = [];
3920
+ const fromTemplate = templatePattern(template);
3921
+ if (fromTemplate) patterns.push(fromTemplate);
3922
+ patterns.push(...OLD_WORDINGS);
3923
+ const flat = body.split(/\s+/).filter(Boolean).join(" ");
3924
+ for (const pattern of patterns) {
3925
+ const match = pattern.exec(flat) ?? pattern.exec(body);
3926
+ if (match?.[1]) return match[1].toLowerCase();
3927
+ }
3928
+ return null;
3929
+ }
3930
+
3931
+ // src/integration/turn-tracker.ts
3932
+ function keyOf(turn) {
3933
+ return turn.kind === "reply" ? `conversation:${turn.conversationId}` : `invite:${turn.inviteId}`;
3934
+ }
3935
+ var TurnTracker = class {
3936
+ now;
3937
+ turns = /* @__PURE__ */ new Map();
3938
+ /** Waits on a turn's end, ended by `release`. */
3939
+ waiters = /* @__PURE__ */ new Map();
3940
+ constructor(options = {}) {
3941
+ this.now = options.now ?? Date.now;
3942
+ }
3943
+ /** Start tracking a turn. Null when one is already running for that conversation or invite. */
3944
+ begin(turn) {
3945
+ const key = keyOf(turn);
3946
+ if (this.turns.has(key)) return null;
3947
+ const handle = { key, turn, startedAt: this.now() };
3948
+ this.turns.set(key, { handle, waitTimedOutAt: null, released: false });
3949
+ return handle;
3950
+ }
3951
+ conversationRunning(conversationId) {
3952
+ return this.turns.has(`conversation:${conversationId}`);
3953
+ }
3954
+ inviteRunning(inviteId) {
3955
+ return this.turns.has(`invite:${inviteId}`);
3956
+ }
3957
+ /** The cards whose conversation has no running turn: the ones a gate may see. */
3958
+ withoutRunning(cards) {
3959
+ return cards.filter((card) => !this.conversationRunning(card.conversation_id));
3960
+ }
3961
+ /** Snapshot for status. */
3962
+ running() {
3963
+ return [...this.turns.values()].map(({ handle, waitTimedOutAt }) => ({
3964
+ ...handle.turn,
3965
+ startedAt: handle.startedAt,
3966
+ waitTimedOutAt
3967
+ }));
3968
+ }
3969
+ get size() {
3970
+ return this.turns.size;
3971
+ }
3972
+ /**
3973
+ * Follow what the runtime reports until it confirms the end, through any
3974
+ * number of `still_running` reports. Resolves with the confirmed end, or
3975
+ * never when the runtime cannot say (until `release`). A rejected report
3976
+ * counts as a failed turn. The turn stays tracked: call `end` once its
3977
+ * outcome is recorded.
3978
+ */
3979
+ async confirmedEnd(handle, done) {
3980
+ if (!this.holds(handle)) return null;
3981
+ const released = new Promise((resolve) => {
3982
+ const list = this.waiters.get(handle.key) ?? [];
3983
+ list.push(() => resolve(null));
3984
+ this.waiters.set(handle.key, list);
3985
+ });
3986
+ let report = done;
3987
+ while (report !== void 0) {
3988
+ let end;
3989
+ try {
3990
+ end = await Promise.race([report, released]);
3991
+ } catch (err) {
3992
+ if (!this.holds(handle)) return null;
3993
+ return { status: "failed", agentchatCalls: null, detail: `the turn's report failed: ${err instanceof Error ? err.message : String(err)}` };
3994
+ }
3995
+ if (end === null || !this.holds(handle)) return null;
3996
+ if (end.status !== "still_running") return end;
3997
+ const entry = this.turns.get(handle.key);
3998
+ entry.waitTimedOutAt = this.now();
3999
+ report = end.next;
4000
+ }
4001
+ return released;
4002
+ }
4003
+ /** Called with every turn `release` lets go of (a loop frees its slot). */
4004
+ onRelease(listener) {
4005
+ this.releaseListeners.add(listener);
4006
+ return () => {
4007
+ this.releaseListeners.delete(listener);
4008
+ };
4009
+ }
4010
+ releaseListeners = /* @__PURE__ */ new Set();
4011
+ /** Whether this turn is still tracked (not ended, not released). Check it after every await before recording. */
4012
+ holds(handle) {
4013
+ const entry = this.turns.get(handle.key);
4014
+ return entry !== void 0 && entry.handle === handle && !entry.released;
4015
+ }
4016
+ /** Stop tracking a turn (its outcome is recorded, or it never started). */
4017
+ end(handle) {
4018
+ const entry = this.turns.get(handle.key);
4019
+ if (entry?.handle === handle) {
4020
+ this.turns.delete(handle.key);
4021
+ this.waiters.delete(handle.key);
4022
+ }
4023
+ }
4024
+ /**
4025
+ * Let go of a turn whose end will not be confirmed (an operator's call). Its
4026
+ * conversation may be gated again; nothing is recorded for it.
4027
+ */
4028
+ release(key) {
4029
+ const entry = this.turns.get(key);
4030
+ if (!entry) return false;
4031
+ entry.released = true;
4032
+ this.turns.delete(key);
4033
+ const waiting = this.waiters.get(key) ?? [];
4034
+ this.waiters.delete(key);
4035
+ for (const wake of waiting) wake();
4036
+ for (const listener of this.releaseListeners) {
4037
+ try {
4038
+ listener(entry.handle);
4039
+ } catch {
4040
+ }
4041
+ }
4042
+ return true;
4043
+ }
4044
+ };
4045
+
4046
+ // src/integration/files.ts
4047
+ var modules = null;
4048
+ var FS_MODULE = "node:fs/promises";
4049
+ var PATH_MODULE = "node:path";
4050
+ function nodeModules() {
4051
+ modules ??= Promise.all([
4052
+ import(
4053
+ /* webpackIgnore: true */
4054
+ /* @vite-ignore */
4055
+ FS_MODULE
4056
+ ),
4057
+ import(
4058
+ /* webpackIgnore: true */
4059
+ /* @vite-ignore */
4060
+ PATH_MODULE
4061
+ )
4062
+ ]).then(([fs, path]) => ({
4063
+ fs: fs.default ?? fs,
4064
+ path: path.default ?? path
4065
+ }));
4066
+ return modules;
4067
+ }
4068
+ var RENAME_RETRY_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
4069
+ var RENAME_ATTEMPTS = 6;
4070
+ var RENAME_DELAY_MS = 20;
4071
+ function isWindows() {
4072
+ return globalThis.process?.platform === "win32";
4073
+ }
4074
+ function randomSuffix() {
4075
+ const bytes = new Uint8Array(6);
4076
+ const cryptoObj = globalThis.crypto;
4077
+ if (cryptoObj?.getRandomValues) cryptoObj.getRandomValues(bytes);
4078
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
4079
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4080
+ }
4081
+ async function renameWithRetry(from, to, options = {}) {
4082
+ const { fs } = await nodeModules();
4083
+ const rename = options.rename ?? ((a, b) => fs.rename(a, b));
4084
+ const attempts = options.retry ?? isWindows() ? RENAME_ATTEMPTS : 1;
4085
+ for (let attempt = 1; ; attempt++) {
4086
+ try {
4087
+ await rename(from, to);
4088
+ return;
4089
+ } catch (err) {
4090
+ const code = err.code;
4091
+ if (attempt >= attempts || code === void 0 || !RENAME_RETRY_CODES.has(code)) throw err;
4092
+ await new Promise((resolve) => setTimeout(resolve, RENAME_DELAY_MS));
4093
+ }
4094
+ }
4095
+ }
4096
+ async function writeAtomic(file, data, options = {}) {
4097
+ const { fs, path } = await nodeModules();
4098
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 448 });
4099
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${randomSuffix()}.tmp`);
4100
+ try {
4101
+ const handle = await fs.open(tmp, "wx", options.mode ?? 438);
4102
+ try {
4103
+ if (options.mode !== void 0) await handle.chmod(options.mode);
4104
+ await handle.writeFile(data);
4105
+ await handle.sync();
4106
+ } finally {
4107
+ await handle.close();
4108
+ }
4109
+ await renameWithRetry(tmp, file, options);
4110
+ } catch (err) {
4111
+ await fs.rm(tmp, { force: true }).catch(() => void 0);
4112
+ throw err;
4113
+ }
4114
+ }
4115
+ async function readBytes(file) {
4116
+ const { fs } = await nodeModules();
4117
+ try {
4118
+ return new Uint8Array(await fs.readFile(file));
4119
+ } catch {
4120
+ return null;
4121
+ }
4122
+ }
4123
+
4124
+ // src/integration/texts-cache.ts
4125
+ var TEXTS_REFRESH_MS = 24 * 60 * 6e4;
4126
+ var TEXTS_RETRY_MS = 5 * 6e4;
4127
+ var TEXTS_RETRY_MAX_MS = 60 * 6e4;
4128
+ var TEXTS_FETCH_TIMEOUT_MS = 1e4;
4129
+ var CACHE_FILE_VERSION = 1;
4130
+ function isTexts(value) {
4131
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4132
+ const t = value;
4133
+ const manual = t.manual;
4134
+ const nonEmpty = (v) => typeof v === "string" && v.trim().length > 0;
4135
+ return typeof t.version === "string" && typeof manual === "object" && manual !== null && typeof manual.url === "string" && typeof manual.version === "string" && nonEmpty(t.wake_instruction) && nonEmpty(t.invite_prompt) && nonEmpty(t.identity_line) && typeof t.identity_line_template === "string";
4136
+ }
4137
+ var TextsCache = class {
4138
+ runtime;
4139
+ client;
4140
+ filePath;
4141
+ refreshMs;
4142
+ retryMs;
4143
+ retryMaxMs;
4144
+ fetchTimeoutMs;
4145
+ onError;
4146
+ now;
4147
+ _setTimeout;
4148
+ _clearTimeout;
4149
+ listeners = /* @__PURE__ */ new Set();
4150
+ texts = null;
4151
+ _source = "none";
4152
+ _fetchedAt = null;
4153
+ _lastError = null;
4154
+ failures = 0;
4155
+ serverSeen = false;
4156
+ inFlight = null;
4157
+ timer = null;
4158
+ started = false;
4159
+ stopped = false;
4160
+ constructor(options) {
4161
+ this.client = options.client;
4162
+ this.runtime = options.runtime;
4163
+ this.filePath = options.filePath ?? null;
4164
+ this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS;
4165
+ this.retryMs = options.retryMs ?? TEXTS_RETRY_MS;
4166
+ this.retryMaxMs = Math.max(this.retryMs, options.retryMaxMs ?? TEXTS_RETRY_MAX_MS);
4167
+ this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS;
4168
+ this.onError = options.onError ?? (() => void 0);
4169
+ this.now = options.now ?? Date.now;
4170
+ this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
4171
+ this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle));
4172
+ }
4173
+ /** The texts in hand, or null until a copy exists. No network. */
4174
+ current() {
4175
+ return this.texts;
4176
+ }
4177
+ /** Where `current()` came from: this process's fetch, the file, or nowhere yet. */
4178
+ get source() {
4179
+ return this._source;
4180
+ }
4181
+ /** When the current copy was served (also for a copy read from the file). */
4182
+ get fetchedAt() {
4183
+ return this._fetchedAt;
4184
+ }
4185
+ /** The last fetch failure, cleared by the next success. */
4186
+ get lastError() {
4187
+ return this._lastError;
4188
+ }
4189
+ /** The API base the texts are fetched from — what a manual download is pinned to. */
4190
+ get apiBase() {
4191
+ return typeof this.client.baseUrl === "string" ? this.client.baseUrl : null;
4192
+ }
4193
+ /** Called with every copy that differs from the one before (from the file or the server). */
4194
+ onChange(listener) {
4195
+ this.listeners.add(listener);
4196
+ return () => {
4197
+ this.listeners.delete(listener);
4198
+ };
4199
+ }
4200
+ /**
4201
+ * Read the file, make one fetch, arm the timer. Resolves with what is in
4202
+ * hand once the first attempt has finished; never throws.
4203
+ */
4204
+ async start() {
4205
+ if (this.started) return this.texts;
4206
+ this.started = true;
4207
+ this.stopped = false;
4208
+ await this.loadFile();
4209
+ await this.refresh();
4210
+ return this.texts;
4211
+ }
4212
+ stop() {
4213
+ this.stopped = true;
4214
+ if (this.timer !== null) {
4215
+ this._clearTimeout(this.timer);
4216
+ this.timer = null;
4217
+ }
4218
+ }
4219
+ /**
4220
+ * The texts for a cycle: what is in hand, after one more fetch attempt if
4221
+ * the server has not answered yet in this process. Null only when the
4222
+ * server is unreachable and no copy was ever kept.
4223
+ */
4224
+ async ensure() {
4225
+ if (!this.serverSeen && !this.stopped) await this.refresh();
4226
+ return this.texts;
4227
+ }
4228
+ /** Fetch now (coalesced with one in flight), keep it, arm the next attempt. Resolves whether the server answered. */
4229
+ refresh() {
4230
+ if (this.inFlight !== null) return this.inFlight;
4231
+ this.inFlight = this.fetchOnce().finally(() => {
4232
+ this.inFlight = null;
4233
+ });
4234
+ return this.inFlight;
4235
+ }
4236
+ async fetchOnce() {
4237
+ try {
4238
+ const served = await this.client.texts.get({
4239
+ runtime: this.runtime,
4240
+ timeoutMs: this.fetchTimeoutMs,
4241
+ retry: "never"
4242
+ });
4243
+ if (!isTexts(served)) throw new Error("GET /v1/texts: the answer is not a text set");
4244
+ const runtime = served.runtime;
4245
+ if (runtime !== void 0 && runtime !== this.runtime) {
4246
+ throw new Error(`GET /v1/texts: texts for ${String(runtime)}, asked for ${this.runtime}`);
4247
+ }
4248
+ if (this.stopped) return true;
4249
+ const fetchedAt = new Date(this.now()).toISOString();
4250
+ this.serverSeen = true;
4251
+ this.failures = 0;
4252
+ this._lastError = null;
4253
+ this.adopt(served, "server", fetchedAt);
4254
+ await this.saveFile(served, fetchedAt);
4255
+ this.arm(this.refreshMs);
4256
+ return true;
4257
+ } catch (err) {
4258
+ if (this.stopped) return false;
4259
+ const message = err instanceof Error ? err.message : String(err);
4260
+ this.failures += 1;
4261
+ if (message !== this._lastError) {
4262
+ this._lastError = message;
4263
+ this.report(new Error(`texts: ${message} \u2014 ${this.texts === null ? "no texts yet" : `keeping the ${this._source} copy from ${this._fetchedAt ?? "?"}`}`));
4264
+ }
4265
+ this.arm(Math.min(this.retryMaxMs, this.retryMs * 2 ** Math.min(this.failures - 1, 20)));
4266
+ return false;
4267
+ }
4268
+ }
4269
+ adopt(texts, source, fetchedAt) {
4270
+ const changed = this.texts === null || canonicalJson(this.texts) !== canonicalJson(texts);
4271
+ this.texts = texts;
4272
+ this._source = source;
4273
+ this._fetchedAt = fetchedAt;
4274
+ if (!changed) return;
4275
+ for (const listener of this.listeners) {
4276
+ try {
4277
+ listener(texts, source);
4278
+ } catch (err) {
4279
+ this.report(err instanceof Error ? err : new Error(String(err)));
4280
+ }
4281
+ }
4282
+ }
4283
+ async loadFile() {
4284
+ if (this.filePath === null || this.texts !== null) return;
4285
+ const bytes = await readBytes(this.filePath).catch(() => null);
4286
+ if (bytes === null) return;
4287
+ try {
4288
+ const entry = JSON.parse(new TextDecoder().decode(bytes));
4289
+ if (entry.version !== CACHE_FILE_VERSION || entry.runtime !== this.runtime) return;
4290
+ if (typeof entry.fetched_at !== "string" || !isTexts(entry.texts)) return;
4291
+ this.adopt(entry.texts, "cache", entry.fetched_at);
4292
+ } catch {
4293
+ }
4294
+ }
4295
+ async saveFile(texts, fetchedAt) {
4296
+ if (this.filePath === null) return;
4297
+ const entry = { version: CACHE_FILE_VERSION, runtime: this.runtime, fetched_at: fetchedAt, texts };
4298
+ try {
4299
+ await writeAtomic(this.filePath, `${JSON.stringify(entry, null, 2)}
4300
+ `, { mode: 384 });
4301
+ } catch (err) {
4302
+ this.report(new Error(`texts: the cache file could not be written: ${err instanceof Error ? err.message : String(err)}`));
4303
+ }
4304
+ }
4305
+ arm(ms) {
4306
+ if (this.stopped || !this.started) return;
4307
+ if (this.timer !== null) this._clearTimeout(this.timer);
4308
+ this.timer = this._setTimeout(() => {
4309
+ this.timer = null;
4310
+ void this.refresh();
4311
+ }, ms);
4312
+ this.timer.unref?.();
4313
+ }
4314
+ report(error) {
4315
+ try {
4316
+ this.onError(error);
4317
+ } catch {
4318
+ }
4319
+ }
4320
+ };
4321
+
4322
+ // src/integration/manual-sync.ts
4323
+ var MANUAL_MAX_BYTES = 512 * 1024;
4324
+ var MANUAL_FETCH_TIMEOUT_MS = 1e4;
4325
+ var MANUAL_MAX_REDIRECTS = 3;
4326
+ var MANUAL_SKILL_NAME = "agentchat";
4327
+ function manualFrontMatter(raw) {
4328
+ const text = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replace(/\r\n/g, "\n");
4329
+ if (!text.startsWith("---\n")) return null;
4330
+ let close = text.indexOf("\n---", 3);
4331
+ while (close >= 0 && text.charAt(close + 4) !== "\n" && close + 4 !== text.length) close = text.indexOf("\n---", close + 1);
4332
+ if (close < 0) return null;
4333
+ const fields = /* @__PURE__ */ new Map();
4334
+ for (const line of text.slice(4, close).split("\n")) {
4335
+ const match = /^([A-Za-z0-9_-]+):[ \t]*(.*?)[ \t]*$/.exec(line);
4336
+ if (match === null) continue;
4337
+ const value = match[2] ?? "";
4338
+ fields.set(match[1] ?? "", /^(["']).*\1$/.test(value) ? value.slice(1, -1) : value);
4339
+ }
4340
+ return fields;
4341
+ }
4342
+ function manualVersion(text) {
4343
+ const version = manualFrontMatter(text)?.get("version");
4344
+ return version !== void 0 && version.length > 0 ? version : null;
4345
+ }
4346
+ async function syncManual(options) {
4347
+ const file = options.path;
4348
+ const served = options.served;
4349
+ const local = await readLocal(file);
4350
+ const fallback = toBytes(options.fallback);
4351
+ const base = { path: file, previous: local.version, served: served?.version ?? null, url: served?.url ?? null };
4352
+ let tampered = false;
4353
+ let error = null;
4354
+ if (served !== null) {
4355
+ const hash = announcedHash(served);
4356
+ if (hash instanceof Error) {
4357
+ error = hash.message;
4358
+ } else {
4359
+ if (local.exists && local.version === served.version) {
4360
+ if (hash === null || await sha256(local.bytes) === hash) {
4361
+ return { ...base, tampered, state: "current", version: local.version, source: null, written: false, upToDate: true, error: null };
4362
+ }
4363
+ tampered = true;
4364
+ }
4365
+ const origin = manualOrigin(options.apiBase);
4366
+ if (!origin.ok) {
4367
+ error = origin.reason;
4368
+ } else {
4369
+ let bytes = null;
4370
+ let source = "fallback";
4371
+ if (fallback !== null && await isAnnounced(fallback, served, hash)) {
4372
+ bytes = fallback;
4373
+ } else {
4374
+ try {
4375
+ bytes = await downloadManual(served, hash, origin, options);
4376
+ source = "download";
4377
+ } catch (err) {
4378
+ error = describe2(err);
4379
+ }
4380
+ }
4381
+ if (bytes !== null) {
4382
+ try {
4383
+ await writeAtomic(file, bytes, { mode: 420, ...options.rename ? { rename: options.rename } : {} });
4384
+ return { ...base, tampered, state: "updated", version: served.version, source, written: true, upToDate: true, error: null };
4385
+ } catch (err) {
4386
+ error = `could not write ${file}: ${describe2(err)}`;
4387
+ }
4388
+ }
4389
+ }
4390
+ }
4391
+ }
4392
+ if (local.exists) {
4393
+ return { ...base, tampered, state: "kept", version: local.version, source: null, written: false, upToDate: served === null ? null : false, error };
4394
+ }
4395
+ if (fallback === null) {
4396
+ return { ...base, tampered, state: "failed", version: null, source: null, written: false, upToDate: served === null ? null : false, error: error ?? "no manual could be had and no fallback was given" };
4397
+ }
4398
+ try {
4399
+ await writeAtomic(file, fallback, { mode: 420, ...options.rename ? { rename: options.rename } : {} });
4400
+ } catch (err) {
4401
+ return { ...base, tampered, state: "failed", version: null, source: null, written: false, upToDate: served === null ? null : false, error: describe2(err) };
4402
+ }
4403
+ const fallbackIsServed = served !== null && await isAnnounced(fallback, served, announcedHashOrNull(served));
4404
+ return {
4405
+ ...base,
4406
+ tampered,
4407
+ state: "fallback",
4408
+ version: manualVersion(decode(fallback)),
4409
+ source: "fallback",
4410
+ written: true,
4411
+ upToDate: served === null ? null : fallbackIsServed,
4412
+ error
4413
+ };
4414
+ }
4415
+ var ManualSync = class {
4416
+ options;
4417
+ controller = new AbortController();
4418
+ chain = Promise.resolve();
4419
+ unsubscribe = null;
4420
+ lastError = null;
4421
+ last = null;
4422
+ constructor(options) {
4423
+ this.options = options;
4424
+ }
4425
+ /** The latest result, for an integration's status. */
4426
+ get result() {
4427
+ return this.last;
4428
+ }
4429
+ /** Sync now, then follow every texts change. Resolves with the first result. */
4430
+ start() {
4431
+ if (this.unsubscribe === null) {
4432
+ this.unsubscribe = this.options.texts.onChange((texts) => {
4433
+ void this.sync(texts.manual);
4434
+ });
4435
+ }
4436
+ return this.sync();
4437
+ }
4438
+ stop() {
4439
+ this.unsubscribe?.();
4440
+ this.unsubscribe = null;
4441
+ this.controller.abort();
4442
+ }
4443
+ /** One serialised sync against `served` (default: the texts in hand). Null when nothing is in hand or stopped. */
4444
+ sync(served = this.options.texts.current()?.manual ?? null) {
4445
+ const next = this.chain.then(async () => {
4446
+ if (served === null || this.controller.signal.aborted) return null;
4447
+ const result = await syncManual({
4448
+ path: this.options.targetPath,
4449
+ served,
4450
+ apiBase: this.options.texts.apiBase,
4451
+ signal: this.controller.signal,
4452
+ ...this.options.fallback !== void 0 ? { fallback: this.options.fallback } : {},
4453
+ ...this.options.fetch !== void 0 ? { fetch: this.options.fetch } : {},
4454
+ ...this.options.timeoutMs !== void 0 ? { timeoutMs: this.options.timeoutMs } : {},
4455
+ ...this.options.maxBytes !== void 0 ? { maxBytes: this.options.maxBytes } : {}
4456
+ });
4457
+ if (this.controller.signal.aborted) return result;
4458
+ this.last = result;
4459
+ if (result.upToDate === true || result.error !== this.lastError) {
4460
+ try {
4461
+ this.options.onResult?.(result);
4462
+ } catch {
4463
+ }
4464
+ }
4465
+ this.lastError = result.upToDate === true ? null : result.error;
4466
+ return result;
4467
+ });
4468
+ this.chain = next.catch(() => void 0);
4469
+ return next;
4470
+ }
4471
+ };
4472
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
4473
+ var MANUAL_HOME = "agentchat.me";
4474
+ function manualOrigin(apiBase) {
4475
+ if (apiBase === null) return { ok: false, reason: "no API base is known for the served texts" };
4476
+ let url;
4477
+ try {
4478
+ url = new URL(apiBase);
4479
+ } catch {
4480
+ return { ok: false, reason: `the API base ${apiBase} is not a URL` };
4481
+ }
4482
+ if (url.protocol === "https:") return { ok: true, host: url.hostname, plainLoopback: false };
4483
+ if (url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname)) return { ok: true, host: url.hostname, plainLoopback: true };
4484
+ return { ok: false, reason: `the served texts came from ${url.origin}, which is not HTTPS, so the manual is not downloaded` };
4485
+ }
4486
+ function refusal(url, origin) {
4487
+ const host = url.hostname;
4488
+ if (host !== MANUAL_HOME && !host.endsWith(`.${MANUAL_HOME}`) && host !== origin.host) {
4489
+ return `${url.host} is neither ${MANUAL_HOME} nor the API's own host`;
4490
+ }
4491
+ if (url.username !== "" || url.password !== "") return "the address carries credentials";
4492
+ if (url.protocol === "https:") return null;
4493
+ if (url.protocol === "http:" && origin.plainLoopback && LOOPBACK_HOSTS.has(host)) return null;
4494
+ return `${url.protocol}// to ${url.host} \u2014 the manual is fetched over HTTPS only (plain HTTP only to loopback, from a loopback API base)`;
4495
+ }
4496
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
4497
+ var SHA256_HEX = /^[0-9a-f]{64}$/;
4498
+ async function sha256(bytes) {
4499
+ const subtle = globalThis.crypto?.subtle;
4500
+ if (!subtle) throw new Error("Web Crypto (globalThis.crypto.subtle) is not available");
4501
+ const digest = new Uint8Array(await subtle.digest("SHA-256", bytes));
4502
+ return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
4503
+ }
4504
+ function announcedHash(served) {
4505
+ const raw = served.sha256;
4506
+ if (raw === void 0 || raw === null) return null;
4507
+ const hash = typeof raw === "string" ? raw.trim().toLowerCase() : "";
4508
+ return SHA256_HEX.test(hash) ? hash : new Error("the announced sha256 is not a hex sha256");
4509
+ }
4510
+ function announcedHashOrNull(served) {
4511
+ const hash = announcedHash(served);
4512
+ return hash instanceof Error ? null : hash;
4513
+ }
4514
+ async function isAnnounced(bytes, served, hash) {
4515
+ return manualVersion(decode(bytes)) === served.version && (hash === null || await sha256(bytes) === hash);
4516
+ }
4517
+ async function readLocal(file) {
4518
+ const bytes = await readBytes(file).catch(() => null);
4519
+ if (bytes === null) return { exists: false, bytes: new Uint8Array(0), version: null };
4520
+ return { exists: true, bytes, version: manualVersion(decode(bytes)) };
4521
+ }
4522
+ function toBytes(value) {
4523
+ if (value === null || value === void 0) return null;
4524
+ return typeof value === "string" ? new TextEncoder().encode(value) : value;
4525
+ }
4526
+ function decode(bytes) {
4527
+ return new TextDecoder("utf-8").decode(bytes);
4528
+ }
4529
+ async function downloadManual(served, hash, origin, options) {
4530
+ let url;
4531
+ try {
4532
+ url = new URL(served.url);
4533
+ } catch {
4534
+ throw new Error(`the announced address is not a URL: ${served.url}`);
4535
+ }
4536
+ const refused = refusal(url, origin);
4537
+ if (refused !== null) throw new Error(`refusing ${url.href}: ${refused}`);
4538
+ const maxBytes = options.maxBytes ?? MANUAL_MAX_BYTES;
4539
+ const timeoutMs = options.timeoutMs ?? MANUAL_FETCH_TIMEOUT_MS;
4540
+ const timeout = AbortSignal.timeout(timeoutMs);
4541
+ const signal = options.signal !== void 0 ? anySignal(options.signal, timeout) : timeout;
4542
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
4543
+ let bytes;
4544
+ try {
4545
+ for (let hop = 0; ; hop++) {
4546
+ const response = await doFetch(url.href, {
4547
+ method: "GET",
4548
+ redirect: "manual",
4549
+ signal,
4550
+ headers: { accept: "text/markdown, text/plain;q=0.9, */*;q=0.1" }
4551
+ });
4552
+ if (REDIRECT_STATUSES.has(response.status)) {
4553
+ await response.body?.cancel().catch(() => void 0);
4554
+ if (hop >= MANUAL_MAX_REDIRECTS) throw new Error(`more than ${MANUAL_MAX_REDIRECTS} redirects from ${served.url}`);
4555
+ const location = response.headers.get("location");
4556
+ if (location === null || location === "") throw new Error(`HTTP ${response.status} from ${url.href} with no Location`);
4557
+ let next;
4558
+ try {
4559
+ next = new URL(location, url);
4560
+ } catch {
4561
+ throw new Error(`HTTP ${response.status} from ${url.href} to an unparseable Location`);
4562
+ }
4563
+ const why = refusal(next, origin);
4564
+ if (why !== null) throw new Error(`redirected to ${next.href}: ${why}`);
4565
+ url = next;
4566
+ continue;
4567
+ }
4568
+ if (response.type === "opaqueredirect" || response.status === 0) throw new Error(`an opaque redirect from ${url.href}`);
4569
+ if (response.url !== "" && response.url !== url.href) {
4570
+ const why = refusal(new URL(response.url), origin);
4571
+ if (why !== null) throw new Error(`redirected to ${response.url}: ${why}`);
4572
+ }
4573
+ if (!response.ok) throw new Error(`HTTP ${response.status} from ${url.href}`);
4574
+ const declared = Number(response.headers.get("content-length") ?? Number.NaN);
4575
+ if (Number.isFinite(declared) && declared > maxBytes) throw new Error(`${declared} bytes declared, over the ${maxBytes}-byte cap`);
4576
+ bytes = await readCapped(response, maxBytes);
4577
+ break;
4578
+ }
4579
+ } catch (err) {
4580
+ if (timeout.aborted) throw new Error(`no answer from ${served.url} within ${timeoutMs} ms`);
4581
+ throw err;
4582
+ }
4583
+ let text;
4584
+ try {
4585
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
4586
+ } catch {
4587
+ throw new Error("the body is not UTF-8 text");
4588
+ }
4589
+ checkManualText(text, served.version);
4590
+ if (hash !== null) {
4591
+ const got = await sha256(bytes);
4592
+ if (got !== hash) throw new Error(`the body's sha256 is ${got}, the server announced ${hash}`);
4593
+ }
4594
+ return bytes;
4595
+ }
4596
+ async function readCapped(response, maxBytes) {
4597
+ const reader = response.body?.getReader();
4598
+ if (reader === void 0) return new Uint8Array(0);
4599
+ const chunks = [];
4600
+ let total = 0;
4601
+ for (; ; ) {
4602
+ const { done, value } = await reader.read();
4603
+ if (done) break;
4604
+ total += value.byteLength;
4605
+ if (total > maxBytes) {
4606
+ await reader.cancel().catch(() => void 0);
4607
+ throw new Error(`the body is over the ${maxBytes}-byte cap`);
4608
+ }
4609
+ chunks.push(value);
4610
+ }
4611
+ const out = new Uint8Array(total);
4612
+ let offset = 0;
4613
+ for (const chunk of chunks) {
4614
+ out.set(chunk, offset);
4615
+ offset += chunk.byteLength;
4616
+ }
4617
+ return out;
4618
+ }
4619
+ function checkManualText(text, announced) {
4620
+ if (text.includes("\0")) throw new Error("the body is not text");
4621
+ const fields = manualFrontMatter(text);
4622
+ if (fields === null) throw new Error("the body has no front matter \u2014 not the manual");
4623
+ if (fields.get("name") !== MANUAL_SKILL_NAME) throw new Error(`the front matter names "${fields.get("name") ?? ""}", not the ${MANUAL_SKILL_NAME} skill`);
4624
+ const version = manualVersion(text);
4625
+ if (version !== announced) throw new Error(`the body is version ${version ?? "(none)"}, the server announced ${announced}`);
4626
+ }
4627
+ function anySignal(a, b) {
4628
+ const any = AbortSignal.any;
4629
+ if (typeof any === "function") return any([a, b]);
4630
+ const controller = new AbortController();
4631
+ const abort = () => controller.abort();
4632
+ if (a.aborted || b.aborted) controller.abort();
4633
+ a.addEventListener("abort", abort, { once: true });
4634
+ b.addEventListener("abort", abort, { once: true });
4635
+ return controller.signal;
4636
+ }
4637
+ function describe2(err) {
4638
+ if (!(err instanceof Error)) return String(err);
4639
+ const cause = err.cause;
4640
+ const detail = cause instanceof Error ? cause.code ?? cause.message : null;
4641
+ return detail !== null && !err.message.includes(detail) ? `${err.message} (${detail})` : err.message;
4642
+ }
4643
+
4644
+ // src/integration/probe.ts
4645
+ var HOSTED_MCP_PATH = "/mcp";
4646
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
4647
+ var REQUIRED_HOSTED_TOOLS = ["agentchat_inbox", "agentchat_decide"];
4648
+ function hostedMcpUrl(apiBase) {
4649
+ return `${apiBase.replace(/\/+$/, "")}${HOSTED_MCP_PATH}`;
4650
+ }
4651
+ async function probeHostedTools(options) {
4652
+ const fetchImpl = options.fetch ?? fetch;
4653
+ const controller = new AbortController();
4654
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 1e4);
4655
+ timer.unref?.();
4656
+ const headers = {
4657
+ authorization: `Bearer ${options.apiKey}`,
4658
+ "content-type": "application/json",
4659
+ accept: "application/json, text/event-stream",
4660
+ ...clientIdentityHeaders(options.clientIdentity)
4661
+ };
4662
+ const call = async (id, method, params, extra = {}) => {
4663
+ const res = await fetchImpl(hostedMcpUrl(options.apiBase), {
4664
+ method: "POST",
4665
+ headers: { ...headers, ...extra },
4666
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
4667
+ signal: controller.signal
4668
+ });
4669
+ const text = await res.text();
4670
+ return { res, result: readResult(text) };
4671
+ };
4672
+ try {
4673
+ const init = await call(1, "initialize", {
4674
+ protocolVersion: MCP_PROTOCOL_VERSION,
4675
+ capabilities: {},
4676
+ clientInfo: { name: options.clientIdentity?.name ?? "typescript_sdk", version: options.clientIdentity?.version ?? "0" }
4677
+ });
4678
+ if (!init.res.ok) {
4679
+ return {
4680
+ ok: false,
4681
+ status: init.res.status,
4682
+ error: init.res.status === 401 ? "the key does not authenticate against the hosted MCP server" : `HTTP ${init.res.status}`
4683
+ };
4684
+ }
4685
+ if (!init.result) return { ok: false, status: init.res.status, error: "no initialize result in the answer" };
4686
+ const serverInfo = init.result.serverInfo ?? {};
4687
+ const protocolVersion = typeof init.result.protocolVersion === "string" ? init.result.protocolVersion : MCP_PROTOCOL_VERSION;
4688
+ const session = init.res.headers.get("mcp-session-id");
4689
+ const facts = {
4690
+ ...typeof serverInfo.name === "string" ? { serverName: serverInfo.name } : {},
4691
+ ...typeof serverInfo.version === "string" ? { serverVersion: serverInfo.version } : {},
4692
+ protocolVersion
4693
+ };
4694
+ const list = await call(2, "tools/list", {}, {
4695
+ "mcp-protocol-version": protocolVersion,
4696
+ ...session ? { "mcp-session-id": session } : {}
4697
+ });
4698
+ if (!list.res.ok) return { ok: false, status: list.res.status, ...facts, error: `tools/list: HTTP ${list.res.status}` };
4699
+ const raw = list.result?.tools;
4700
+ if (!Array.isArray(raw)) return { ok: false, status: list.res.status, ...facts, error: "no tools/list result in the answer" };
4701
+ const tools = raw.flatMap(
4702
+ (tool) => typeof tool === "object" && tool !== null && typeof tool.name === "string" ? [tool.name] : []
4703
+ );
4704
+ const missing = (options.require ?? REQUIRED_HOSTED_TOOLS).filter((name) => !tools.includes(name));
4705
+ return {
4706
+ ok: missing.length === 0,
4707
+ status: list.res.status,
4708
+ ...facts,
4709
+ tools,
4710
+ missing,
4711
+ ...missing.length > 0 ? { error: `the hosted tools do not list ${missing.join(", ")}` } : {}
4712
+ };
4713
+ } catch (err) {
4714
+ return { ok: false, error: controller.signal.aborted ? "no answer from the hosted MCP server in time" : err instanceof Error ? err.message : String(err) };
4715
+ } finally {
4716
+ clearTimeout(timer);
4717
+ }
4718
+ }
4719
+ function readResult(text) {
4720
+ const candidates = [];
4721
+ const trimmed = text.trim();
4722
+ if (trimmed.startsWith("{")) candidates.push(trimmed);
4723
+ for (const line of text.split(/\r?\n/)) {
4724
+ if (line.startsWith("data:")) candidates.push(line.slice(5).trim());
4725
+ }
4726
+ for (const candidate of candidates) {
4727
+ try {
4728
+ const parsed = JSON.parse(candidate);
4729
+ const result = parsed.result;
4730
+ if (result && typeof result === "object" && !Array.isArray(result)) return result;
4731
+ } catch {
4732
+ }
4733
+ }
4734
+ return null;
4735
+ }
4736
+
4737
+ // src/integration/receive-loop.ts
4738
+ var TRAY_LIMIT = 50;
4739
+ var SILENT_MEMORY = 1e3;
4740
+ var PACE_MS = 6e4;
4741
+ var TURN_OVERDUE_MS = 30 * 6e4;
4742
+ var NO_PROGRESS_BACKOFF_MS = 1e3;
4743
+ var NO_PROGRESS_BACKOFF_MAX_MS = 6e4;
4744
+ var GATE_CALL_TIMEOUT_MS = 6e4;
4745
+ var CYCLE_TIMEOUT_MS = 10 * 6e4;
4746
+ var RECENT_CYCLES = 20;
4747
+ var Pacer = class {
4748
+ constructor(paceMs, now2) {
4749
+ this.paceMs = paceMs;
4750
+ this.now = now2;
4751
+ }
4752
+ paceMs;
4753
+ now;
4754
+ until = /* @__PURE__ */ new Map();
4755
+ hold(key, anchor) {
4756
+ this.until.delete(key);
4757
+ this.until.set(key, { anchor, until: this.now() + this.paceMs });
4758
+ while (this.until.size > SILENT_MEMORY) {
4759
+ const oldest = this.until.keys().next().value;
4760
+ if (oldest === void 0) break;
4761
+ this.until.delete(oldest);
4762
+ }
4763
+ }
4764
+ held(key, anchor) {
4765
+ const entry = this.until.get(key);
4766
+ if (!entry) return false;
4767
+ if (entry.anchor !== anchor || this.now() >= entry.until) {
4768
+ this.until.delete(key);
4769
+ return false;
4770
+ }
4771
+ return true;
4772
+ }
4773
+ release(key) {
4774
+ this.until.delete(key);
4775
+ }
4776
+ releaseInvites() {
4777
+ for (const key of [...this.until.keys()]) if (key.startsWith("invite:")) this.until.delete(key);
4778
+ }
4779
+ };
4780
+ var ReceiveLoop = class {
4781
+ options;
4782
+ client;
4783
+ coalescer;
4784
+ tracker;
4785
+ pacer;
4786
+ maxTurns;
4787
+ now;
4788
+ _setTimeout;
4789
+ _clearTimeout;
4790
+ abort = new AbortController();
4791
+ realtime;
4792
+ unsubscribe = [];
4793
+ silent = /* @__PURE__ */ new Map();
4794
+ /** When a single-run invite's silent run was counted (D5 pacing in single-run mode). */
4795
+ silentAt = /* @__PURE__ */ new Map();
4796
+ paceMs;
4797
+ waiting = [];
4798
+ /** Conversations whose verdict a gate call is recording right now (an abandoned cycle's included). */
4799
+ recordsInFlight = /* @__PURE__ */ new Set();
4800
+ /** Turns holding a slot (admitted, not yet ended or released). */
4801
+ slotted = /* @__PURE__ */ new Set();
4802
+ handle;
4803
+ started = false;
4804
+ stopped = false;
4805
+ heldWhileRunning = false;
4806
+ activeTurns = 0;
4807
+ noProgressStreak = 0;
4808
+ moreTimer = null;
4809
+ lastCycle = null;
4810
+ recentCycles = [];
4811
+ cycleToken = 0;
4812
+ /** The running cycle's controller: aborted by stop() too, so a gate mid-way records nothing more. */
4813
+ cycleAbort = null;
4814
+ gateCallTimeoutMs;
4815
+ cycleTimeoutMs;
4816
+ lastError = null;
4817
+ counts = {
4818
+ frames: 0,
4819
+ echoes: 0,
4820
+ turnsStarted: 0,
4821
+ turnsRefused: 0,
4822
+ turnsQueued: 0,
4823
+ inviteTurnsStarted: 0,
4824
+ runsStarted: 0,
4825
+ runsCompleted: 0,
4826
+ runsFailed: 0,
4827
+ runsNotStarted: 0,
4828
+ outcomeRecordFailures: 0
4829
+ };
4830
+ outcomes = {};
4831
+ pendingWork = /* @__PURE__ */ new Set();
4832
+ constructor(options) {
4833
+ if (options.mode === "gateCall" && (!options.callModel || !options.startTurn)) {
4834
+ throw new Error("ReceiveLoop: gateCall mode needs callModel and startTurn");
4835
+ }
4836
+ if (options.mode === "singleRun" && !options.startRun) {
4837
+ throw new Error("ReceiveLoop: singleRun mode needs startRun");
4838
+ }
4839
+ const maxTurns = options.maxConcurrentTurns ?? 1;
4840
+ if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new RangeError("ReceiveLoop: maxConcurrentTurns must be an integer >= 1");
4841
+ this.options = options;
4842
+ this.client = options.client;
4843
+ this.now = options.now ?? Date.now;
4844
+ this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
4845
+ this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
4846
+ this.maxTurns = maxTurns;
4847
+ this.gateCallTimeoutMs = timeoutOption(options.gateCallTimeoutMs, GATE_CALL_TIMEOUT_MS, "gateCallTimeoutMs");
4848
+ this.cycleTimeoutMs = timeoutOption(options.cycleTimeoutMs, CYCLE_TIMEOUT_MS, "cycleTimeoutMs");
4849
+ this.handle = options.handle ? normalizeHandle(options.handle) : null;
4850
+ this.tracker = options.tracker ?? new TurnTracker({ now: this.now });
4851
+ this.unsubscribe.push(this.tracker.onRelease((handle) => this.releaseSlot(handle)));
4852
+ this.paceMs = options.paceMs ?? PACE_MS;
4853
+ this.pacer = new Pacer(this.paceMs, this.now);
4854
+ this.coalescer = new WakeCoalescer({
4855
+ onCycle: () => this.cycle(),
4856
+ onError: (err) => this.fail(err),
4857
+ ...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
4858
+ ...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
4859
+ now: this.now,
4860
+ ...options.setTimeout ? { setTimeout: options.setTimeout } : {},
4861
+ ...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
4862
+ });
4863
+ const socket = options.socket;
4864
+ if (socket === null) this.realtime = null;
4865
+ else if (socket instanceof RealtimeClient) this.realtime = socket;
4866
+ else {
4867
+ this.realtime = new RealtimeClient({
4868
+ apiKey: socket.apiKey,
4869
+ baseUrl: socket.baseUrl ?? wsBase(this.client.baseUrl),
4870
+ client: this.client,
4871
+ ackOnReceipt: true,
4872
+ capabilities: { heartbeat: true, rewake: true },
4873
+ ...socket.clientIdentity ? { clientIdentity: socket.clientIdentity } : {},
4874
+ ...socket.webSocket ? { webSocket: socket.webSocket } : {},
4875
+ ...socket.reconnectInterval !== void 0 ? { reconnectInterval: socket.reconnectInterval } : {},
4876
+ ...socket.maxReconnectInterval !== void 0 ? { maxReconnectInterval: socket.maxReconnectInterval } : {}
4877
+ });
4878
+ }
4879
+ }
4880
+ /** Attach to the socket and connect it; with no socket, wait for `wake()`. Resolves once the connect loop has started. */
4881
+ async start() {
4882
+ if (this.started || this.stopped) return;
4883
+ this.started = true;
4884
+ const rt = this.realtime;
4885
+ if (rt === null) return;
4886
+ this.unsubscribe.push(
4887
+ rt.on("message.new", (message) => this.onMessage(message)),
4888
+ rt.on("wake", (frame) => this.onWakeFrame(frame.payload)),
4889
+ rt.on("group.invite.received", () => {
4890
+ this.counts.frames += 1;
4891
+ this.wakeFrom("invite");
4892
+ }),
4893
+ rt.onConnect(() => this.wakeFrom("connect")),
4894
+ rt.onError((error) => this.emit({ type: "error", error }))
4895
+ );
4896
+ try {
4897
+ await rt.connect();
4898
+ } catch (err) {
4899
+ this.fail(err);
4900
+ }
4901
+ }
4902
+ /** A wake the integration heard itself (a wake webhook, a timer of its own). */
4903
+ wake() {
4904
+ this.wakeFrom("external");
4905
+ }
4906
+ /**
4907
+ * Stop: no new cycles or turns, waiting turns dropped (their cards stay on
4908
+ * the tray), the socket closed, running turns and runs signalled through
4909
+ * their `AbortSignal`. Resolves when the running cycle and any recording
4910
+ * already under way have finished. A turn that ends later still has its
4911
+ * outcome recorded.
4912
+ */
4913
+ async stop() {
4914
+ if (this.stopped) return;
4915
+ this.stopped = true;
4916
+ this.coalescer.stop();
4917
+ this.clearMoreTimer();
4918
+ this.abort.abort();
4919
+ this.cycleAbort?.abort();
4920
+ for (const { handle } of this.waiting.splice(0)) this.tracker.end(handle);
4921
+ for (const off of this.unsubscribe.splice(0)) {
4922
+ try {
4923
+ off();
4924
+ } catch {
4925
+ }
4926
+ }
4927
+ try {
4928
+ this.realtime?.disconnect();
4929
+ } catch {
4930
+ }
4931
+ await this.coalescer.idle();
4932
+ await Promise.allSettled([...this.pendingWork]);
4933
+ }
4934
+ /** Resolves when the running cycle has finished (tests, graceful stops). */
4935
+ idle() {
4936
+ return this.coalescer.idle();
4937
+ }
4938
+ /** Let go of a turn whose end the runtime will never confirm (an operator's call). Nothing is recorded for it. */
4939
+ releaseTurn(key) {
4940
+ const released = this.tracker.release(key);
4941
+ if (released) this.wakeFrom("more");
4942
+ return released;
4943
+ }
4944
+ status() {
4945
+ const texts = this.options.texts.current();
4946
+ const counters = this.coalescer.counters();
4947
+ const now2 = this.now();
4948
+ return {
4949
+ mode: this.options.mode,
4950
+ started: this.started,
4951
+ stopped: this.stopped,
4952
+ handle: this.handle,
4953
+ socket: this.realtime === null ? null : {
4954
+ state: this.realtime.state,
4955
+ ackNegotiated: this.realtime.ackNegotiated,
4956
+ capabilities: [...this.realtime.capabilities].sort(),
4957
+ intakePaused: this.realtime.intakePaused
4958
+ },
4959
+ coalescer: { state: this.coalescer.state, ...counters },
4960
+ texts: {
4961
+ version: texts?.version ?? null,
4962
+ manualVersion: texts?.manual?.version ?? null,
4963
+ source: this.options.texts.source ?? null,
4964
+ fetchedAt: this.options.texts.fetchedAt ?? null,
4965
+ lastError: this.options.texts.lastError ?? null
4966
+ },
4967
+ lastCycle: this.lastCycle,
4968
+ recentCycles: [...this.recentCycles],
4969
+ turns: this.tracker.running().map((turn) => ({ ...turn, overdue: now2 - turn.startedAt > TURN_OVERDUE_MS })),
4970
+ counters: {
4971
+ ...this.counts,
4972
+ turnsActive: this.activeTurns,
4973
+ turnsWaiting: this.waiting.length,
4974
+ outcomes: { ...this.outcomes }
4975
+ },
4976
+ lastError: this.lastError
4977
+ };
4978
+ }
4979
+ // ─── wakes ──────────────────────────────────────────────────────────────
4980
+ onMessage(message) {
4981
+ this.counts.frames += 1;
4982
+ const payload = message.payload ?? {};
4983
+ const conversationId = typeof payload.conversation_id === "string" ? payload.conversation_id : void 0;
4984
+ const raw = payload.sender ?? payload.from ?? payload.sender_handle;
4985
+ const sender = typeof raw === "string" ? normalizeHandle(raw) : "";
4986
+ if (this.handle !== null && sender === this.handle) {
4987
+ this.counts.echoes += 1;
4988
+ this.emit({ type: "echo", ...conversationId ? { conversationId } : {} });
4989
+ return;
4990
+ }
4991
+ this.wakeFrom("message", conversationId);
4992
+ }
4993
+ onWakeFrame(payload) {
4994
+ this.counts.frames += 1;
4995
+ const reason = typeof payload.reason === "string" ? payload.reason : void 0;
4996
+ const id = typeof payload.conversation_id === "string" ? payload.conversation_id : void 0;
4997
+ const named = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.filter((x) => typeof x === "string") : [];
4998
+ if (reason === "unanswered") {
4999
+ for (const conversationId of named) this.pacer.release(`conversation:${conversationId}`);
5000
+ this.pacer.releaseInvites();
5001
+ }
5002
+ this.wakeFrom("wake_frame", id, {
5003
+ ...reason !== void 0 ? { reason } : {},
5004
+ ...named.length > 0 ? { conversationIds: named } : {}
5005
+ });
5006
+ }
5007
+ wakeFrom(source, conversationId, extra = {}) {
5008
+ if (this.stopped) return;
5009
+ this.emit({ type: "wake", source, ...conversationId ? { conversationId } : {}, ...extra });
5010
+ this.coalescer.wake();
5011
+ }
5012
+ // ─── one cycle ──────────────────────────────────────────────────────────
5013
+ async cycle() {
5014
+ if (this.stopped) return;
5015
+ const token = ++this.cycleToken;
5016
+ const controller = new AbortController();
5017
+ this.cycleAbort = controller;
5018
+ const startedAt = this.now();
5019
+ let excludedMs = 0;
5020
+ let excludedSince = null;
5021
+ let depth = 0;
5022
+ const run2 = {
5023
+ token,
5024
+ signal: controller.signal,
5025
+ stale: () => this.cycleToken !== token || this.stopped,
5026
+ exclude: async (work2) => {
5027
+ if (depth++ === 0) excludedSince = this.now();
5028
+ try {
5029
+ return await work2();
5030
+ } finally {
5031
+ if (--depth === 0 && excludedSince !== null) {
5032
+ excludedMs += this.now() - excludedSince;
5033
+ excludedSince = null;
5034
+ }
5035
+ }
5036
+ }
5037
+ };
5038
+ const work = (async () => {
5039
+ const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run2) : await this.singleRunCycle(run2);
5040
+ if (!run2.stale() || this.stopped) this.finishCycle(summary);
5041
+ })();
5042
+ let timer = null;
5043
+ const overdue = new Promise((resolve) => {
5044
+ if (!Number.isFinite(this.cycleTimeoutMs)) return;
5045
+ const check = () => {
5046
+ timer = null;
5047
+ const now2 = this.now();
5048
+ const excluded = excludedMs + (excludedSince !== null ? now2 - excludedSince : 0);
5049
+ const active = now2 - startedAt - excluded;
5050
+ if (active >= this.cycleTimeoutMs) {
5051
+ resolve("overdue");
5052
+ return;
5053
+ }
5054
+ timer = this._setTimeout(check, Math.max(1, this.cycleTimeoutMs - active));
5055
+ timer.unref?.();
5056
+ };
5057
+ timer = this._setTimeout(check, this.cycleTimeoutMs);
5058
+ timer.unref?.();
5059
+ });
5060
+ const result = await Promise.race([work.then(() => "done"), overdue]);
5061
+ if (timer !== null) this._clearTimeout(timer);
5062
+ if (this.cycleAbort === controller) this.cycleAbort = null;
5063
+ if (result === "done") return;
5064
+ this.cycleToken += 1;
5065
+ controller.abort();
5066
+ void work.catch(() => void 0);
5067
+ const failure = `the cycle ran past ${this.cycleTimeoutMs} ms (not counting turns) and was abandoned; the next wake starts a new one`;
5068
+ this.fail(new Error(failure));
5069
+ this.finishCycle(this.summary("abandoned", { failure }));
5070
+ }
5071
+ finishCycle(summary) {
5072
+ this.lastCycle = summary;
5073
+ this.recentCycles.push(summary);
5074
+ if (this.recentCycles.length > RECENT_CYCLES) this.recentCycles.shift();
5075
+ if (summary.failure !== null) this.lastError = summary.failure;
5076
+ this.emit({ type: "cycle", summary });
5077
+ }
5078
+ /**
5079
+ * The gate's view of the client: a verdict in flight is known until it
5080
+ * answers (its card is held out of the next gate). It is not aborted with
5081
+ * an abandoned cycle: the server may already have taken it, and a second
5082
+ * one could climb the defer ladder twice.
5083
+ */
5084
+ recordingClient(run2) {
5085
+ const decisions = this.client.decisions;
5086
+ return {
5087
+ decisions: {
5088
+ record: async (conversationId, options) => {
5089
+ this.recordsInFlight.add(conversationId);
5090
+ try {
5091
+ return await decisions.record(conversationId, options);
5092
+ } finally {
5093
+ this.recordsInFlight.delete(conversationId);
5094
+ if (run2.stale()) this.afterTurnEnded();
5095
+ }
5096
+ }
5097
+ }
5098
+ };
5099
+ }
5100
+ /** The runtime's model call, bounded by `gateCallTimeoutMs` (and the cycle's own abandonment). */
5101
+ boundedModelCall(run2) {
5102
+ return (prompt) => new Promise((resolve, reject) => {
5103
+ const controller = new AbortController();
5104
+ const abort = () => {
5105
+ controller.abort();
5106
+ reject(new Error("the cycle was abandoned"));
5107
+ };
5108
+ if (run2.signal.aborted) {
5109
+ abort();
5110
+ return;
5111
+ }
5112
+ run2.signal.addEventListener("abort", abort, { once: true });
5113
+ const timer = Number.isFinite(this.gateCallTimeoutMs) ? this._setTimeout(() => {
5114
+ run2.signal.removeEventListener("abort", abort);
5115
+ controller.abort();
5116
+ reject(new Error(`no answer within ${this.gateCallTimeoutMs} ms`));
5117
+ }, this.gateCallTimeoutMs) : null;
5118
+ if (timer !== null) timer.unref?.();
5119
+ let call;
5120
+ try {
5121
+ call = Promise.resolve(this.options.callModel(prompt, { signal: controller.signal }));
5122
+ } catch (err) {
5123
+ call = Promise.reject(err);
5124
+ }
5125
+ call.then(
5126
+ (text) => {
5127
+ if (timer !== null) this._clearTimeout(timer);
5128
+ run2.signal.removeEventListener("abort", abort);
5129
+ resolve(text);
5130
+ },
5131
+ (err) => {
5132
+ if (timer !== null) this._clearTimeout(timer);
5133
+ run2.signal.removeEventListener("abort", abort);
5134
+ reject(err);
5135
+ }
5136
+ );
5137
+ });
5138
+ }
5139
+ async readTray() {
5140
+ try {
5141
+ const tray = await this.client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true });
5142
+ if (this.handle === null && typeof tray.you === "string" && tray.you.length > 0) {
5143
+ this.handle = normalizeHandle(tray.you);
5144
+ }
5145
+ return tray;
5146
+ } catch (err) {
5147
+ if (!this.stopped) this.fail(err);
5148
+ return null;
5149
+ }
5150
+ }
5151
+ async checkReady() {
5152
+ const readiness = this.options.readiness;
5153
+ if (!readiness) return null;
5154
+ try {
5155
+ const answer = await readiness();
5156
+ return answer.ready ? null : answer.reason;
5157
+ } catch (err) {
5158
+ return err instanceof Error ? err.message : String(err);
5159
+ }
5160
+ }
5161
+ async gateCallCycle(run2) {
5162
+ const tray = await this.readTray();
5163
+ if (run2.stale()) return this.summary("abandoned");
5164
+ if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
5165
+ const cards = cardsOf(tray);
5166
+ const invites = trayInvites(tray);
5167
+ const unheld = this.tracker.withoutRunning(cards).filter((card) => !this.recordsInFlight.has(card.conversation_id));
5168
+ const heldByTurns = cards.length - unheld.length;
5169
+ if (heldByTurns > 0) this.heldWhileRunning = true;
5170
+ const gateCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
5171
+ const openInvites = invites.filter((invite) => !this.tracker.inviteRunning(invite.invite_id));
5172
+ const owedInvites = openInvites.filter((invite) => !this.pacer.held(`invite:${invite.invite_id}`, null));
5173
+ const paced = unheld.length - gateCards.length + (openInvites.length - owedInvites.length);
5174
+ const owedCards = gateCards.filter((card) => card.muted !== true);
5175
+ const base = { cards: cards.length, invites: invites.length, heldByTurns, paced, truncated: tray.truncated === true };
5176
+ if (cards.length === 0 && invites.length === 0) return this.summary("empty", base);
5177
+ if (owedCards.length === 0 && owedInvites.length === 0) return this.summary("nothing_owed", base);
5178
+ const texts = await this.options.texts.ensure();
5179
+ if (run2.stale()) return this.summary("abandoned", base);
5180
+ if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
5181
+ const unready = await this.checkReady();
5182
+ if (run2.stale()) return this.summary("abandoned", base);
5183
+ if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5184
+ let gated = 0;
5185
+ const tally = {
5186
+ reply: 0,
5187
+ dismiss: 0,
5188
+ defer: 0,
5189
+ undecided: 0,
5190
+ recorded: 0,
5191
+ recordFailures: 0,
5192
+ turnsStarted: 0,
5193
+ turnsRefused: 0,
5194
+ turnsQueued: 0
5195
+ };
5196
+ let outcome = "invites_only";
5197
+ let failure = null;
5198
+ if (owedCards.length > 0) {
5199
+ gated = gateCards.length;
5200
+ const result = await run({
5201
+ tray: { ...tray, conversations: gateCards },
5202
+ callModel: this.boundedModelCall(run2),
5203
+ client: this.recordingClient(run2),
5204
+ texts,
5205
+ signal: run2.signal,
5206
+ ...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
5207
+ });
5208
+ for (const verdict of result.verdicts) tally[verdict.decision] += 1;
5209
+ tally.undecided = result.undecided.length;
5210
+ tally.recorded = result.recorded;
5211
+ tally.recordFailures = result.recordFailures.length;
5212
+ if (result.outcome === "fail_closed") {
5213
+ outcome = "fail_closed";
5214
+ failure = result.failure;
5215
+ } else {
5216
+ outcome = "decided";
5217
+ for (const reply of result.reply) {
5218
+ if (run2.stale()) break;
5219
+ tally[launchKey(await run2.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
5220
+ }
5221
+ }
5222
+ }
5223
+ for (const invite of owedInvites) {
5224
+ if (run2.stale()) break;
5225
+ tally[launchKey(await run2.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
5226
+ }
5227
+ if (run2.stale()) return this.summary("abandoned", base);
5228
+ if (tray.truncated === true && outcome === "decided") {
5229
+ this.readTheRest(tally.recorded > 0 || tally.turnsStarted > 0);
5230
+ }
5231
+ return this.summary(outcome, { ...base, gated, ...tally, failure });
5232
+ }
5233
+ /**
5234
+ * More conversations wait than one tray shows. After a cycle that moved
5235
+ * something (a verdict recorded, a turn started) read again at once; after
5236
+ * one that did not, wait 1 s, doubling to 60 s, so a cycle that cannot
5237
+ * progress (every record failing, every turn refused) never spins.
5238
+ */
5239
+ readTheRest(progressed) {
5240
+ if (this.stopped) return;
5241
+ if (progressed) {
5242
+ this.noProgressStreak = 0;
5243
+ this.clearMoreTimer();
5244
+ this.wakeFrom("more");
5245
+ return;
5246
+ }
5247
+ this.noProgressStreak += 1;
5248
+ if (this.moreTimer !== null) return;
5249
+ const delay = Math.min(NO_PROGRESS_BACKOFF_MAX_MS, NO_PROGRESS_BACKOFF_MS * 2 ** Math.min(this.noProgressStreak - 1, 16));
5250
+ this.moreTimer = this._setTimeout(() => {
5251
+ this.moreTimer = null;
5252
+ this.wakeFrom("more");
5253
+ }, delay);
5254
+ this.moreTimer.unref?.();
5255
+ }
5256
+ clearMoreTimer() {
5257
+ if (this.moreTimer !== null) {
5258
+ this._clearTimeout(this.moreTimer);
5259
+ this.moreTimer = null;
5260
+ }
5261
+ }
5262
+ async singleRunCycle(run2) {
5263
+ const tray = await this.readTray();
5264
+ if (run2.stale()) return this.summary("abandoned");
5265
+ let cards = null;
5266
+ let invites = null;
5267
+ let base = { cards: 0, invites: 0, heldByTurns: 0, truncated: false };
5268
+ if (tray !== null) {
5269
+ cards = cardsOf(tray).filter((card) => card.muted !== true).length;
5270
+ invites = trayInvites(tray).length;
5271
+ base = { cards: cardsOf(tray).length, invites, heldByTurns: 0, truncated: tray.truncated === true };
5272
+ if (base.cards === 0 && invites === 0) return this.summary("empty", base);
5273
+ if (cards === 0 && invites === 0) return this.summary("nothing_owed", base);
5274
+ }
5275
+ const texts = await this.options.texts.ensure();
5276
+ if (run2.stale()) return this.summary("abandoned", base);
5277
+ if (texts === null) return this.summary("texts_missing", { ...base, failure: "the served texts are not available" });
5278
+ const unready = await this.checkReady();
5279
+ if (run2.stale()) return this.summary("abandoned", base);
5280
+ if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5281
+ const prompt = cards === 0 && (invites ?? 0) > 0 ? texts.invite_prompt.trim() : (invites ?? 0) > 0 ? `${texts.wake_instruction.trim()}
5282
+
5283
+ ${texts.invite_prompt.trim()}` : texts.wake_instruction.trim();
5284
+ this.counts.runsStarted += 1;
5285
+ let end;
5286
+ try {
5287
+ end = await run2.exclude(() => this.options.startRun({ prompt, texts, cards, invites, signal: this.abort.signal }));
5288
+ } catch (err) {
5289
+ end = { status: "not_started", detail: err instanceof Error ? err.message : String(err) };
5290
+ }
5291
+ if (end.status === "completed") this.counts.runsCompleted += 1;
5292
+ else if (end.status === "failed") this.counts.runsFailed += 1;
5293
+ else this.counts.runsNotStarted += 1;
5294
+ this.emit({ type: "run", end });
5295
+ const startedWith = tray === null || this.options.dismissIgnoredInvites === false ? [] : trayInvites(tray);
5296
+ if (startedWith.length > 0) await this.track(this.afterRunInvites(startedWith, end));
5297
+ const outcome = end.status === "completed" ? "run_completed" : end.status === "failed" ? "run_failed" : "run_not_started";
5298
+ return this.summary(outcome, { ...base, failure: end.status === "completed" ? null : end.detail ?? null });
5299
+ }
5300
+ async afterRunInvites(invites, end) {
5301
+ const completed = end.status === "completed";
5302
+ const fresh = completed ? await this.readTray() : null;
5303
+ const turn = completed ? { status: "completed", agentchatCalls: null } : { status: "failed", ...end.detail !== void 0 ? { detail: end.detail } : {} };
5304
+ for (const invite of invites) {
5305
+ await this.concludeInvite(invite, turn, fresh, { requireKnownCalls: false, paced: true });
5306
+ }
5307
+ }
5308
+ // ─── turns (gate-call mode) ─────────────────────────────────────────────
5309
+ async startReplyTurn(reply, texts) {
5310
+ const anchor = anchorFrom(reply.card);
5311
+ const handle = this.tracker.begin({ kind: "reply", conversationId: reply.conversationId, anchor });
5312
+ if (handle === null) return "refused";
5313
+ const request = {
5314
+ kind: "reply",
5315
+ conversationId: reply.conversationId,
5316
+ card: reply.card,
5317
+ anchor,
5318
+ category: reply.category,
5319
+ prompt: replyPrompt(texts, reply.conversationId),
5320
+ texts,
5321
+ signal: this.abort.signal
5322
+ };
5323
+ return this.launch(handle, async () => {
5324
+ const admission = await this.admit(this.options.startTurn, request);
5325
+ if (!admission.started) {
5326
+ this.tracker.end(handle);
5327
+ this.counts.turnsRefused += 1;
5328
+ this.emit({ type: "turn_refused", kind: "reply", id: reply.conversationId, error: admission.error ?? null });
5329
+ return false;
5330
+ }
5331
+ this.counts.turnsStarted += 1;
5332
+ this.emit({ type: "turn_started", request: withoutRuntime(request) });
5333
+ void this.afterReplyTurn(handle, reply, admission.done);
5334
+ return true;
5335
+ });
5336
+ }
5337
+ async startInviteTurn(invite, texts) {
5338
+ const handle = this.tracker.begin({ kind: "invite", inviteId: invite.invite_id });
5339
+ if (handle === null) return "refused";
5340
+ const request = {
5341
+ kind: "invite",
5342
+ invite,
5343
+ prompt: `${texts.invite_prompt.trim()}
5344
+
5345
+ invite_id: ${invite.invite_id}`,
5346
+ texts,
5347
+ signal: this.abort.signal
5348
+ };
5349
+ return this.launch(handle, async () => {
5350
+ const admission = await this.admit(this.options.startInviteTurn ?? this.options.startTurn, request);
5351
+ if (!admission.started) {
5352
+ this.tracker.end(handle);
5353
+ this.counts.turnsRefused += 1;
5354
+ this.emit({ type: "turn_refused", kind: "invite", id: invite.invite_id, error: admission.error ?? null });
5355
+ return false;
5356
+ }
5357
+ this.counts.inviteTurnsStarted += 1;
5358
+ this.emit({ type: "turn_started", request: withoutRuntime(request) });
5359
+ void this.afterInviteTurn(handle, invite, admission.done);
5360
+ return true;
5361
+ });
5362
+ }
5363
+ /**
5364
+ * Start a turn now when a slot is free, else let it wait for one (its
5365
+ * tracker entry holds the card out of the gate).
5366
+ *
5367
+ * Waiting turns go first, in order. A slot can be free while turns still
5368
+ * wait: the pump frees it when an admission is refused and hands it on to
5369
+ * the next waiting turn only after an await. A turn gated in that window
5370
+ * queues behind them instead of taking the slot. A refused admission here
5371
+ * hands its slot on the same way.
5372
+ */
5373
+ async launch(handle, admit) {
5374
+ if (this.waiting.length > 0 || this.activeTurns >= this.maxTurns) {
5375
+ this.waiting.push({ handle, admit });
5376
+ this.counts.turnsQueued += 1;
5377
+ if (this.activeTurns < this.maxTurns) void this.pump();
5378
+ return "queued";
5379
+ }
5380
+ if (await this.admitInSlot(handle, admit)) return "started";
5381
+ if (this.waiting.length > 0) void this.pump();
5382
+ return "refused";
5383
+ }
5384
+ async admitInSlot(handle, admit) {
5385
+ this.activeTurns += 1;
5386
+ this.slotted.add(handle);
5387
+ const started = await admit();
5388
+ if (!started) this.releaseSlot(handle, { pump: false });
5389
+ return started;
5390
+ }
5391
+ /** The turn's slot is free (it ended, was refused, or was released): start the turns waiting for one. */
5392
+ releaseSlot(handle, options = {}) {
5393
+ if (this.slotted.delete(handle)) this.activeTurns = Math.max(0, this.activeTurns - 1);
5394
+ const queued = this.waiting.findIndex((w) => w.handle === handle);
5395
+ if (queued >= 0) this.waiting.splice(queued, 1);
5396
+ if (options.pump !== false) void this.pump();
5397
+ }
5398
+ async pump() {
5399
+ while (this.waiting.length > 0 && this.activeTurns < this.maxTurns && !this.stopped) {
5400
+ const next = this.waiting.shift();
5401
+ if (!this.tracker.holds(next.handle)) continue;
5402
+ await this.admitInSlot(next.handle, next.admit);
5403
+ }
5404
+ }
5405
+ async afterReplyTurn(handle, reply, done) {
5406
+ try {
5407
+ const end = await this.tracker.confirmedEnd(handle, done);
5408
+ if (end === null || !this.tracker.holds(handle)) return;
5409
+ await this.track(this.recordReplyOutcome(handle, reply, end));
5410
+ } finally {
5411
+ this.tracker.end(handle);
5412
+ this.releaseSlot(handle);
5413
+ this.afterTurnEnded();
5414
+ }
5415
+ }
5416
+ async recordReplyOutcome(handle, reply, end) {
5417
+ const fresh = await this.readTray();
5418
+ if (!this.tracker.holds(handle)) return;
5419
+ const anchor = anchorFrom(reply.card);
5420
+ const key = `${reply.conversationId}|${anchor ?? ""}`;
5421
+ const silentBefore = this.silent.get(key) ?? 0;
5422
+ const outcome = turnOutcome({
5423
+ turn: end,
5424
+ turnStartedAt: handle.startedAt,
5425
+ gateCard: reply.card,
5426
+ category: reply.category,
5427
+ freshTray: fresh,
5428
+ silentBefore
5429
+ });
5430
+ this.count(outcome.reason);
5431
+ if (outcome.reason === "silent_first") {
5432
+ this.remember(key, silentBefore + 1);
5433
+ this.pacer.hold(`conversation:${reply.conversationId}`, anchor);
5434
+ } else if (outcome.reason === "card_left_tray" || outcome.reason === "turn_recorded_verdict") {
5435
+ this.silent.delete(key);
5436
+ }
5437
+ let recorded = false;
5438
+ if (outcome.action !== "none") {
5439
+ try {
5440
+ recorded = await applyOutcome(this.client, outcome);
5441
+ this.silent.delete(key);
5442
+ } catch (err) {
5443
+ this.counts.outcomeRecordFailures += 1;
5444
+ this.fail(err);
5445
+ }
5446
+ }
5447
+ this.emit({ type: "turn_outcome", outcome, recorded });
5448
+ }
5449
+ async afterInviteTurn(handle, invite, done) {
5450
+ try {
5451
+ const end = await this.tracker.confirmedEnd(handle, done);
5452
+ if (end === null || !this.tracker.holds(handle)) return;
5453
+ await this.track(this.recordInviteOutcome(handle, invite, end));
5454
+ this.pacer.hold(`invite:${invite.invite_id}`, null);
5455
+ } finally {
5456
+ this.tracker.end(handle);
5457
+ this.releaseSlot(handle);
5458
+ this.afterTurnEnded();
5459
+ }
5460
+ }
5461
+ async recordInviteOutcome(handle, invite, end) {
5462
+ const fresh = await this.readTray();
5463
+ if (!this.tracker.holds(handle)) return;
5464
+ await this.concludeInvite(invite, end, fresh);
5465
+ }
5466
+ /** The D5 rule for one invite after a turn or a run, and the one call it asks for. */
5467
+ async concludeInvite(invite, end, fresh, rule = {}) {
5468
+ const key = `invite|${invite.invite_id}`;
5469
+ const silentBefore = this.silent.get(key) ?? 0;
5470
+ let outcome = inviteOutcome({
5471
+ turn: end,
5472
+ invite,
5473
+ freshTray: fresh,
5474
+ silentBefore,
5475
+ ...rule.requireKnownCalls !== void 0 ? { requireKnownCalls: rule.requireKnownCalls } : {}
5476
+ });
5477
+ const countedAt = this.silentAt.get(key);
5478
+ if (rule.paced && outcome.reason === "silent_again" && countedAt !== void 0 && this.now() - countedAt < this.paceMs) {
5479
+ outcome = { action: "none", reason: "silent_paced", inviteId: invite.invite_id };
5480
+ }
5481
+ this.count(`invite_${outcome.reason}`);
5482
+ if (outcome.reason === "silent_first") {
5483
+ this.remember(key, silentBefore + 1);
5484
+ this.silentAt.set(key, this.now());
5485
+ }
5486
+ if (outcome.reason === "invite_answered") {
5487
+ this.silent.delete(key);
5488
+ this.silentAt.delete(key);
5489
+ }
5490
+ let recorded = false;
5491
+ if (outcome.action !== "none") {
5492
+ try {
5493
+ recorded = await applyInviteOutcome(this.client, outcome);
5494
+ this.silent.delete(key);
5495
+ this.silentAt.delete(key);
5496
+ } catch (err) {
5497
+ this.counts.outcomeRecordFailures += 1;
5498
+ this.fail(err);
5499
+ }
5500
+ }
5501
+ this.emit({ type: "invite_outcome", outcome, recorded });
5502
+ }
5503
+ async admit(start, request) {
5504
+ try {
5505
+ return await start(request);
5506
+ } catch (err) {
5507
+ return { started: false, error: err instanceof Error ? err.message : String(err) };
5508
+ }
5509
+ }
5510
+ /** A turn's end: cards a cycle left out meanwhile are read again. */
5511
+ afterTurnEnded() {
5512
+ if (this.heldWhileRunning && !this.stopped) {
5513
+ this.heldWhileRunning = false;
5514
+ this.wakeFrom("more");
5515
+ }
5516
+ }
5517
+ // ─── small things ───────────────────────────────────────────────────────
5518
+ /** Recording under way after a turn's confirmed end: `stop()` waits for it. */
5519
+ track(work) {
5520
+ this.pendingWork.add(work);
5521
+ return work.finally(() => this.pendingWork.delete(work));
5522
+ }
5523
+ remember(key, count) {
5524
+ this.silent.delete(key);
5525
+ this.silent.set(key, count);
5526
+ while (this.silent.size > SILENT_MEMORY) {
5527
+ const oldest = this.silent.keys().next().value;
5528
+ if (oldest === void 0) break;
5529
+ this.silent.delete(oldest);
5530
+ this.silentAt.delete(oldest);
5531
+ }
5532
+ }
5533
+ count(reason) {
5534
+ this.outcomes[reason] = (this.outcomes[reason] ?? 0) + 1;
5535
+ }
5536
+ summary(outcome, parts = {}) {
5537
+ return {
5538
+ at: new Date(this.now()).toISOString(),
5539
+ outcome,
5540
+ cards: 0,
5541
+ invites: 0,
5542
+ gated: 0,
5543
+ reply: 0,
5544
+ dismiss: 0,
5545
+ defer: 0,
5546
+ undecided: 0,
5547
+ recorded: 0,
5548
+ recordFailures: 0,
5549
+ turnsStarted: 0,
5550
+ turnsRefused: 0,
5551
+ turnsQueued: 0,
5552
+ heldByTurns: 0,
5553
+ paced: 0,
5554
+ truncated: false,
5555
+ failure: null,
5556
+ ...parts
5557
+ };
5558
+ }
5559
+ fail(err) {
5560
+ const error = err instanceof Error ? err : new Error(String(err));
5561
+ this.lastError = error.message;
5562
+ this.emit({ type: "error", error });
5563
+ }
5564
+ emit(event) {
5565
+ try {
5566
+ this.options.onEvent?.(event);
5567
+ } catch {
5568
+ }
5569
+ }
5570
+ };
5571
+ function replyPrompt(texts, conversationId) {
5572
+ return `${texts.wake_instruction.trim()}
5573
+
5574
+ conversation_id: ${conversationId}`;
5575
+ }
5576
+ function timeoutOption(value, fallback, name) {
5577
+ if (value === void 0) return fallback;
5578
+ if (value === 0 || value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;
5579
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new RangeError(`ReceiveLoop: ${name} must be 0 (off) or a positive number`);
5580
+ return value;
5581
+ }
5582
+ function launchKey(launch) {
5583
+ return launch === "started" ? "turnsStarted" : launch === "queued" ? "turnsQueued" : "turnsRefused";
5584
+ }
5585
+ function trayInvites(tray) {
5586
+ const raw = tray.invites;
5587
+ if (!Array.isArray(raw)) return [];
5588
+ return raw.filter(
5589
+ (invite) => typeof invite === "object" && invite !== null && typeof invite.invite_id === "string" && invite.invite_id.length > 0
5590
+ );
5591
+ }
5592
+ function anchorFrom(card) {
5593
+ return anchorOf(card) ?? null;
5594
+ }
5595
+ function withoutRuntime(request) {
5596
+ const { signal: _signal, texts: _texts, ...rest } = request;
5597
+ return rest;
5598
+ }
5599
+ function wsBase(httpBase) {
5600
+ const base = (httpBase ?? "https://api.agentchat.me").replace(/\/+$/, "");
5601
+ return base.replace(/^http/, "ws");
5602
+ }
5603
+
5604
+ // src/wake-webhook-verify.ts
5605
+ var WakeWebhookVerificationError = class extends Error {
5606
+ reason;
5607
+ constructor(reason, message) {
5608
+ super(message ?? `wake webhook verification failed: ${reason}`);
5609
+ this.name = "WakeWebhookVerificationError";
5610
+ this.reason = reason;
5611
+ }
5612
+ };
5613
+ var DEFAULT_TOLERANCE_S = 300;
5614
+ var DIGITS = /^\d+$/;
5615
+ var HEX = /^[0-9a-fA-F]+$/;
5616
+ async function verifyWakeWebhook(options) {
5617
+ const bytes = typeof options.body === "string" ? new TextEncoder().encode(options.body) : options.body;
5618
+ const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_S;
5619
+ const nowSeconds = (options.now ?? Date.now)() / 1e3;
5620
+ switch (options.dialect) {
5621
+ case "agentchat": {
5622
+ const auth = header(options.headers, "authorization");
5623
+ if (auth === null || auth.trim() === "") throw new WakeWebhookVerificationError("missing_signature");
5624
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(auth.trim());
5625
+ if (!match?.[1]) throw new WakeWebhookVerificationError("malformed_signature");
5626
+ if (!await sameSecret(match[1], options.secret)) throw new WakeWebhookVerificationError("bad_signature");
5627
+ break;
5628
+ }
5629
+ case "hermes": {
5630
+ const ts = header(options.headers, "x-webhook-timestamp");
5631
+ const sig = header(options.headers, "x-webhook-signature-v2");
5632
+ if (ts === null || sig === null) throw new WakeWebhookVerificationError("missing_signature");
5633
+ const timestamp = ts.trim();
5634
+ const signature = sig.trim();
5635
+ if (!DIGITS.test(timestamp) || !HEX.test(signature)) throw new WakeWebhookVerificationError("malformed_signature");
5636
+ checkSkew(Number(timestamp), nowSeconds, tolerance);
5637
+ const expected = toHex(await hmac(utf8(options.secret), concat(utf8(`${timestamp}.`), bytes)));
5638
+ if (!constantTimeEqual(expected, signature.toLowerCase())) throw new WakeWebhookVerificationError("bad_signature");
5639
+ break;
5640
+ }
5641
+ case "standard-webhooks": {
5642
+ const id = header(options.headers, "webhook-id");
5643
+ const ts = header(options.headers, "webhook-timestamp");
5644
+ const sig = header(options.headers, "webhook-signature");
5645
+ if (id === null || ts === null || sig === null) throw new WakeWebhookVerificationError("missing_signature");
5646
+ const timestamp = ts.trim();
5647
+ if (!DIGITS.test(timestamp)) throw new WakeWebhookVerificationError("malformed_signature");
5648
+ const candidates = sig.trim().split(/\s+/).flatMap((entry) => {
5649
+ const comma = entry.indexOf(",");
5650
+ return comma > 0 && entry.slice(0, comma) === "v1" ? [entry.slice(comma + 1)] : [];
5651
+ });
5652
+ if (candidates.length === 0) throw new WakeWebhookVerificationError("malformed_signature");
5653
+ checkSkew(Number(timestamp), nowSeconds, tolerance);
5654
+ const key = options.secret.startsWith("whsec_") ? fromBase64(options.secret.slice("whsec_".length)) : utf8(options.secret);
5655
+ const expected = toBase64(await hmac(key, concat(utf8(`${id.trim()}.${timestamp}.`), bytes)));
5656
+ let matched = false;
5657
+ for (const candidate of candidates) {
5658
+ if (constantTimeEqual(expected, candidate)) matched = true;
5659
+ }
5660
+ if (!matched) throw new WakeWebhookVerificationError("bad_signature");
5661
+ break;
5662
+ }
5663
+ default:
5664
+ throw new WakeWebhookVerificationError("malformed_signature", `wake webhook verification: unknown dialect ${String(options.dialect)}`);
5665
+ }
5666
+ let parsed;
5667
+ try {
5668
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
5669
+ } catch {
5670
+ throw new WakeWebhookVerificationError("malformed_payload");
5671
+ }
5672
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || parsed.type !== "agentchat.wake") {
5673
+ throw new WakeWebhookVerificationError("malformed_payload");
5674
+ }
5675
+ return parsed;
5676
+ }
5677
+ function header(headers, name) {
5678
+ const getter = headers.get;
5679
+ if (typeof getter === "function") {
5680
+ const value = headers.get(name);
5681
+ return typeof value === "string" ? value : null;
5682
+ }
5683
+ const record = headers;
5684
+ for (const key of Object.keys(record)) {
5685
+ if (key.toLowerCase() !== name) continue;
5686
+ const value = record[key];
5687
+ if (typeof value === "string") return value;
5688
+ if (Array.isArray(value) && typeof value[0] === "string") return value.join(", ");
5689
+ }
5690
+ return null;
5691
+ }
5692
+ function checkSkew(timestamp, nowSeconds, tolerance) {
5693
+ if (tolerance > 0 && Math.abs(nowSeconds - timestamp) > tolerance) {
5694
+ throw new WakeWebhookVerificationError("timestamp_skew");
5695
+ }
5696
+ }
5697
+ function subtleCrypto() {
5698
+ const subtle = globalThis.crypto?.subtle;
5699
+ if (!subtle) {
5700
+ throw new WakeWebhookVerificationError("bad_signature", "Web Crypto (globalThis.crypto.subtle) is not available in this runtime");
5701
+ }
5702
+ return subtle;
5703
+ }
5704
+ async function hmac(key, data) {
5705
+ const subtle = subtleCrypto();
5706
+ const cryptoKey = await subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
5707
+ return new Uint8Array(await subtle.sign("HMAC", cryptoKey, data));
5708
+ }
5709
+ async function sameSecret(given, secret) {
5710
+ const subtle = subtleCrypto();
5711
+ const [a, b] = await Promise.all([
5712
+ subtle.digest("SHA-256", utf8(given)),
5713
+ subtle.digest("SHA-256", utf8(secret))
5714
+ ]);
5715
+ return constantTimeEqual(toHex(new Uint8Array(a)), toHex(new Uint8Array(b)));
5716
+ }
5717
+ function utf8(value) {
5718
+ return new TextEncoder().encode(value);
5719
+ }
5720
+ function concat(a, b) {
5721
+ const out = new Uint8Array(a.byteLength + b.byteLength);
5722
+ out.set(a, 0);
5723
+ out.set(b, a.byteLength);
5724
+ return out;
5725
+ }
5726
+ function toHex(bytes) {
5727
+ let hex = "";
5728
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
5729
+ return hex;
5730
+ }
5731
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
5732
+ function toBase64(bytes) {
5733
+ let out = "";
5734
+ for (let i = 0; i < bytes.length; i += 3) {
5735
+ const a = bytes[i] ?? 0;
5736
+ const b = bytes[i + 1];
5737
+ const c = bytes[i + 2];
5738
+ const n = a << 16 | (b ?? 0) << 8 | (c ?? 0);
5739
+ out += B64[n >> 18 & 63] + B64[n >> 12 & 63];
5740
+ out += b === void 0 ? "=" : B64[n >> 6 & 63];
5741
+ out += c === void 0 ? "=" : B64[n & 63];
5742
+ }
5743
+ return out;
5744
+ }
5745
+ function fromBase64(value) {
5746
+ const clean = value.replace(/[\s=]/g, "").replace(/-/g, "+").replace(/_/g, "/");
5747
+ const bytes = [];
5748
+ let buffer = 0;
5749
+ let bits = 0;
5750
+ for (const char of clean) {
5751
+ const index = B64.indexOf(char);
5752
+ if (index < 0) continue;
5753
+ buffer = (buffer & 4095) << 6 | index;
5754
+ bits += 6;
5755
+ if (bits >= 8) {
5756
+ bits -= 8;
5757
+ bytes.push(buffer >> bits & 255);
5758
+ }
5759
+ }
5760
+ return new Uint8Array(bytes);
5761
+ }
5762
+ function constantTimeEqual(a, b) {
5763
+ if (a.length !== b.length) return false;
5764
+ let mismatch = 0;
5765
+ for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
5766
+ return mismatch === 0;
5767
+ }
5768
+
3037
5769
  // src/render.ts
3038
5770
  var SEC = 1e3;
3039
5771
  var MIN = 60 * SEC;
@@ -3109,6 +5841,6 @@ var ALLOWED_ATTACHMENT_MIME = [
3109
5841
  "video/webm"
3110
5842
  ];
3111
5843
 
3112
- export { ALLOWED_ATTACHMENT_MIME, AgentChatClient, AgentChatError, AwaitingReplyError, BlockedError, ConnectionError, DEFAULT_RETRY_POLICY, EmailExhaustedError, EmailLimitReachedError, ErrorCode, ForbiddenError, GroupDeletedError, HandleRequiredError, HttpTransport, INBOX_TRAY_DEFAULT_LIMIT, INBOX_TRAY_MAX_LIMIT, INBOX_WAIT_MAX_MS, MAX_ATTACHMENT_SIZE, NotFoundError, RateLimitedError, RealtimeClient, RecipientBackloggedError, RestrictedError, ServerError, SuspendedError, UnauthorizedError, VERSION, ValidationError, createAgentChatError, gate_exports as gate, isAuthRejectionClose, paginate, parseRetryAfter, renderMessageContext };
5844
+ export { ALLOWED_ATTACHMENT_MIME, AgentChatClient, AgentChatError, AwaitingReplyError, BlockedError, CONNECT_BUDGET_CLOSE_CODE, CONNECT_BUDGET_MAX_DELAY_MS, CONNECT_BUDGET_MIN_DELAY_MS, ConnectionError, DEFAULT_RETRY_POLICY, EmailExhaustedError, EmailLimitReachedError, ErrorCode, ForbiddenError, GroupDeletedError, HandleRequiredError, HttpTransport, INBOX_TRAY_DEFAULT_LIMIT, INBOX_TRAY_MAX_LIMIT, INBOX_WAIT_MAX_MS, MAX_ATTACHMENT_SIZE, NotFoundError, RateLimitedError, RealtimeClient, RecipientBackloggedError, RestrictedError, ServerError, SuspendedError, UnauthorizedError, VERSION, ValidationError, WakeWebhookVerificationError, connectBudgetDelayMs, createAgentChatError, gate_exports as gate, integration_exports as integration, isAuthRejectionClose, paginate, parseRetryAfter, renderMessageContext, verifyWakeWebhook, wakePayloadOf };
3113
5845
  //# sourceMappingURL=index.js.map
3114
5846
  //# sourceMappingURL=index.js.map