viber-channel 0.8.47 → 0.8.49

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.
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Bounded retry of a transport ACK (#751), shared by the Claude channel's DM
3
+ * streams and the Codex/Gemma bridge so both runtimes behave the same.
4
+ *
5
+ * - each attempt is bounded by {@link ACK_ATTEMPT_TIMEOUT_MS}: a POST that hangs
6
+ * can never keep an id "in flight" forever;
7
+ * - `ok` and `rejected` (4xx — the server will never accept it) are final;
8
+ * - `failed` (network, 5xx, 408, 429, timeout) retries after each delay, then
9
+ * gives up and returns `failed` — the caller retries on the next delivery.
10
+ * Never throws.
11
+ */
12
+ export const ACK_ATTEMPT_TIMEOUT_MS = 10_000;
13
+ export const ACK_RETRY_DELAYS_MS = [1000, 2000, 4000];
14
+
15
+ /** Cap of an ACK-pending set (#751): the oldest ids are dropped beyond it. */
16
+ export const PENDING_ACKS_MAX = 1000;
17
+
18
+ /** Add `id` to a pending set, dropping the oldest entries beyond the cap. */
19
+ export function addPending(set: Set<string>, id: string, log?: (line: string) => void): void {
20
+ set.add(id);
21
+ if (set.size <= PENDING_ACKS_MAX) return;
22
+ let dropped = 0;
23
+ for (const old of set) {
24
+ if (set.size <= PENDING_ACKS_MAX) break;
25
+ set.delete(old);
26
+ dropped += 1;
27
+ }
28
+ log?.(`[ack] pending-ACK set over ${PENDING_ACKS_MAX}: dropped the ${dropped} oldest\n`);
29
+ }
30
+
31
+ export type AckOutcome = "ok" | "rejected" | "failed";
32
+
33
+ export async function ackWithRetry(
34
+ attempt: (signal: AbortSignal) => Promise<boolean | AckOutcome>,
35
+ opts: { delaysMs?: number[]; attemptTimeoutMs?: number; signal?: AbortSignal } = {},
36
+ ): Promise<AckOutcome> {
37
+ const delays = opts.delaysMs ?? ACK_RETRY_DELAYS_MS;
38
+ const timeoutMs = opts.attemptTimeoutMs ?? ACK_ATTEMPT_TIMEOUT_MS;
39
+ for (let i = 0; i <= delays.length; i++) {
40
+ if (opts.signal?.aborted) return "failed";
41
+ const perAttempt = opts.signal
42
+ ? AbortSignal.any([opts.signal, AbortSignal.timeout(timeoutMs)])
43
+ : AbortSignal.timeout(timeoutMs);
44
+ let r: boolean | AckOutcome;
45
+ try {
46
+ r = await Promise.race([
47
+ attempt(perAttempt),
48
+ new Promise<"failed">((resolve) => perAttempt.addEventListener("abort", () => resolve("failed"), { once: true })),
49
+ ]);
50
+ } catch {
51
+ r = "failed";
52
+ }
53
+ if (r === true || r === "ok") return "ok";
54
+ if (r === "rejected") return "rejected";
55
+ if (i < delays.length) await sleep(delays[i], opts.signal);
56
+ }
57
+ return "failed";
58
+ }
59
+
60
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
61
+ return new Promise((resolve) => {
62
+ if (signal?.aborted) return resolve();
63
+ const t = setTimeout(resolve, ms);
64
+ signal?.addEventListener(
65
+ "abort",
66
+ () => {
67
+ clearTimeout(t);
68
+ resolve();
69
+ },
70
+ { once: true },
71
+ );
72
+ });
73
+ }
@@ -24,7 +24,7 @@ import {
24
24
  RefreshNetworkError,
25
25
  refreshConversationToken,
26
26
  } from "./conversation.js";
27
- import { ackMessage, ConversationTokenExpiredError, fetchMessages, postMessage } from "./messages.js";
27
+ import { ackMessageResult, ConversationTokenExpiredError, fetchMessages, fetchMessageWindow, type MessageWindowQuery, postMessage } from "./messages.js";
28
28
  import { buildSseUrl } from "./urls.js";
29
29
  import { cfAccessHeaders } from "./cfAccess.js";
30
30
  import { sessionFilePath, writeHandle } from "./channel_session.js";
@@ -37,6 +37,10 @@ import {
37
37
  type PersistentControlStream,
38
38
  } from "./control_stream.js";
39
39
  import { type PresenceGate, startCoverageWatch } from "./coverage_watch.js";
40
+ import { createIdleGuard, type IdleGuard } from "./sse_idle.js";
41
+ import { ackWithRetry, addPending } from "./ack_retry.js";
42
+ import { ackServerEvent, createServerEventHandler } from "./server_events.js";
43
+ import { createLaunchConfirmer, postLaunched } from "./launch_confirm.js";
40
44
  import { type PresenceEndReason, type PresenceRecordHandle, startPresenceRecord } from "./presence_record.js";
41
45
 
42
46
  /** A conversation message as it arrives over the conversation SSE / message list. */
@@ -61,6 +65,21 @@ export interface ConversationMessage {
61
65
  export interface BridgeWatermark {
62
66
  /** Highest delivered (replied-to) message id (0 = nothing delivered yet). */
63
67
  lastId: number;
68
+ /**
69
+ * #751: ids whose transport ACK is not confirmed yet. At or below `lastId`,
70
+ * only these are re-acknowledged — a reconnect's full re-read never re-ACKs
71
+ * the whole history (one Worker subrequest each).
72
+ */
73
+ pendingAcks?: Set<string>;
74
+ /**
75
+ * #751 (Codex, step-07): CONTIGUOUS coverage, advanced only by a fully processed
76
+ * page of the id-ordered window — never by a live delivery. Absent on a legacy
77
+ * watermark (`lastId` stands for it). The reconcile resumes from here, so a 101
78
+ * missed while 102 arrived live is still handled.
79
+ */
80
+ floor?: number;
81
+ /** #751: ids delivered ABOVE `floor`. */
82
+ delivered?: Set<string>;
64
83
  }
65
84
 
66
85
  /** One live conversation stream's mutable runtime state (token rotates). */
@@ -480,7 +499,21 @@ export function readTurnDegradation(err: unknown): TurnDegradation | undefined {
480
499
  * never skips. Pure + exported for unit tests (pattern `decideTurnPostAction`).
481
500
  */
482
501
  export function watermarkShouldSkip(numId: number, watermark?: BridgeWatermark): boolean {
483
- return !!watermark && Number.isSafeInteger(numId) && numId <= watermark.lastId;
502
+ if (!watermark || !Number.isSafeInteger(numId)) return false;
503
+ return numId <= bridgeFloorOf(watermark) || !!watermark.delivered?.has(String(numId));
504
+ }
505
+
506
+ /** #751: the contiguous floor of a bridge watermark (a legacy one: its lastId). */
507
+ export function bridgeFloorOf(w: BridgeWatermark): number {
508
+ if (w.floor === undefined) w.floor = w.lastId;
509
+ return w.floor;
510
+ }
511
+
512
+ /** #751: raise the contiguous floor (reconcile only) and forget the ids under it. */
513
+ export function bridgeAdvanceFloor(w: BridgeWatermark | undefined, to: number): void {
514
+ if (!w || !Number.isSafeInteger(to) || to <= bridgeFloorOf(w)) return;
515
+ w.floor = to;
516
+ for (const id of w.delivered ?? []) if (Number(id) <= to) w.delivered?.delete(id);
484
517
  }
485
518
 
486
519
  /**
@@ -490,9 +523,10 @@ export function watermarkShouldSkip(numId: number, watermark?: BridgeWatermark):
490
523
  * gate; a NaN/absent/unsafe id is never watermarked. Pure + exported.
491
524
  */
492
525
  export function watermarkAdvance(numId: number, watermark?: BridgeWatermark): void {
493
- if (watermark && Number.isSafeInteger(numId) && numId > watermark.lastId) {
494
- watermark.lastId = numId;
495
- }
526
+ if (!watermark || !Number.isSafeInteger(numId)) return;
527
+ const floor = bridgeFloorOf(watermark);
528
+ if (numId > watermark.lastId) watermark.lastId = numId;
529
+ if (numId > floor) (watermark.delivered ??= new Set<string>()).add(String(numId));
496
530
  }
497
531
 
498
532
  /** Bearer + fingerprint + CF Access headers for a conversation request. */
@@ -547,6 +581,12 @@ export interface ConversationStreamDeps {
547
581
  * whole point of the cross-run dedup.
548
582
  */
549
583
  watermarks: Map<string, BridgeWatermark>;
584
+ /**
585
+ * #751: per-conversation injectors, set by each live sseLoop — a durable
586
+ * server event (delivery_failed…) is presented to the model as a turn on the
587
+ * conversation it concerns, serialised with the live turns.
588
+ */
589
+ injectors?: Map<string, (text: string) => Promise<void>>;
550
590
  /** Global shutdown signal — aborting it stops every stream. */
551
591
  parentSignal: AbortSignal;
552
592
  /**
@@ -632,10 +672,10 @@ export async function runConversationStream(
632
672
  // abort+restart on re-join (the finally below deliberately does NOT delete it).
633
673
  let watermark = watermarks.get(convId);
634
674
  if (!watermark) {
635
- watermark = { lastId: 0 };
675
+ watermark = { lastId: 0, pendingAcks: new Set<string>() }; // #751: ACK tracking on
636
676
  watermarks.set(convId, watermark);
637
677
  }
638
- await sseLoop({ minted, runtime, fingerprint, ownInstanceKey: instanceKey, options, signal: ctrl.signal, getBaseUrl: baseUrl, logPrefix, runTurn, watermark, gate: deps.gate });
678
+ await sseLoop({ minted, runtime, fingerprint, ownInstanceKey: instanceKey, options, signal: ctrl.signal, getBaseUrl: baseUrl, logPrefix, runTurn, watermark, gate: deps.gate, injectors: deps.injectors });
639
679
  } finally {
640
680
  parentSignal.removeEventListener("abort", onParentAbort);
641
681
  runtime.scheduler?.cancel();
@@ -690,6 +730,17 @@ export async function sseLoop(opts: {
690
730
  fetchMessagesImpl?: typeof fetchMessages;
691
731
  /** #627: the pause gate (see ConversationStreamDeps.gate). */
692
732
  gate?: PresenceGate;
733
+ /** #751: idle deadline per wait for bytes; default `SSE_IDLE_TIMEOUT_MS`. */
734
+ idleTimeoutMs?: number;
735
+ /** Reconnect delay after a failure; default 2000 ms (tests shorten it). */
736
+ reconnectDelayMs?: number;
737
+ /** #751: bound of the reconcile REST phase (own guard); default 10 000 ms. */
738
+ catchUpTimeoutMs?: number;
739
+ /** #751: where to register this conversation's turn injector (see ConversationStreamDeps). */
740
+ injectors?: Map<string, (text: string) => Promise<void>>;
741
+ /** #751: ACK retry delays / per-attempt bound (tests shorten them). */
742
+ ackRetryDelaysMs?: number[];
743
+ ackAttemptTimeoutMs?: number;
693
744
  }): Promise<void> {
694
745
  const { minted, runtime, fingerprint, ownInstanceKey, options, signal, getBaseUrl, logPrefix, runTurn, watermark } = opts;
695
746
  const deps = { gate: opts.gate };
@@ -731,7 +782,7 @@ export async function sseLoop(opts: {
731
782
  // reply UNLESS an outbound tool already posted this turn (anti-double-post).
732
783
  // Returns true when the reply was dropped because the stream was aborted
733
784
  // mid-flight (caller must not trip the --once clean exit).
734
- async function replyForTurn(content: string, echoMsg?: ConversationMessage): Promise<boolean> {
785
+ async function replyForTurn(content: string, echoMsg?: ConversationMessage, noAutoPost = false): Promise<boolean> {
735
786
  let result: TurnResult;
736
787
  try {
737
788
  result = await runTurn(content, echoMsg, signal);
@@ -762,6 +813,14 @@ export async function sseLoop(opts: {
762
813
  rearmFailureNotice();
763
814
  return false;
764
815
  case "auto-post":
816
+ if (noAutoPost) {
817
+ // #751: a server-event notice turn NEVER auto-posts — its text would land in
818
+ // the DM of the unhooked peer, get its own deadline, its own delivery_failed,
819
+ // another notice turn… (loop, Opus review). The model acts through tools.
820
+ process.stderr.write(`${logPrefix} notice turn on ${runtime.id}: reply not posted (notices never auto-post)\n`);
821
+ rearmFailureNotice();
822
+ return false;
823
+ }
765
824
  await postBridgeReply({ baseUrl: baseUrl(), runtime, text: reply, ownPostedIds, signal, logPrefix, fetchImpl, gate: deps.gate });
766
825
  rearmFailureNotice();
767
826
  return false;
@@ -797,17 +856,41 @@ export async function sseLoop(opts: {
797
856
  // the Worker's insertMessageAck qualification. N/A today: addressed_to is
798
857
  // dormant and fan-out is per-conversation, so every connected bridge truly
799
858
  // receives the message (consistent with decision A = delivered-to-bridge).
859
+ //
860
+ // #751: a PEER agent's message is acknowledged too — the transport receipt its
861
+ // sender relies on (the Worker accepts it only in a canonical-pair DM, from the
862
+ // other member). Elsewhere the Worker rejects it (4xx): the id is then marked
863
+ // done and never retried, so a multi-agent room costs one request per message.
800
864
  function ackInboundReceipt(msg: ConversationMessage): void {
801
- if (msg.role !== "user" && msg.role !== "user_voice") return;
802
- if (msg.sender_instance_id) return;
865
+ const fromWeb = (msg.role === "user" || msg.role === "user_voice") && !msg.sender_instance_id;
866
+ const fromPeer = !!msg.sender_instance_id && msg.sender_instance_id !== ownInstanceKey;
867
+ if (!fromWeb && !fromPeer) return;
803
868
  const idStr = msg.id !== undefined && msg.id !== null ? String(msg.id) : undefined;
804
869
  if (!idStr) return;
870
+ if (ownPostedIds.has(idStr)) return;
805
871
  if (ackedIds.has(idStr) || ackInFlightIds.has(idStr)) return;
872
+ // Below the watermark, only an id still pending its ACK goes out again.
873
+ const n = Number(idStr);
874
+ // Tracking is on when the caller seeded `pendingAcks`; without it (unknown ACK
875
+ // state, #346 B.13) a re-delivered id is still re-acknowledged.
876
+ if (watermark?.pendingAcks && Number.isSafeInteger(n) && n <= watermark.lastId && !watermark.pendingAcks.has(idStr)) return;
806
877
  ackInFlightIds.add(idStr);
807
- void ackMessage(baseUrl(), runtime.id, runtime.token, idStr, signal, fetchImpl)
808
- .then((ok) => {
809
- if (ok) ackedIds.add(idStr);
810
- else process.stderr.write(`${logPrefix} ack failed for message ${idStr} (will retry on reconnect)\n`);
878
+ const pending = watermark ? (watermark.pendingAcks ??= new Set<string>()) : undefined;
879
+ if (pending) addPending(pending, idStr, (l) => process.stderr.write(`${logPrefix} ${l}`));
880
+ // Same bounded retry as the Claude DM streams (#751): each attempt is timed
881
+ // out, failures retry in-run, a 4xx refusal is final.
882
+ void ackWithRetry((sig) => ackMessageResult(baseUrl(), runtime.id, runtime.token, idStr, sig, fetchImpl), {
883
+ delaysMs: opts.ackRetryDelaysMs,
884
+ attemptTimeoutMs: opts.ackAttemptTimeoutMs,
885
+ signal,
886
+ })
887
+ .then((r) => {
888
+ if (r !== "failed") {
889
+ ackedIds.add(idStr);
890
+ pending?.delete(idStr);
891
+ } else if (!signal.aborted) {
892
+ process.stderr.write(`${logPrefix} ack failed for message ${idStr} (will retry on reconnect)\n`);
893
+ }
811
894
  })
812
895
  .finally(() => ackInFlightIds.delete(idStr));
813
896
  }
@@ -856,6 +939,23 @@ export async function sseLoop(opts: {
856
939
  }
857
940
  }
858
941
 
942
+ // #751: one turn at a time on this conversation — live messages and injected
943
+ // server events share this chain, so an injected notice never races a turn.
944
+ let turnChain: Promise<unknown> = Promise.resolve();
945
+ function serialTurn<T>(fn: () => Promise<T>): Promise<T> {
946
+ const next = turnChain.then(fn);
947
+ turnChain = next.catch(() => {});
948
+ return next;
949
+ }
950
+ if (opts.injectors) {
951
+ const convId = minted.conversation_id;
952
+ opts.injectors.set(convId, async (text: string) => {
953
+ // A notice turn: the model reads it, its text is never auto-posted (no loop).
954
+ await serialTurn(() => replyForTurn(text, undefined, true));
955
+ });
956
+ signal.addEventListener("abort", () => opts.injectors?.delete(convId), { once: true });
957
+ }
958
+
859
959
  async function handleInboundMessage(msg: ConversationMessage): Promise<boolean> {
860
960
  const idStr = msg.id !== undefined && msg.id !== null ? String(msg.id) : undefined;
861
961
  // TRUTHY check (not `!== undefined`): idStr === "" must yield NaN, not
@@ -908,19 +1008,71 @@ export async function sseLoop(opts: {
908
1008
 
909
1009
  // On every (re)connect the SSE has NO replay — re-read the message list and
910
1010
  // process anything missed. The first pass seeds without replying.
1011
+ /**
1012
+ * #751: the legacy listing returns the OLDEST 500 messages — past that, neither
1013
+ * the first pass (#291 trigger + seed) nor a reconnect's catch-up saw the recent
1014
+ * ones. First pass: the most recent page (`?tail=500`). Afterwards: by id from
1015
+ * the watermark (or below it, an id still pending its ACK), paginated. An older
1016
+ * Worker (no `window` echo) answers the legacy listing, used as before.
1017
+ */
1018
+ async function fetchReconcileWindow(
1019
+ rest: { race<T>(p: Promise<T>): Promise<T>; readonly signal: AbortSignal },
1020
+ ): Promise<{ msgs: Array<Record<string, unknown>>; windowed: boolean }> {
1021
+ const get = (q: MessageWindowQuery) =>
1022
+ rest.race(fetchMessageWindow(baseUrl(), minted.conversation_id, runtime.token, q, rest.signal, fetchImpl));
1023
+ if (!primed || !watermark) {
1024
+ const first = await get({ tail: 500 });
1025
+ if (!first.window && first.messages.length >= 500) {
1026
+ process.stderr.write(`${logPrefix} catch-up INCOMPLETE: this server ignores the window (legacy page of the OLDEST 500)\n`);
1027
+ }
1028
+ return { msgs: first.messages, windowed: false };
1029
+ }
1030
+ const pending = [...(watermark.pendingAcks ?? [])].map(Number).filter((n) => Number.isSafeInteger(n));
1031
+ const floor = bridgeFloorOf(watermark);
1032
+ let cursor = Math.max(0, pending.length > 0 ? Math.min(floor, Math.min(...pending) - 1) : floor);
1033
+ const out: Array<Record<string, unknown>> = [];
1034
+ let windowed = true;
1035
+ for (let page = 0; page < 10; page++) {
1036
+ const res = await get({ after: cursor });
1037
+ out.push(...res.messages);
1038
+ if (!res.window) {
1039
+ windowed = false; // a capped legacy page never sets a floor
1040
+ if (res.messages.length >= 500) process.stderr.write(`${logPrefix} catch-up INCOMPLETE: legacy page of 500\n`);
1041
+ break;
1042
+ }
1043
+ if (res.messages.length < res.window.max) break;
1044
+ const last = Number(res.messages[res.messages.length - 1]?.id);
1045
+ if (!Number.isSafeInteger(last) || last <= cursor) break;
1046
+ cursor = last;
1047
+ }
1048
+ return { msgs: out, windowed };
1049
+ }
1050
+
911
1051
  async function reconcileMessages(): Promise<boolean> {
912
1052
  let msgs: Array<Record<string, unknown>>;
1053
+ let windowed = false;
1054
+ // #751 (Codex, step-07): the REST reconcile runs on its OWN bounded guard — a
1055
+ // frozen Worker delays the live read by at most that bound, never deafens it.
1056
+ const rest = createIdleGuard({ idleMs: opts.catchUpTimeoutMs ?? 10_000, signal });
913
1057
  try {
914
1058
  // #333: catch-up is a REST call to GET /api/conversations/:id/messages,
915
1059
  // which is served by the Worker API (baseUrl) — NOT by minted.ws_url, which
916
1060
  // is the SSE/voice host (the CF tunnel in staging/prod). Using ws_url here
917
1061
  // 404s whenever the SSE host differs from the API host (masked in dev where
918
1062
  // they collapse to one origin). The SSE subscription still uses ws_url.
919
- msgs = await fetchMessagesImpl(baseUrl(), minted.conversation_id, runtime.token);
1063
+ if (opts.fetchMessagesImpl) {
1064
+ msgs = await rest.race(fetchMessagesImpl(baseUrl(), minted.conversation_id, runtime.token));
1065
+ } else {
1066
+ const w = await fetchReconcileWindow(rest);
1067
+ msgs = w.msgs;
1068
+ windowed = w.windowed;
1069
+ }
920
1070
  } catch (err) {
921
1071
  if (err instanceof ConversationTokenExpiredError) throw err;
922
1072
  process.stderr.write(`${logPrefix} catch-up fetch failed: ${safeErrorMessage(err)}\n`);
923
1073
  return false;
1074
+ } finally {
1075
+ rest.dispose();
924
1076
  }
925
1077
  const seed = (msg: ConversationMessage): void => {
926
1078
  const idStr = msg.id !== undefined && msg.id !== null ? String(msg.id) : undefined;
@@ -942,7 +1094,7 @@ export async function sseLoop(opts: {
942
1094
  `${logPrefix} join catch-up: forwarding trigger (most recent of ${msgs.length}), seeded ${plan.seed.length} prior\n`,
943
1095
  );
944
1096
  for (const m of plan.forward) {
945
- if (await handleInboundMessage(m)) return true;
1097
+ if (await serialTurn(() => handleInboundMessage(m))) return true;
946
1098
  }
947
1099
  return false;
948
1100
  }
@@ -953,7 +1105,13 @@ export async function sseLoop(opts: {
953
1105
  seed(msg);
954
1106
  continue;
955
1107
  }
956
- if (await handleInboundMessage(msg)) return true;
1108
+ if (await serialTurn(() => handleInboundMessage(msg))) return true;
1109
+ }
1110
+ // #751: a fully processed window page is covered — raise the contiguous floor
1111
+ // (the bridge handles at most once, so every processed id is settled).
1112
+ if (primed && windowed) {
1113
+ const ids = msgs.map((m) => Number(m.id)).filter((n) => Number.isSafeInteger(n));
1114
+ if (ids.length > 0) bridgeAdvanceFloor(watermark, Math.max(...ids));
957
1115
  }
958
1116
  if (!primed) {
959
1117
  primed = true;
@@ -962,6 +1120,7 @@ export async function sseLoop(opts: {
962
1120
  return false;
963
1121
  }
964
1122
 
1123
+ let guard: IdleGuard | undefined;
965
1124
  while (true) {
966
1125
  try {
967
1126
  if (signal.aborted) throw signal.reason;
@@ -969,7 +1128,11 @@ export async function sseLoop(opts: {
969
1128
  requestHeaders.Accept = "text/event-stream";
970
1129
  process.stderr.write(`${logPrefix} connecting to SSE: ${sseUrl}\n`);
971
1130
 
972
- const resp = await fetchImpl(sseUrl, { headers: requestHeaders, signal });
1131
+ // #751: bound every wait for bytes (headers, then each read) — the
1132
+ // server beats every ~15 s, a longer silence is a dead connection. Only
1133
+ // the WAIT is timed: a model turn between two reads is never counted.
1134
+ guard = createIdleGuard({ idleMs: opts.idleTimeoutMs, signal });
1135
+ const resp = await guard.race(fetchImpl(sseUrl, { headers: requestHeaders, signal: guard.signal }));
973
1136
  if (resp.status === 401) throw new ConversationTokenExpiredError();
974
1137
  if (!resp.ok || !resp.body) throw new Error(`SSE connection failed: HTTP ${resp.status}`);
975
1138
 
@@ -980,7 +1143,7 @@ export async function sseLoop(opts: {
980
1143
  let buffer = "";
981
1144
 
982
1145
  while (true) {
983
- const { done, value } = await reader.read();
1146
+ const { done, value } = await guard.read(reader);
984
1147
  if (done) break;
985
1148
  buffer += decoder.decode(value, { stream: true });
986
1149
 
@@ -1045,7 +1208,7 @@ export async function sseLoop(opts: {
1045
1208
  process.stderr.write(`${logPrefix} ignored malformed message SSE payload: ${safeErrorMessage(err)}\n`);
1046
1209
  continue;
1047
1210
  }
1048
- if (await handleInboundMessage(msg)) return;
1211
+ if (await serialTurn(() => handleInboundMessage(msg))) return;
1049
1212
  }
1050
1213
  }
1051
1214
  }
@@ -1063,7 +1226,10 @@ export async function sseLoop(opts: {
1063
1226
  throw new BridgeShutdownError("conversation token expired", 3);
1064
1227
  }
1065
1228
  process.stderr.write(`${logPrefix} SSE failed: ${String(err)}, retrying in 2s...\n`);
1066
- await sleep(2000);
1229
+ await sleep(opts.reconnectDelayMs ?? 2000);
1230
+ } finally {
1231
+ guard?.dispose();
1232
+ guard = undefined;
1067
1233
  }
1068
1234
  }
1069
1235
  }
@@ -1446,6 +1612,8 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1446
1612
  // abort+restart on re-join. Bounded growth: one `{lastId}` per convId seen —
1447
1613
  // acceptable (consensus reviewers, step-01 invariant).
1448
1614
  const watermarks = new Map<string, BridgeWatermark>();
1615
+ // #751: live conversations' turn injectors (durable server events → a turn).
1616
+ const injectors = new Map<string, (text: string) => Promise<void>>();
1449
1617
  const streamTasks = new Set<Promise<void>>();
1450
1618
  let voiceBaseUrl = "";
1451
1619
  let instanceKey = "";
@@ -1469,6 +1637,7 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1469
1637
  options,
1470
1638
  activeStreams,
1471
1639
  watermarks,
1640
+ injectors,
1472
1641
  parentSignal: shutdown.signal,
1473
1642
  api,
1474
1643
  identityBaseUrl,
@@ -1548,6 +1717,30 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1548
1717
  // #627: an old server may still probe; this agent never beats on the network —
1549
1718
  // its runner answers for it (Python no longer probes a runner-covered agent).
1550
1719
  onBeatNow: () => {},
1720
+ // #751: a durable server event is presented to the model as a turn on the
1721
+ // conversation it concerns (its auto-posted replies are DM messages too, with
1722
+ // their own deadline — a Codex replying to a deaf lead must learn it). Only
1723
+ // then is it ACKed; with no live conversation it stays un-ACKed and the
1724
+ // server re-pushes it.
1725
+ // #751: confirm this launch once the channel is connected server-side.
1726
+ onConnected: createLaunchConfirmer({
1727
+ jobName: process.env.VIBER_JOB_NAME,
1728
+ post: (job, sig) => postLaunched(baseUrl(), identity.instanceKey, identity.instanceToken, job, sig),
1729
+ log: (l) => process.stderr.write(`${logPrefix} ${l}`),
1730
+ }),
1731
+ onEvent: createServerEventHandler({
1732
+ ack: (eventId) => ackServerEvent(baseUrl(), identity.instanceKey, identity.instanceToken, eventId),
1733
+ surface: async (ev, text) => {
1734
+ const convId = typeof ev.data.conversation_id === "string" ? ev.data.conversation_id : "";
1735
+ // Only on the conversation it concerns — never on an unrelated one (the
1736
+ // user's, say). Not live: no ACK, the server re-pushes it later.
1737
+ const inject = convId ? injectors.get(convId) : undefined;
1738
+ if (!inject) throw new Error(`conversation ${convId || "?"} is not live here`);
1739
+ process.stderr.write(`${logPrefix} server event ${ev.eventId} -> turn on ${convId || "a live conversation"}\n`);
1740
+ await inject(`[Viber system notice — not from a person] ${text}`);
1741
+ },
1742
+ log: (l) => process.stderr.write(`${logPrefix} ${l}`),
1743
+ }),
1551
1744
  },
1552
1745
  );
1553
1746
  controlStream.firstJoin.catch(() => {});
@@ -17,6 +17,7 @@
17
17
  * Claude specifics) so both bridges can consume it and it can be unit-tested with
18
18
  * a mock fetch.
19
19
  */
20
+ import { createIdleGuard, SseHttpError } from "./sse_idle.js";
20
21
  import { cfAccessHeaders } from "./cfAccess.js";
21
22
  import type { ConversationMintResponse } from "./conversation.js";
22
23
 
@@ -29,9 +30,17 @@ export interface ControlEvent {
29
30
  /** Build the instance control-stream SSE URL. `presence=runner` (#627): this agent's
30
31
  * runner vouches for it, so its connect must not count as liveness on the server. */
31
32
  export function buildControlStreamUrl(baseUrl: string, instanceId: string): string {
32
- return `${baseUrl}/api/instances/${instanceId}/events?presence=runner`;
33
+ return `${baseUrl}/api/instances/${instanceId}/events?presence=runner&caps=${CHANNEL_CAPS}`;
33
34
  }
34
35
 
36
+ /**
37
+ * #751: what this channel can do, declared on every control connect (the server
38
+ * rewrites it each time): it ACKs agent DMs (`dm-ack`) and handles durable server
39
+ * events (`events`). A server only arms DM delivery deadlines / queues events for
40
+ * instances that declared them — an older channel gets neither.
41
+ */
42
+ export const CHANNEL_CAPS = "dm-ack,events";
43
+
35
44
  /**
36
45
  * POST /api/instances/:id/heartbeat — instance control-stream liveness (#311).
37
46
  *
@@ -101,6 +110,8 @@ export interface ControlStreamOptions {
101
110
  signal?: AbortSignal;
102
111
  /** Injectable for tests; defaults to global fetch. */
103
112
  fetchImpl?: typeof fetch;
113
+ /** Idle deadline per wait for bytes (#751). Default `SSE_IDLE_TIMEOUT_MS`. */
114
+ idleTimeoutMs?: number;
104
115
  }
105
116
 
106
117
  /**
@@ -126,27 +137,32 @@ export async function* subscribeControlStream(
126
137
  const doFetch = opts.fetchImpl ?? fetch;
127
138
  const url = buildControlStreamUrl(opts.getBaseUrl(), opts.instanceId);
128
139
 
129
- const resp = await doFetch(url, {
130
- headers: {
131
- Authorization: `Bearer ${opts.instanceToken}`,
132
- Accept: "text/event-stream",
133
- "Cache-Control": "no-cache",
134
- ...cfAccessHeaders(),
135
- },
136
- signal: opts.signal,
137
- });
138
- if (resp.status === 401) throw new ControlStreamAuthError();
139
- if (!resp.ok || !resp.body) {
140
- throw new Error(`control stream connection failed: HTTP ${resp.status}`);
141
- }
140
+ // #751: a wait for bytes longer than the idle deadline (server beats every
141
+ // ~15 s) means a dead connection — throw so the caller reconnects, instead of
142
+ // parking here forever on a half-open socket.
143
+ const guard = createIdleGuard({ idleMs: opts.idleTimeoutMs, signal: opts.signal });
144
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
145
+ try {
146
+ const resp = await guard.race(
147
+ doFetch(url, {
148
+ headers: {
149
+ Authorization: `Bearer ${opts.instanceToken}`,
150
+ Accept: "text/event-stream",
151
+ "Cache-Control": "no-cache",
152
+ ...cfAccessHeaders(),
153
+ },
154
+ signal: guard.signal,
155
+ }),
156
+ );
157
+ if (resp.status === 401) throw new ControlStreamAuthError();
158
+ if (!resp.ok || !resp.body) throw new SseHttpError(resp.status, "control stream");
142
159
 
143
- const reader = resp.body.getReader();
144
- const decoder = new TextDecoder();
145
- let buffer = "";
160
+ reader = resp.body.getReader();
161
+ const decoder = new TextDecoder();
162
+ let buffer = "";
146
163
 
147
- try {
148
164
  while (true) {
149
- const { done, value } = await reader.read();
165
+ const { done, value } = await guard.read(reader);
150
166
  if (done) break;
151
167
  // Normalise CRLF → LF: the SSE spec allows \r\n line/record separators and
152
168
  // some servers (incl. Cloudflare) emit them; without this the `\n\n` split
@@ -170,11 +186,12 @@ export async function* subscribeControlStream(
170
186
  }
171
187
  }
172
188
  } finally {
189
+ guard.dispose();
173
190
  // Release the reader (and cancel the body) so an early `break`/`return` by
174
191
  // the consumer — e.g. waitForJoin resolving on the first join — or an abort
175
192
  // doesn't leak the underlying connection until GC.
176
193
  try {
177
- await reader.cancel();
194
+ await reader?.cancel();
178
195
  } catch {
179
196
  /* already closed / aborted */
180
197
  }
@@ -274,6 +291,13 @@ export interface PersistentControlStreamHandlers {
274
291
  * force-offlined at the probe deadline).
275
292
  */
276
293
  onBeatNow?: () => void;
294
+ /**
295
+ * #751: any OTHER named event (delivery_failed, delivery_recovered,
296
+ * agent_connected, …) with its raw `data` — previously dropped silently.
297
+ */
298
+ onEvent?: (event: string, data: string) => void;
299
+ /** #751: called on EVERY `connected` (each reconnect) — the stream is live server-side. */
300
+ onConnected?: () => void;
277
301
  log?: (msg: string) => void;
278
302
  /** Backoff before reconnecting after a drop / clean end. Default 2000ms. */
279
303
  reconnectDelayMs?: number;
@@ -342,6 +366,7 @@ export function runPersistentControlStream(
342
366
  try {
343
367
  for await (const ev of subscribeControlStream(opts)) {
344
368
  if (ev.event === "connected") {
369
+ handlers.onConnected?.();
345
370
  if (!announcedOnline) {
346
371
  announcedOnline = true;
347
372
  log("[control-stream] online — instance control stream connected\n");
@@ -357,7 +382,10 @@ export function runPersistentControlStream(
357
382
  handlers.onBeatNow?.();
358
383
  continue;
359
384
  }
360
- if (ev.event !== "join") continue; // ping / unknown (connected handled above)
385
+ if (ev.event !== "join") {
386
+ if (ev.event !== "ping") handlers.onEvent?.(ev.event, ev.data);
387
+ continue;
388
+ }
361
389
  const minted = parseJoinPayload(ev.data, log);
362
390
  if (!minted) continue;
363
391
  handlers.onJoin?.(minted);