viber-channel 0.8.46 → 0.8.48

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,264 @@
1
+ /**
2
+ * Catch-up for the Claude channel's MAIN conversation stream (#751 step-02).
3
+ *
4
+ * The conversation SSE has no replay: a message saved while the stream was down
5
+ * (server restart, idle-timeout reconnect) was never delivered to the agent, and
6
+ * nothing said so. DM streams already re-read the message list on every
7
+ * (re)connect (#291/#427); this gives the main conversation the same guarantee.
8
+ *
9
+ * FLOOR (fixed, never "the highest id seen live" — a missed 101 below a live 102
10
+ * would be lost, Codex review):
11
+ * - primed BEFORE the first SSE open with `?tail=1`: the Worker's own newest id,
12
+ * no clock comparison at all. Nothing older is ever replayed (startup
13
+ * unchanged). Every connect then catches up from the floor — the first one too,
14
+ * which covers the prime→open gap and any failed live delivery;
15
+ * - if that prime failed, the next successful one uses `?tail=1&before_ts=` the
16
+ * SERVER time of the first connect (its `Date` header) minus
17
+ * {@link PRIME_MARGIN_S}. The margin biases toward REPLAY: at worst the last
18
+ * minute before the first connect is delivered once more; a message of the
19
+ * outage is never put under the floor by clock skew (Opus review).
20
+ *
21
+ * DELIVERY: in id order, through `?after=` pages (the legacy listing returns the
22
+ * OLDEST 500 rows only). An id is marked delivered only AFTER the delivery
23
+ * succeeded, so a failed model notification is retried on the next reconnect.
24
+ * Live delivery shares the same set. Messages posted by any instance id this
25
+ * process has carried are skipped (self-echo across a re-registration).
26
+ *
27
+ * OLDER WORKER (no `window` echo): prime from the listing only if it is not
28
+ * truncated; otherwise catch-up is DISABLED for the session and said in the log
29
+ * — never replay an unbounded history.
30
+ */
31
+
32
+ export const PRIME_MARGIN_S = 60;
33
+ /** Bound of the pre-open prime, on its own guard: it must not delay the SSE long. */
34
+ export const CATCHUP_PRIME_TIMEOUT_MS = 10_000;
35
+ const MAX_PAGES = 10;
36
+
37
+ export interface CatchUpMessage {
38
+ id?: unknown;
39
+ timestamp?: unknown;
40
+ sender_instance_id?: unknown;
41
+ [k: string]: unknown;
42
+ }
43
+
44
+ export interface WindowQuery {
45
+ after?: number;
46
+ tail?: number;
47
+ beforeTs?: number;
48
+ }
49
+
50
+ export interface WindowResult {
51
+ messages: CatchUpMessage[];
52
+ window: { max: number } | null;
53
+ }
54
+
55
+ function numericId(raw: unknown): number | null {
56
+ if (raw === undefined || raw === null || raw === "") return null;
57
+ const n = Number(raw);
58
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
59
+ }
60
+
61
+ const LEGACY_MAX = 500;
62
+
63
+ export class MainConversationCatchUp {
64
+ private connects = 0;
65
+ private firstConnectServerTs: number | undefined;
66
+ private primed = false;
67
+ private disabled = false;
68
+ private floor = 0;
69
+ /** Ids at or below this are pruned from `delivered` at the NEXT connect. */
70
+ private pruneBelow = 0;
71
+ private readonly delivered = new Set<number>();
72
+
73
+ /** Record a successful SSE connect and the server time it carried (seconds). */
74
+ noteConnect(serverTs: number | undefined): void {
75
+ this.connects += 1;
76
+ if (this.connects === 1) this.firstConnectServerTs = serverTs;
77
+ }
78
+
79
+ /**
80
+ * Only what was actually delivered — never inferred from the floor: a message
81
+ * published between the SSE open and the prime's `tail` answer sits under the
82
+ * floor AND in the live buffer, and must still be delivered live (Codex).
83
+ */
84
+ isDelivered(rawId: unknown): boolean {
85
+ const id = numericId(rawId);
86
+ return id !== null && this.delivered.has(id);
87
+ }
88
+
89
+ /** Mark AFTER a successful delivery (live or catch-up). */
90
+ markDelivered(rawId: unknown): void {
91
+ const id = numericId(rawId);
92
+ if (id !== null) this.delivered.add(id);
93
+ }
94
+
95
+ /**
96
+ * Run on every successful (re)connect, BEFORE reading live events, after
97
+ * {@link noteConnect}. Never throws. Returns how many messages were delivered.
98
+ */
99
+ async onConnected(
100
+ fetchWindow: (q: WindowQuery) => Promise<WindowResult>,
101
+ deliver: (msg: CatchUpMessage) => Promise<void>,
102
+ isOwn: (senderInstanceId: unknown) => boolean,
103
+ log: (line: string) => void = () => {},
104
+ ): Promise<number> {
105
+ if (this.disabled) return 0;
106
+ // Prune what the PREVIOUS connection settled: its live buffer is gone, so
107
+ // those ids can no longer come back live and need no dedup entry.
108
+ for (const id of this.delivered) if (id <= this.pruneBelow) this.delivered.delete(id);
109
+ try {
110
+ // Normally primed BEFORE the SSE opened (primeBeforeOpen). If that failed,
111
+ // prime now from the first connect's server time (biased to replay).
112
+ if (!this.primed) {
113
+ const ok = await this.prime(fetchWindow, false, log);
114
+ if (!ok) return 0;
115
+ }
116
+ // Always catch up — on the first connect too: it covers what was saved
117
+ // between the prime and the SSE open, and a live delivery that failed is
118
+ // still above the floor, so the next connect retries it (Codex).
119
+ return await this.catchUp(fetchWindow, deliver, isOwn, log);
120
+ } catch (err) {
121
+ log(`[viber-channel] main catch-up failed: ${err instanceof Error ? err.message : String(err)}\n`);
122
+ return 0;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Prime the floor BEFORE the very first SSE open, at the Worker's tail (no
128
+ * clock involved). Everything saved after it — including a message that
129
+ * arrives in the live buffer of the first connection — is then above the
130
+ * floor, so a failed live delivery is retried by the next catch-up. No-op once
131
+ * primed, or after the first connect (onConnected then primes from the bound).
132
+ * Never throws.
133
+ */
134
+ async primeBeforeOpen(fetchWindow: (q: WindowQuery) => Promise<WindowResult>, log: (line: string) => void = () => {}): Promise<void> {
135
+ if (this.primed || this.disabled || this.connects > 0) return;
136
+ try {
137
+ await this.prime(fetchWindow, true, log);
138
+ } catch (err) {
139
+ log(`[viber-channel] main catch-up prime failed: ${err instanceof Error ? err.message : String(err)}\n`);
140
+ }
141
+ }
142
+
143
+ private async prime(
144
+ fetchWindow: (q: WindowQuery) => Promise<WindowResult>,
145
+ isFirst: boolean,
146
+ log: (line: string) => void,
147
+ ): Promise<boolean> {
148
+ const bound =
149
+ !isFirst && this.firstConnectServerTs !== undefined ? this.firstConnectServerTs - PRIME_MARGIN_S : undefined;
150
+ if (!isFirst && bound === undefined) {
151
+ log("[viber-channel] main catch-up: no server time from the first connect — priming at the current tail\n");
152
+ }
153
+ const res = await fetchWindow(bound !== undefined ? { tail: 1, beforeTs: bound } : { tail: 1 });
154
+ let ids = res.messages.map((m) => numericId(m.id)).filter((n): n is number => n !== null);
155
+ if (!res.window) {
156
+ // Older Worker: the legacy listing (oldest 500, query ignored).
157
+ if (res.messages.length >= LEGACY_MAX) {
158
+ this.disabled = true;
159
+ log("[viber-channel] main catch-up DISABLED: this server ignores the window and the history exceeds one page\n");
160
+ return false;
161
+ }
162
+ if (bound !== undefined) {
163
+ ids = res.messages
164
+ .filter((m) => typeof m.timestamp === "number" && (m.timestamp as number) < bound)
165
+ .map((m) => numericId(m.id))
166
+ .filter((n): n is number => n !== null);
167
+ }
168
+ }
169
+ this.floor = ids.length > 0 ? Math.max(...ids) : 0;
170
+ this.primed = true;
171
+ return true;
172
+ }
173
+
174
+ private async catchUp(
175
+ fetchWindow: (q: WindowQuery) => Promise<WindowResult>,
176
+ deliver: (msg: CatchUpMessage) => Promise<void>,
177
+ isOwn: (senderInstanceId: unknown) => boolean,
178
+ log: (line: string) => void,
179
+ ): Promise<number> {
180
+ let cursor = this.floor;
181
+ let delivered = 0;
182
+ for (let page = 0; page < MAX_PAGES; page++) {
183
+ const res = await fetchWindow({ after: cursor });
184
+ const rows = res.messages
185
+ .map((m) => ({ m, id: numericId(m.id) }))
186
+ .filter((x): x is { m: CatchUpMessage; id: number } => x.id !== null && x.id > cursor)
187
+ .sort((a, b) => a.id - b.id);
188
+ for (const { m, id } of rows) {
189
+ cursor = id;
190
+ if (this.delivered.has(id) || isOwn(m.sender_instance_id)) continue;
191
+ try {
192
+ await deliver(m);
193
+ this.delivered.add(id);
194
+ delivered += 1;
195
+ } catch (err) {
196
+ // Keep order: stop here, the next reconnect retries from the floor.
197
+ log(
198
+ `[viber-channel] main catch-up: delivery of ${id} failed (${err instanceof Error ? err.message : String(err)}) — retried on next reconnect\n`,
199
+ );
200
+ return delivered;
201
+ }
202
+ }
203
+ // The whole page is delivered or skipped: advance the floor NOW, so a
204
+ // catch-up cut at MAX_PAGES resumes after it instead of re-reading the same
205
+ // pages on every reconnect (Codex). Never derived from live ids.
206
+ if (cursor > this.floor) this.floor = cursor;
207
+ const max = res.window ? res.window.max : LEGACY_MAX;
208
+ if (!res.window) {
209
+ if (res.messages.length >= LEGACY_MAX) {
210
+ log("[viber-channel] main catch-up INCOMPLETE: this server ignores the window (legacy page of 500)\n");
211
+ }
212
+ break;
213
+ }
214
+ if (res.messages.length < max) break;
215
+ if (page === MAX_PAGES - 1) {
216
+ log(`[viber-channel] main catch-up stopped after ${MAX_PAGES} pages — the rest arrives on the next reconnect\n`);
217
+ }
218
+ }
219
+ // Bounded memory: ids under the floor are pruned at the next connect.
220
+ this.pruneBelow = this.floor;
221
+ if (delivered > 0) log(`[viber-channel] main catch-up delivered ${delivered} missed message(s)\n`);
222
+ return delivered;
223
+ }
224
+ }
225
+
226
+ /**
227
+ * The main stream's connect sequence (#751), extracted so the REAL ordering is
228
+ * testable: prime (own guard) → open the SSE (stream guard) → catch-up (own
229
+ * guard) → hand back the response for the live read. The two REST phases never
230
+ * touch the stream guard: a frozen Worker delays the live read by at most
231
+ * `restTimeoutMs` per phase and never aborts a healthy stream (Codex review).
232
+ */
233
+ export async function openWithCatchUp(opts: {
234
+ catchUp: MainConversationCatchUp;
235
+ /** The stream's idle guard (bounds the SSE open and, later, each read). */
236
+ streamGuard: { race<T>(p: Promise<T>): Promise<T>; readonly signal: AbortSignal };
237
+ open: (signal: AbortSignal) => Promise<Response>;
238
+ fetchWindow: (q: WindowQuery, signal: AbortSignal) => Promise<WindowResult>;
239
+ deliver: (msg: CatchUpMessage) => Promise<void>;
240
+ isOwn: (senderInstanceId: unknown) => boolean;
241
+ makeRestGuard: () => { race<T>(p: Promise<T>): Promise<T>; readonly signal: AbortSignal; dispose(): void };
242
+ log?: (line: string) => void;
243
+ /** Called with the open response before the catch-up (status checks, logging). */
244
+ onOpen?: (resp: Response) => Promise<void> | void;
245
+ }): Promise<Response> {
246
+ const log = opts.log ?? (() => {});
247
+ const prime = opts.makeRestGuard();
248
+ try {
249
+ await opts.catchUp.primeBeforeOpen((q) => prime.race(opts.fetchWindow(q, prime.signal)), log);
250
+ } finally {
251
+ prime.dispose();
252
+ }
253
+ const resp = await opts.streamGuard.race(opts.open(opts.streamGuard.signal));
254
+ await opts.onOpen?.(resp);
255
+ const serverDate = Date.parse(resp.headers.get("date") ?? "");
256
+ opts.catchUp.noteConnect(Number.isFinite(serverDate) ? serverDate / 1000 : undefined);
257
+ const rest = opts.makeRestGuard();
258
+ try {
259
+ await opts.catchUp.onConnected((q) => rest.race(opts.fetchWindow(q, rest.signal)), opts.deliver, opts.isOwn, log);
260
+ } finally {
261
+ rest.dispose();
262
+ }
263
+ return resp;
264
+ }
package/lib/messages.ts CHANGED
@@ -84,10 +84,12 @@ export async function fetchMessages(
84
84
  baseUrl: string,
85
85
  conversationId: string,
86
86
  conversationToken: string,
87
+ signal?: AbortSignal,
87
88
  ): Promise<Array<Record<string, unknown>>> {
88
89
  const resp = await fetch(`${baseUrl}/api/conversations/${conversationId}/messages`, {
89
90
  method: "GET",
90
91
  headers: { Authorization: `Bearer ${conversationToken}`, ...cfAccessHeaders() },
92
+ signal,
91
93
  });
92
94
  if (resp.status === 401) throw new ConversationTokenExpiredError();
93
95
  if (!resp.ok) throw new Error(`fetchMessages failed: HTTP ${resp.status}`);
@@ -95,6 +97,48 @@ export async function fetchMessages(
95
97
  return Array.isArray(body.messages) ? body.messages : [];
96
98
  }
97
99
 
100
+ /** A catch-up window query (#751); see viber-api `listMessagesWindow`. */
101
+ export interface MessageWindowQuery {
102
+ after?: number;
103
+ tail?: number;
104
+ beforeTs?: number;
105
+ }
106
+
107
+ export interface MessageWindowResult {
108
+ messages: Array<Record<string, unknown>>;
109
+ /** The server's echo of the applied window; null = an older Worker ignored it. */
110
+ window: { max: number } | null;
111
+ }
112
+
113
+ /**
114
+ * GET /api/conversations/:id/messages with a catch-up window (#751), ordered by
115
+ * id. An older Worker ignores the query and returns the legacy listing (oldest
116
+ * 500) WITHOUT a `window` echo — the caller must then not trust it as a window.
117
+ */
118
+ export async function fetchMessageWindow(
119
+ baseUrl: string,
120
+ conversationId: string,
121
+ conversationToken: string,
122
+ q: MessageWindowQuery,
123
+ signal?: AbortSignal,
124
+ fetchImpl: typeof fetch = fetch,
125
+ ): Promise<MessageWindowResult> {
126
+ const params = new URLSearchParams();
127
+ if (q.after !== undefined) params.set("after", String(q.after));
128
+ if (q.tail !== undefined) params.set("tail", String(q.tail));
129
+ if (q.beforeTs !== undefined) params.set("before_ts", String(q.beforeTs));
130
+ const resp = await fetchImpl(`${baseUrl}/api/conversations/${conversationId}/messages?${params}`, {
131
+ method: "GET",
132
+ headers: { Authorization: `Bearer ${conversationToken}`, ...cfAccessHeaders() },
133
+ signal,
134
+ });
135
+ if (resp.status === 401) throw new ConversationTokenExpiredError();
136
+ if (!resp.ok) throw new Error(`fetchMessageWindow failed: HTTP ${resp.status}`);
137
+ const body = (await resp.json()) as { messages?: Array<Record<string, unknown>>; window?: { max?: number } };
138
+ const w = body.window && typeof body.window === "object" ? { max: Number(body.window.max) || 500 } : null;
139
+ return { messages: Array.isArray(body.messages) ? body.messages : [], window: w };
140
+ }
141
+
98
142
  /**
99
143
  * POST /api/conversations/:id/messages/:messageId/ack — read-acknowledgement (#346).
100
144
  *
@@ -114,6 +158,23 @@ export async function ackMessage(
114
158
  signal?: AbortSignal,
115
159
  fetchImpl: typeof fetch = fetch,
116
160
  ): Promise<boolean> {
161
+ return (await ackMessageResult(baseUrl, conversationId, conversationToken, messageId, signal, fetchImpl)) === "ok";
162
+ }
163
+
164
+ /**
165
+ * Outcome of one ACK attempt (#751): `ok`; `rejected` — a 4xx other than 408/429,
166
+ * i.e. the Worker will never accept this ACK (message not ackable for this
167
+ * instance, e.g. an agent message in a non-DM room), so retrying is pointless;
168
+ * `failed` — network error, 5xx, 408 or 429: worth retrying. Never throws.
169
+ */
170
+ export async function ackMessageResult(
171
+ baseUrl: string,
172
+ conversationId: string,
173
+ conversationToken: string,
174
+ messageId: string | number,
175
+ signal?: AbortSignal,
176
+ fetchImpl: typeof fetch = fetch,
177
+ ): Promise<"ok" | "rejected" | "failed"> {
117
178
  const url = `${baseUrl}/api/conversations/${conversationId}/messages/${messageId}/ack`;
118
179
  try {
119
180
  const resp = await fetchImpl(url, {
@@ -121,9 +182,11 @@ export async function ackMessage(
121
182
  headers: { Authorization: `Bearer ${conversationToken}`, ...cfAccessHeaders() },
122
183
  signal,
123
184
  });
124
- return resp.ok;
185
+ if (resp.ok) return "ok";
186
+ const s = resp.status;
187
+ return s >= 400 && s < 500 && s !== 408 && s !== 429 ? "rejected" : "failed";
125
188
  } catch {
126
- return false;
189
+ return "failed";
127
190
  }
128
191
  }
129
192
 
@@ -18,6 +18,7 @@ import { readFileSync, rmSync } from "node:fs";
18
18
  import { randomBytes } from "node:crypto";
19
19
  import { join } from "node:path";
20
20
  import { cfAccessHeaders } from "./cfAccess.js";
21
+ import { createIdleGuard } from "./sse_idle.js";
21
22
  import { isTrustedViberOrigin } from "./urls.js";
22
23
  import { type ExecDeps, reconcileOnce, runnerIdentity } from "./runner_exec.js";
23
24
  import { requestPresenceResync, runRosterBeat } from "./runner_roster.js";
@@ -271,45 +272,54 @@ async function streamOnce(
271
272
  deps: ExecDeps = {},
272
273
  hooks: RunnerHooks = {},
273
274
  ): Promise<boolean> {
274
- const resp = await fetch(`${auth.base_url}/api/runners/${auth.runner_id}/events`, {
275
- method: "GET",
276
- redirect: "error", // never follow a redirect carrying the bearer (Codex review)
277
- signal,
278
- headers: {
279
- Authorization: `Bearer ${auth.runner_token}`,
280
- Accept: "text/event-stream",
281
- "Cache-Control": "no-cache",
282
- ...cfAccessHeaders(),
283
- },
284
- });
285
- if (resp.status === 401) return true; // revoked — terminal
286
- if (!resp.ok || !resp.body) {
287
- throw new Error(`control stream HTTP ${resp.status}`);
288
- }
289
- hooks.onConnection?.(true);
275
+ // #751: the server pings every ~15 s; a longer wait for bytes (fetch or read)
276
+ // means a dead connection — throw so the loop reconnects instead of parking.
277
+ const guard = createIdleGuard({ signal });
278
+ try {
279
+ const resp = await guard.race(
280
+ fetch(`${auth.base_url}/api/runners/${auth.runner_id}/events`, {
281
+ method: "GET",
282
+ redirect: "error", // never follow a redirect carrying the bearer (Codex review)
283
+ signal: guard.signal,
284
+ headers: {
285
+ Authorization: `Bearer ${auth.runner_token}`,
286
+ Accept: "text/event-stream",
287
+ "Cache-Control": "no-cache",
288
+ ...cfAccessHeaders(),
289
+ },
290
+ }),
291
+ );
292
+ if (resp.status === 401) return true; // revoked — terminal
293
+ if (!resp.ok || !resp.body) {
294
+ throw new Error(`control stream HTTP ${resp.status}`);
295
+ }
296
+ hooks.onConnection?.(true);
290
297
 
291
- const reader = resp.body.getReader();
292
- const decoder = new TextDecoder();
293
- let buffer = "";
294
- while (true) {
295
- const { value, done } = await reader.read();
296
- if (done) return false; // server closed — recoverable, reconnect
297
- buffer += decoder.decode(value, { stream: true });
298
- // Parse complete SSE frames (blank-line separated).
299
- let sep: number;
300
- // biome-ignore lint/suspicious/noAssignInExpressions: standard SSE frame split
301
- while ((sep = buffer.indexOf("\n\n")) !== -1) {
302
- const frame = buffer.slice(0, sep);
303
- buffer = buffer.slice(sep + 2);
304
- const eventLine = frame.split("\n").find((l) => l.startsWith("event:"));
305
- const event = eventLine?.slice("event:".length).trim();
306
- if (event === "stop") return false; // server asked us to unwind
307
- // Any wake-poke ("spawn_pending" etc.) or reconnect → reconcile-pull. The
308
- // event is a HINT; the durable table is the truth. safeReconcile is
309
- // coalesced + self-contained (never throws into this stream).
310
- if (event && event !== "ping" && event !== "connected") {
311
- await safeReconcile(auth, deps);
298
+ const reader = resp.body.getReader();
299
+ const decoder = new TextDecoder();
300
+ let buffer = "";
301
+ while (true) {
302
+ const { value, done } = await guard.read(reader);
303
+ if (done) return false; // server closed — recoverable, reconnect
304
+ buffer += decoder.decode(value, { stream: true });
305
+ // Parse complete SSE frames (blank-line separated).
306
+ let sep: number;
307
+ // biome-ignore lint/suspicious/noAssignInExpressions: standard SSE frame split
308
+ while ((sep = buffer.indexOf("\n\n")) !== -1) {
309
+ const frame = buffer.slice(0, sep);
310
+ buffer = buffer.slice(sep + 2);
311
+ const eventLine = frame.split("\n").find((l) => l.startsWith("event:"));
312
+ const event = eventLine?.slice("event:".length).trim();
313
+ if (event === "stop") return false; // server asked us to unwind
314
+ // Any wake-poke ("spawn_pending" etc.) or reconnect → reconcile-pull. The
315
+ // event is a HINT; the durable table is the truth. safeReconcile is
316
+ // coalesced + self-contained (never throws into this stream).
317
+ if (event && event !== "ping" && event !== "connected") {
318
+ await safeReconcile(auth, deps);
319
+ }
312
320
  }
313
321
  }
322
+ } finally {
323
+ guard.dispose();
314
324
  }
315
325
  }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Durable server→instance events (#751), received on the instance control stream.
3
+ *
4
+ * delivery_failed — a DM this agent sent was NOT acknowledged by its
5
+ * recipient within the deadline (decroché or absent);
6
+ * delivery_recovered — the same DM was acknowledged after all;
7
+ * agent_connected — an agent this one launched has its channel connected
8
+ * server-side (step-05).
9
+ *
10
+ * The server keeps each event until the instance ACKs it and re-pushes it until
11
+ * then, so the same event can arrive twice: it is shown to the model ONCE per
12
+ * event id (in-process dedup) and ACKed every time it arrives.
13
+ */
14
+ import { cfAccessHeaders } from "./cfAccess.js";
15
+
16
+ export const DURABLE_EVENTS = new Set(["delivery_failed", "delivery_unverified", "delivery_recovered", "agent_connected"]);
17
+
18
+ export interface ServerEvent {
19
+ event: string;
20
+ eventId: string;
21
+ data: Record<string, unknown>;
22
+ }
23
+
24
+ /** Parse a control-stream event into a durable server event, or null. */
25
+ export function parseServerEvent(event: string, raw: string): ServerEvent | null {
26
+ if (!DURABLE_EVENTS.has(event)) return null;
27
+ let data: Record<string, unknown>;
28
+ try {
29
+ const parsed = JSON.parse(raw) as unknown;
30
+ if (!parsed || typeof parsed !== "object") return null;
31
+ data = parsed as Record<string, unknown>;
32
+ } catch {
33
+ return null;
34
+ }
35
+ const eventId = typeof data.event_id === "string" ? data.event_id : "";
36
+ if (!eventId) return null;
37
+ return { event, eventId, data };
38
+ }
39
+
40
+ const str = (v: unknown, fallback = "?"): string => (typeof v === "string" && v ? v : typeof v === "number" ? String(v) : fallback);
41
+
42
+ /**
43
+ * The text the agent reads. A transport fact, never a guess about the model:
44
+ * "not acknowledged" means the recipient's CHANNEL did not confirm receipt.
45
+ */
46
+ export function describeServerEvent(ev: ServerEvent): string {
47
+ const d = ev.data;
48
+ const who = `${str(d.recipient_label, "the recipient")} (${str(d.recipient_instance_id)})`;
49
+ switch (ev.event) {
50
+ case "delivery_failed":
51
+ return (
52
+ `Delivery receipt missing: your message ${str(d.message_id)} to ${who} was not acknowledged by its channel ` +
53
+ `within ${str(d.deadline_s, "the")} s — the recipient is unhooked or absent. The message is kept in the DM ` +
54
+ `(${str(d.conversation_id)}) and will be caught up when its channel reconnects: do NOT resend it. ` +
55
+ `Further unacknowledged messages to this recipient are not reported again until it acknowledges one.` +
56
+ (typeof d.excerpt === "string" && d.excerpt ? ` Excerpt: "${d.excerpt}"` : "")
57
+ );
58
+ case "delivery_unverified":
59
+ return (
60
+ `Delivery not verifiable: your message ${str(d.message_id)} to ${who} got no transport receipt within ` +
61
+ `${str(d.deadline_s, "the")} s, and that recipient's channel has not declared it can acknowledge (never ` +
62
+ `connected, or an older version). It may or may not have arrived. The message is kept in the DM ` +
63
+ `(${str(d.conversation_id)}): do NOT resend it blindly. Further such cases for this recipient are not ` +
64
+ `reported again until it acknowledges one.` +
65
+ (typeof d.excerpt === "string" && d.excerpt ? ` Excerpt: "${d.excerpt}"` : "")
66
+ );
67
+ case "delivery_recovered":
68
+ return `Delivery recovered: your message ${str(d.message_id)} to ${who} has now been acknowledged by its channel.`;
69
+ case "agent_connected":
70
+ return (
71
+ `Agent connected: the channel of ${str(d.label, "the agent you launched")} (${str(d.instance_id)}) is connected ` +
72
+ `server-side (launch ${str(d.launch_id)}). This confirms the channel, not that the agent is ready to answer.`
73
+ );
74
+ default:
75
+ return `Server event ${ev.event}`;
76
+ }
77
+ }
78
+
79
+ /** POST the ACK of one event. Never throws; true on success. */
80
+ export async function ackServerEvent(
81
+ baseUrl: string,
82
+ instanceId: string,
83
+ instanceToken: string,
84
+ eventId: string,
85
+ fetchImpl: typeof fetch = fetch,
86
+ ): Promise<boolean> {
87
+ try {
88
+ const resp = await fetchImpl(
89
+ `${baseUrl}/api/instances/${instanceId}/events/${encodeURIComponent(eventId)}/ack`,
90
+ {
91
+ method: "POST",
92
+ headers: { Authorization: `Bearer ${instanceToken}`, ...cfAccessHeaders() },
93
+ signal: AbortSignal.timeout(10_000),
94
+ },
95
+ );
96
+ return resp.ok || resp.status === 404; // 404: already gone — nothing left to ack
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Per-process handler (Codex review): an event is ACKed only AFTER it was shown
104
+ * to the model — an ACK before a failed presentation would stop the server's
105
+ * re-push and lose the callback. Each id is presented once (`shown`), and a
106
+ * presentation in flight is not started twice (`inFlight`); a re-push of an
107
+ * already-shown id only re-sends the ACK (the previous one may have failed).
108
+ * `surface` presents the text to the model (Claude: an MCP notification; a
109
+ * bridge: a turn on the conversation concerned).
110
+ */
111
+ export function createServerEventHandler(deps: {
112
+ ack: (eventId: string) => Promise<boolean>;
113
+ surface: (ev: ServerEvent, text: string) => Promise<void> | void;
114
+ log?: (line: string) => void;
115
+ }): (event: string, raw: string) => void {
116
+ const shown = new Set<string>();
117
+ const inFlight = new Set<string>();
118
+ const ackLogged = (id: string) =>
119
+ void deps.ack(id).then((ok) => {
120
+ if (!ok) deps.log?.(`[server-event] ACK of ${id} failed — the server will re-push it\n`);
121
+ });
122
+ return (event, raw) => {
123
+ const ev = parseServerEvent(event, raw);
124
+ if (!ev) return;
125
+ if (shown.has(ev.eventId)) {
126
+ ackLogged(ev.eventId);
127
+ return;
128
+ }
129
+ if (inFlight.has(ev.eventId)) return;
130
+ inFlight.add(ev.eventId);
131
+ const text = describeServerEvent(ev);
132
+ void Promise.resolve()
133
+ .then(() => deps.surface(ev, text))
134
+ .then(() => {
135
+ shown.add(ev.eventId);
136
+ ackLogged(ev.eventId);
137
+ })
138
+ .catch((err) => {
139
+ // Not shown, not ACKed: the server re-pushes it and we try again.
140
+ deps.log?.(`[server-event] could not surface ${ev.eventId}: ${String(err)}\n`);
141
+ })
142
+ .finally(() => inFlight.delete(ev.eventId));
143
+ };
144
+ }