viber-channel 0.8.47 → 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.
package/lib/dm_stream.ts CHANGED
@@ -8,15 +8,20 @@
8
8
  *
9
9
  * This is intentionally narrow: it only forwards `message` events to `onMessage`
10
10
  * (the caller maps them to a Claude notification with provenance). `stop` ends
11
- * the stream; transient drops reconnect with backoff; a 401 ends it (the DM
12
- * token expired — the peer can re-open the DM, which re-pushes a fresh join).
11
+ * the stream; transient failures (network, 5xx, 408/429, idle timeout) reconnect
12
+ * with a bounded backoff and NO cap (#751: a cap of 8 made every Claude DM give up
13
+ * for good after a ~14 s server outage, while the agent stayed online and senders
14
+ * got "sent"); any other 4xx ends it; a 401 ends it (the DM token expired — the
15
+ * peer re-opening the DM re-invites an expired member, which pushes a fresh join).
13
16
  *
14
17
  * Side-effect-free and runtime-agnostic so it can be unit-tested with a mock
15
18
  * fetch — mirrors the shape of control_stream.ts.
16
19
  */
17
20
  import { cfAccessHeaders } from "./cfAccess.js";
18
21
  import { buildSseUrl } from "./urls.js";
19
- import { ConversationTokenExpiredError, fetchMessages } from "./messages.js";
22
+ import { ackMessageResult, ConversationTokenExpiredError, fetchMessageWindow, type MessageWindowResult } from "./messages.js";
23
+ import { backoffDelay, createIdleGuard, isTerminalSseError, SseHttpError } from "./sse_idle.js";
24
+ import { ackWithRetry, addPending } from "./ack_retry.js";
20
25
 
21
26
  /** A conversation message as it arrives on the SSE `message` event. */
22
27
  export interface DmMessage {
@@ -40,6 +45,23 @@ export interface DmMessage {
40
45
  export interface DmWatermark {
41
46
  /** Highest delivered message id (0 = nothing delivered yet). */
42
47
  lastId: number;
48
+ /**
49
+ * #751 (Codex, step-07): CONTIGUOUS coverage — every id at or below it was
50
+ * delivered or legitimately skipped. Advanced ONLY by a catch-up page fully
51
+ * processed from the id-ordered window; never by a live delivery. Absent on a
52
+ * legacy watermark: `lastId` then stands for it. The catch-up resumes from here,
53
+ * so a 101 that was missed while 102 arrived live is still delivered.
54
+ */
55
+ floor?: number;
56
+ /** #751: ids delivered ABOVE `floor` (live, or catch-up past a failure). */
57
+ delivered?: Set<string>;
58
+ /**
59
+ * #751: ids whose transport ACK has not been confirmed yet. Survives across
60
+ * runs with the watermark, so an id at or below `lastId` is re-acknowledged
61
+ * ONLY if it is in here — a re-join's catch-up never re-ACKs the whole
62
+ * history (one Worker subrequest per message, Opus review).
63
+ */
64
+ pendingAcks?: Set<string>;
43
65
  }
44
66
 
45
67
  /** Signature of the catch-up fetch (mirrors messages.ts `fetchMessages`). */
@@ -70,14 +92,10 @@ export interface DmStreamOptions {
70
92
  signal?: AbortSignal;
71
93
  /** Backoff before reconnecting after a transient drop. Default 2000ms. */
72
94
  reconnectDelayMs?: number;
73
- /**
74
- * Cap on CONSECUTIVE connection errors before giving up (#291 step-04). A
75
- * clean end (normal SSE recycle) resets the counter, so a healthy stream that
76
- * recycles forever never trips it; only a persistent failure (5xx/network)
77
- * does. When the cap is hit the stream stops — the peer re-opening the DM
78
- * re-pushes a fresh join, so it is not a permanent dead end. Default 8.
79
- */
80
- maxConsecutiveErrors?: number;
95
+ /** Cap of the exponential reconnect backoff (#751). Default 30 000 ms. */
96
+ maxReconnectDelayMs?: number;
97
+ /** Idle deadline per wait for bytes (#751). Default `SSE_IDLE_TIMEOUT_MS`. */
98
+ idleTimeoutMs?: number;
81
99
  /** Injectable for tests; defaults to global fetch. */
82
100
  fetchImpl?: typeof fetch;
83
101
  /**
@@ -86,6 +104,24 @@ export interface DmStreamOptions {
86
104
  * forward anything published while we were disconnected (#291 step-03).
87
105
  */
88
106
  fetchMessagesImpl?: FetchMessagesFn;
107
+ /** #751: bound of one catch-up REST phase (own guard); default `CATCHUP_REST_TIMEOUT_MS`. */
108
+ catchUpTimeoutMs?: number;
109
+ /** #751: injectable windowed catch-up fetch (tests); defaults to `fetchMessageWindow`. */
110
+ fetchWindowImpl?: (q: { after?: number }) => Promise<MessageWindowResult>;
111
+ /**
112
+ * This channel's own instance id (#751). A message it posted itself is never
113
+ * acknowledged (the server refuses a sender's ACK of its own DM anyway).
114
+ */
115
+ ownInstanceId?: string;
116
+ /**
117
+ * Transport ACK of one received DM message (#751). Defaults to POST
118
+ * /messages/:id/ack with this DM's token. Resolves true on success.
119
+ */
120
+ ackImpl?: (messageId: string) => Promise<boolean | "ok" | "rejected" | "failed">;
121
+ /** Delays between ACK attempts (#751); default 1 s, 2 s, 4 s — bounded. */
122
+ ackRetryDelaysMs?: number[];
123
+ /** Bound of ONE ACK attempt (#751); default `ACK_ATTEMPT_TIMEOUT_MS`. */
124
+ ackAttemptTimeoutMs?: number;
89
125
  /**
90
126
  * Cross-run dedup watermark (#427). The run-scoped `handledIds` only dedups
91
127
  * WITHIN a single run; a re-join starts a fresh run with an empty set and the
@@ -126,16 +162,109 @@ function abortableDelay(ms: number, signal?: AbortSignal): Promise<void> {
126
162
  * downstream in the onMessage handler (self-echo), so forwarding all unseen
127
163
  * messages here is safe.
128
164
  */
165
+ /**
166
+ * Per-stream transport-ACK state (#751), shared across reconnects of ONE
167
+ * runDmStream run: ids confirmed by the server, and ids with an ACK in flight.
168
+ */
169
+ const ackStates = new WeakMap<DmStreamOptions, { acked: Set<string>; inFlight: Set<string> }>();
170
+
171
+ /**
172
+ * Acknowledge receipt of a peer's DM message to the server (#751) — the transport
173
+ * receipt its SENDER relies on. Posted by the channel CODE as soon as the frame is
174
+ * parsed, independently of dedup and of delivery to the model (an ACK proves
175
+ * reception by the channel, not by the model). Fire-and-forget, bounded retry; an
176
+ * id that still failed is retried when it is delivered again (catch-up after a
177
+ * reconnect). Never throws.
178
+ */
179
+ function acknowledge(opts: DmStreamOptions, msg: DmMessage, idStr: string | undefined): void {
180
+ if (!idStr) return;
181
+ const sender = msg.sender_instance_id;
182
+ if (!sender || (opts.ownInstanceId && sender === opts.ownInstanceId)) return;
183
+ let state = ackStates.get(opts);
184
+ if (!state) {
185
+ state = { acked: new Set(), inFlight: new Set() };
186
+ ackStates.set(opts, state);
187
+ }
188
+ if (state.acked.has(idStr) || state.inFlight.has(idStr)) return;
189
+ state.inFlight.add(idStr);
190
+ const st = state;
191
+ const pending = opts.watermark ? (opts.watermark.pendingAcks ??= new Set<string>()) : undefined;
192
+ if (pending) addPending(pending, idStr, opts.log);
193
+ const attempt = (sig: AbortSignal) =>
194
+ opts.ackImpl
195
+ ? opts.ackImpl(idStr)
196
+ : ackMessageResult(opts.getApiBaseUrl(), opts.conversationId, opts.conversationToken, idStr, sig, opts.fetchImpl);
197
+ void (async () => {
198
+ try {
199
+ const r = await ackWithRetry(attempt, {
200
+ delaysMs: opts.ackRetryDelaysMs,
201
+ attemptTimeoutMs: opts.ackAttemptTimeoutMs,
202
+ signal: opts.signal,
203
+ });
204
+ if (r !== "failed") pending?.delete(idStr);
205
+ if (r === "ok") st.acked.add(idStr);
206
+ else if (r === "rejected") {
207
+ // The Worker will never accept this ACK: stop, never retry it.
208
+ st.acked.add(idStr);
209
+ opts.log?.(`[dm-stream] ${opts.conversationId}: ACK of message ${idStr} rejected by the server\n`);
210
+ } else if (!opts.signal?.aborted) {
211
+ opts.log?.(`[dm-stream] ${opts.conversationId}: ACK of message ${idStr} failed — retried on next delivery\n`);
212
+ }
213
+ } finally {
214
+ st.inFlight.delete(idStr);
215
+ }
216
+ })();
217
+ }
218
+
219
+ /** Contiguous floor of a watermark (a legacy one: its lastId). */
220
+ function floorOf(w: DmWatermark): number {
221
+ if (w.floor === undefined) w.floor = w.lastId;
222
+ return w.floor;
223
+ }
224
+
225
+ /** Was this id delivered in a prior run (or skipped below the contiguous floor)? */
226
+ function alreadyDelivered(w: DmWatermark | undefined, numId: number, idStr: string | undefined): boolean {
227
+ if (!w || !Number.isSafeInteger(numId)) return false;
228
+ return numId <= floorOf(w) || (!!idStr && !!w.delivered?.has(idStr));
229
+ }
230
+
231
+ /** Record a delivery: lastId = max; above the floor, remember the id. */
232
+ function markDelivered(w: DmWatermark | undefined, numId: number, idStr: string | undefined): void {
233
+ if (!w || !Number.isSafeInteger(numId)) return;
234
+ if (numId > w.lastId) w.lastId = numId;
235
+ if (numId > floorOf(w) && idStr) (w.delivered ??= new Set<string>()).add(idStr);
236
+ }
237
+
238
+ /** Raise the contiguous floor (catch-up only) and forget the ids now under it. */
239
+ function advanceFloor(w: DmWatermark | undefined, to: number): void {
240
+ if (!w || to <= floorOf(w)) return;
241
+ w.floor = to;
242
+ for (const id of w.delivered ?? []) if (Number(id) <= to) w.delivered?.delete(id);
243
+ }
244
+
245
+ /**
246
+ * Forward one message. Returns false ONLY when the delivery to the model failed
247
+ * (the catch-up must then not move its floor past it); true when delivered or
248
+ * legitimately skipped (already delivered, no content).
249
+ */
129
250
  async function forwardMessage(
130
251
  opts: DmStreamOptions,
131
252
  handledIds: Set<string>,
132
253
  msg: DmMessage,
133
- ): Promise<void> {
254
+ ): Promise<boolean> {
134
255
  const idStr =
135
256
  msg.id !== undefined && msg.id !== null && String(msg.id).length > 0
136
257
  ? String(msg.id)
137
258
  : undefined;
138
- if (idStr && handledIds.has(idStr)) return; // already forwarded (live or catch-up)
259
+ // #751: the transport ACK goes out BEFORE the delivery dedup — a re-delivered
260
+ // id whose ACK failed gets another chance. Below the watermark, only ids still
261
+ // pending an ACK are re-acknowledged (never the whole replayed history).
262
+ const belowWatermark = alreadyDelivered(opts.watermark, idStr !== undefined ? Number(idStr) : Number.NaN, idStr);
263
+ // Tracking is on when the caller seeded `pendingAcks` (production does); without
264
+ // it the ACK state is unknown and a re-delivered id is re-acknowledged.
265
+ const tracked = opts.watermark?.pendingAcks;
266
+ if (!belowWatermark || !tracked || (idStr && tracked.has(idStr))) acknowledge(opts, msg, idStr);
267
+ if (idStr && handledIds.has(idStr)) return true; // already forwarded (live or catch-up)
139
268
  // Cross-run dedup (#427): the message id is `INTEGER PRIMARY KEY AUTOINCREMENT`
140
269
  // in D1 (migration 0009), so the server assigns a STRICTLY INCREASING, never-
141
270
  // reused id at insert — a genuinely new message always outranks everything
@@ -149,11 +278,13 @@ async function forwardMessage(
149
278
  // handledIds filter rather than silently mis-gating. The watermark only ever
150
279
  // advances AFTER a successful delivery, so a NaN/absent id is never watermarked.
151
280
  const numId = idStr !== undefined ? Number(idStr) : Number.NaN;
152
- if (opts.watermark && Number.isSafeInteger(numId) && numId <= opts.watermark.lastId) return;
281
+ // #751: "at or below the CONTIGUOUS floor, or delivered above it" — not "at or
282
+ // below the highest delivered id", which skipped a missed 101 once 102 arrived.
283
+ if (alreadyDelivered(opts.watermark, numId, idStr)) return true;
153
284
  // Content guard BEFORE consuming the id: a content-less payload must not burn
154
285
  // its id in handledIds, or a later (correctly-populated) catch-up of the same
155
286
  // id would be suppressed forever (review: Opus #4).
156
- if (!msg.content) return;
287
+ if (!msg.content) return true;
157
288
  // Normalize id to a string so downstream meta (message_id) is set consistently
158
289
  // regardless of whether it arrived as a number (GET) or string (SSE).
159
290
  const normalized: DmMessage = idStr ? { ...msg, id: idStr } : msg;
@@ -168,13 +299,13 @@ async function forwardMessage(
168
299
  // Advance the cross-run watermark ONLY after a successful delivery (#427,
169
300
  // Opus guard): a crash mid-handling leaves the id un-watermarked so the next
170
301
  // catch-up retries it — at-least-once over at-most-once, same as handledIds.
171
- if (opts.watermark && Number.isSafeInteger(numId) && numId > opts.watermark.lastId) {
172
- opts.watermark.lastId = numId;
173
- }
302
+ markDelivered(opts.watermark, numId, idStr);
303
+ return true;
174
304
  } catch (handlerErr) {
175
305
  opts.log?.(
176
306
  `[dm-stream] onMessage handler error: ${handlerErr instanceof Error ? handlerErr.message : String(handlerErr)}\n`,
177
307
  );
308
+ return false;
178
309
  }
179
310
  }
180
311
 
@@ -189,26 +320,95 @@ async function forwardMessage(
189
320
  * swallowed (the live stream may still deliver).
190
321
  */
191
322
  async function catchUp(opts: DmStreamOptions, handledIds: Set<string>): Promise<void> {
192
- const doFetch = opts.fetchMessagesImpl ?? fetchMessages;
193
- let msgs: Array<Record<string, unknown>>;
323
+ // #751 (Codex, step-07): the REST catch-up runs on its OWN bounded guard — a
324
+ // frozen Worker delays the live read by at most CATCHUP_REST_TIMEOUT_MS and never
325
+ // leaves this DM deaf; the catch-up is retried on the next connect.
326
+ const rest = createIdleGuard({ idleMs: opts.catchUpTimeoutMs ?? CATCHUP_REST_TIMEOUT_MS, signal: opts.signal });
327
+ let pages: CatchUpPage[];
194
328
  try {
195
- msgs = await doFetch(opts.getApiBaseUrl(), opts.conversationId, opts.conversationToken);
329
+ pages = await fetchCatchUpPages(opts, rest);
196
330
  } catch (err) {
197
331
  if (err instanceof ConversationTokenExpiredError) throw new DmStreamAuthError();
198
332
  opts.log?.(
199
333
  `[dm-stream] ${opts.conversationId} catch-up fetch failed: ${err instanceof Error ? err.message : String(err)}\n`,
200
334
  );
201
335
  return;
336
+ } finally {
337
+ rest.dispose();
202
338
  }
203
- for (const raw of msgs) {
204
- // Abort is terminal: this DM session ends here. Any ids already added to
205
- // handledIds are intentionally dropped — a future DM uses a fresh
206
- // runDmStream with its own handledIds (review: Opus #2).
207
- if (opts.signal?.aborted) return;
208
- await forwardMessage(opts, handledIds, raw as unknown as DmMessage);
339
+ for (const page of pages) {
340
+ let contiguous = true;
341
+ let last = 0;
342
+ for (const raw of page.messages) {
343
+ // Abort is terminal: this DM session ends here. Any ids already added to
344
+ // handledIds are intentionally dropped — a future DM uses a fresh
345
+ // runDmStream with its own handledIds (review: Opus #2).
346
+ if (opts.signal?.aborted) return;
347
+ const ok = await forwardMessage(opts, handledIds, raw as unknown as DmMessage);
348
+ const id = Number((raw as { id?: unknown }).id);
349
+ if (!ok) contiguous = false;
350
+ if (contiguous && Number.isSafeInteger(id)) last = id;
351
+ }
352
+ // Only a page read from the id-ordered window, and processed without a failed
353
+ // delivery up to `last`, moves the contiguous floor — never a capped legacy page.
354
+ if (page.windowed) advanceFloor(opts.watermark, last);
355
+ if (!contiguous) return;
209
356
  }
210
357
  }
211
358
 
359
+ interface CatchUpPage {
360
+ messages: Array<Record<string, unknown>>;
361
+ /** Read from the id-ordered window (vs. the legacy, oldest-500 listing). */
362
+ windowed: boolean;
363
+ }
364
+
365
+ /** Bound of one catch-up REST phase, on its own guard. */
366
+ export const CATCHUP_REST_TIMEOUT_MS = 10_000;
367
+
368
+ /** Pages of the catch-up window, at most this many per (re)connect (#751). */
369
+ const CATCHUP_MAX_PAGES = 10;
370
+
371
+ /**
372
+ * #751: the legacy listing returns the OLDEST 500 messages, so a DM longer than
373
+ * that never caught up its recent messages. Read by id instead, from the lowest id
374
+ * that may still need work: the watermark, or below it an id still pending its
375
+ * transport ACK. An injected `fetchMessagesImpl` (tests of the full-list
376
+ * semantics) or an older Worker (no `window` echo) keep the single legacy read.
377
+ */
378
+ async function fetchCatchUpPages(opts: DmStreamOptions, rest: { race<T>(p: Promise<T>): Promise<T>; readonly signal: AbortSignal }): Promise<CatchUpPage[]> {
379
+ if (opts.fetchMessagesImpl && !opts.fetchWindowImpl) {
380
+ return [{ messages: await rest.race(opts.fetchMessagesImpl(opts.getApiBaseUrl(), opts.conversationId, opts.conversationToken)), windowed: false }];
381
+ }
382
+ const fetchWindow = (q: { after?: number }) =>
383
+ rest.race(
384
+ opts.fetchWindowImpl
385
+ ? opts.fetchWindowImpl(q)
386
+ : fetchMessageWindow(opts.getApiBaseUrl(), opts.conversationId, opts.conversationToken, q, rest.signal),
387
+ );
388
+ const pending = [...(opts.watermark?.pendingAcks ?? [])].map(Number).filter((n) => Number.isSafeInteger(n));
389
+ // From the CONTIGUOUS floor (not the highest delivered id), or below it an id
390
+ // still pending its ACK.
391
+ let cursor = opts.watermark ? floorOf(opts.watermark) : 0;
392
+ if (pending.length > 0) cursor = Math.min(cursor, Math.min(...pending) - 1);
393
+ cursor = Math.max(0, cursor);
394
+ const pages: CatchUpPage[] = [];
395
+ for (let i = 0; i < CATCHUP_MAX_PAGES; i++) {
396
+ const res = await fetchWindow({ after: cursor });
397
+ pages.push({ messages: res.messages, windowed: !!res.window });
398
+ if (!res.window) {
399
+ if (res.messages.length >= 500) {
400
+ opts.log?.(`[dm-stream] ${opts.conversationId}: catch-up INCOMPLETE — this server ignores the window (legacy page of 500)\n`);
401
+ }
402
+ break;
403
+ }
404
+ if (res.messages.length < res.window.max) break;
405
+ const last = Number(res.messages[res.messages.length - 1]?.id);
406
+ if (!Number.isSafeInteger(last) || last <= cursor) break;
407
+ cursor = last;
408
+ }
409
+ return pages;
410
+ }
411
+
212
412
  /**
213
413
  * One SSE connection attempt: yields each parsed `message` payload until the
214
414
  * stream ends, `stop` arrives, or the signal aborts. Returns "stop" if the
@@ -219,32 +419,47 @@ async function catchUp(opts: DmStreamOptions, handledIds: Set<string>): Promise<
219
419
  async function consumeOnce(
220
420
  opts: DmStreamOptions,
221
421
  handledIds: Set<string>,
422
+ onConnected: () => void,
222
423
  ): Promise<"stop" | "end"> {
223
424
  const doFetch = opts.fetchImpl ?? fetch;
224
425
  const url = buildSseUrl(opts.wsUrl, opts.conversationId);
225
- const resp = await doFetch(url, {
226
- headers: {
227
- Authorization: `Bearer ${opts.conversationToken}`,
228
- Accept: "text/event-stream",
229
- "Cache-Control": "no-cache",
230
- ...cfAccessHeaders(),
231
- },
232
- signal: opts.signal,
233
- });
234
- if (resp.status === 401) throw new DmStreamAuthError();
235
- if (!resp.ok || !resp.body) {
236
- throw new Error(`DM stream connection failed: HTTP ${resp.status}`);
426
+ const guard = createIdleGuard({ idleMs: opts.idleTimeoutMs, signal: opts.signal });
427
+ try {
428
+ const resp = await guard.race(
429
+ doFetch(url, {
430
+ headers: {
431
+ Authorization: `Bearer ${opts.conversationToken}`,
432
+ Accept: "text/event-stream",
433
+ "Cache-Control": "no-cache",
434
+ ...cfAccessHeaders(),
435
+ },
436
+ signal: guard.signal,
437
+ }),
438
+ );
439
+ if (resp.status === 401) throw new DmStreamAuthError();
440
+ if (!resp.ok || !resp.body) throw new SseHttpError(resp.status, "DM stream");
441
+ onConnected();
442
+ return await readEvents(opts, handledIds, resp.body, guard);
443
+ } finally {
444
+ guard.dispose();
237
445
  }
446
+ }
238
447
 
448
+ async function readEvents(
449
+ opts: DmStreamOptions,
450
+ handledIds: Set<string>,
451
+ body: ReadableStream<Uint8Array>,
452
+ guard: ReturnType<typeof createIdleGuard>,
453
+ ): Promise<"stop" | "end"> {
239
454
  // Subscription is live → replay anything missed before reading live events.
240
455
  await catchUp(opts, handledIds);
241
456
 
242
- const reader = resp.body.getReader();
457
+ const reader = body.getReader();
243
458
  const decoder = new TextDecoder();
244
459
  let buffer = "";
245
460
  try {
246
461
  while (true) {
247
- const { done, value } = await reader.read();
462
+ const { done, value } = await guard.read(reader);
248
463
  if (done) return "end";
249
464
  buffer += decoder
250
465
  .decode(value, { stream: true })
@@ -302,43 +517,44 @@ export class DmStreamAuthError extends Error {
302
517
  */
303
518
  export async function runDmStream(opts: DmStreamOptions): Promise<void> {
304
519
  const log = opts.log ?? (() => {});
305
- const delayMs = opts.reconnectDelayMs ?? 2000;
306
- const maxErrors = opts.maxConsecutiveErrors ?? 8;
520
+ const baseDelayMs = opts.reconnectDelayMs ?? 2000;
521
+ const maxDelayMs = opts.maxReconnectDelayMs ?? 30_000;
307
522
  const signal = opts.signal;
308
523
  // Shared across reconnects so catch-up + live delivery dedup by message id.
309
524
  const handledIds = new Set<string>();
310
- // CONSECUTIVE connection errors. A clean end resets it to 0, so a normally
311
- // recycling stream never trips the cap — only a persistent failure does.
312
- let consecutiveErrors = 0;
525
+ // Failed attempts since the last successful connect — drives the backoff only.
526
+ // There is deliberately NO cap (#751): giving up left the DM deaf for good.
527
+ let failures = 0;
313
528
 
314
529
  while (true) {
315
530
  if (signal?.aborted) return;
316
531
  try {
317
- const reason = await consumeOnce(opts, handledIds);
318
- consecutiveErrors = 0; // clean end (or stop) → reset the retry budget
532
+ const reason = await consumeOnce(opts, handledIds, () => {
533
+ if (failures > 0) log(`[dm-stream] ${opts.conversationId} reconnected after ${failures} failed attempt(s)\n`);
534
+ failures = 0;
535
+ });
319
536
  if (reason === "stop") {
320
- log(`[dm-stream] ${opts.conversationId} stopped\n`);
537
+ log(`[dm-stream] ${opts.conversationId} stopped
538
+ `);
321
539
  return;
322
540
  }
323
- // Clean end → reconnect after backoff.
541
+ // Clean end → reconnect after the base delay.
324
542
  } catch (err) {
325
543
  if (err instanceof DmStreamAuthError) {
326
- log(`[dm-stream] ${opts.conversationId} token expired — ending (peer can re-open)\n`);
544
+ log(`[dm-stream] ${opts.conversationId} token expired — ending (a peer re-opening the DM re-invites)\n`);
327
545
  return;
328
546
  }
329
547
  if (signal?.aborted) return;
330
- consecutiveErrors += 1;
331
- log(
332
- `[dm-stream] ${opts.conversationId}: ${err instanceof Error ? err.message : String(err)}, reconnecting (${consecutiveErrors}/${maxErrors})...\n`,
333
- );
334
- if (consecutiveErrors >= maxErrors) {
335
- log(
336
- `[dm-stream] ${opts.conversationId} giving up after ${maxErrors} consecutive errors — ending (peer can re-open)\n`,
337
- );
548
+ if (isTerminalSseError(err)) {
549
+ log(`[dm-stream] ${opts.conversationId}: ${(err as Error).message} — terminal, ending\n`);
338
550
  return;
339
551
  }
552
+ failures += 1;
553
+ log(
554
+ `[dm-stream] ${opts.conversationId}: ${err instanceof Error ? err.message : String(err)}, reconnecting (attempt ${failures})...\n`,
555
+ );
340
556
  }
341
557
  if (signal?.aborted) return;
342
- await abortableDelay(delayMs, signal);
558
+ await abortableDelay(failures > 0 ? backoffDelay(failures, baseDelayMs, maxDelayMs) : baseDelayMs, signal);
343
559
  }
344
560
  }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The launched agent's half of a launch handshake (#751 step-05).
3
+ *
4
+ * On its control stream's `connected` — the server-side proof that this channel is
5
+ * really connected — the channel CODE tells the server which launch it is: the job
6
+ * name its launcher imposed (`VIBER_JOB_NAME`, unique per attempt; vibe-master
7
+ * always sets it, EMPTY when the agent was not launched by the gateway — then
8
+ * nothing is sent). The server matches it with the gateway's half and pushes
9
+ * `agent_connected` to the launcher. Nothing is sent to this agent's model.
10
+ *
11
+ * Confirmed once per process (a later `connected` re-sends only if no attempt
12
+ * succeeded yet); each attempt is bounded and retried (ack_retry).
13
+ */
14
+ import { type AckOutcome, ackWithRetry } from "./ack_retry.js";
15
+ import { cfAccessHeaders } from "./cfAccess.js";
16
+
17
+ export function createLaunchConfirmer(deps: {
18
+ jobName: string | undefined;
19
+ post: (jobName: string, signal: AbortSignal) => Promise<AckOutcome>;
20
+ log?: (line: string) => void;
21
+ delaysMs?: number[];
22
+ }): () => void {
23
+ const jobName = deps.jobName?.trim() ?? "";
24
+ let done = false;
25
+ let inFlight = false;
26
+ return () => {
27
+ if (!jobName || done || inFlight) return;
28
+ inFlight = true;
29
+ void ackWithRetry((sig) => deps.post(jobName, sig), { delaysMs: deps.delaysMs ?? [2000, 5000, 15000] })
30
+ .then((r) => {
31
+ if (r === "ok") {
32
+ done = true;
33
+ deps.log?.(`[launch] confirmed launch ${jobName} to the server\n`);
34
+ } else if (r === "rejected") {
35
+ done = true; // the server will never accept it (another project / label): stop
36
+ deps.log?.(`[launch] launch ${jobName} not confirmable here (refused by the server)\n`);
37
+ } else {
38
+ deps.log?.(`[launch] could not confirm launch ${jobName} yet — retried on the next connect\n`);
39
+ }
40
+ })
41
+ .finally(() => {
42
+ inFlight = false;
43
+ });
44
+ };
45
+ }
46
+
47
+ /** POST /api/instances/:id/launched. Never throws. */
48
+ export async function postLaunched(
49
+ baseUrl: string,
50
+ instanceId: string,
51
+ instanceToken: string,
52
+ jobName: string,
53
+ signal: AbortSignal,
54
+ fetchImpl: typeof fetch = fetch,
55
+ ): Promise<AckOutcome> {
56
+ try {
57
+ const resp = await fetchImpl(`${baseUrl}/api/instances/${instanceId}/launched`, {
58
+ method: "POST",
59
+ headers: { Authorization: `Bearer ${instanceToken}`, "Content-Type": "application/json", ...cfAccessHeaders() },
60
+ body: JSON.stringify({ job_name: jobName }),
61
+ signal,
62
+ });
63
+ if (resp.ok) return "ok";
64
+ const s = resp.status;
65
+ return s >= 400 && s < 500 && s !== 408 && s !== 429 ? "rejected" : "failed";
66
+ } catch {
67
+ return "failed";
68
+ }
69
+ }