agentchatme 1.2.1 → 1.3.0

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