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.
- package/lib/ack_retry.ts +73 -0
- package/lib/bridge_core.ts +214 -21
- package/lib/control_stream.ts +49 -21
- package/lib/dm_stream.ts +276 -60
- package/lib/launch_confirm.ts +69 -0
- package/lib/main_catchup.ts +264 -0
- package/lib/messages.ts +65 -2
- package/lib/runner_registry.ts +44 -10
- package/lib/runner_relaunch.ts +6 -1
- package/lib/runner_roster.ts +5 -3
- package/lib/runner_stream.ts +47 -37
- package/lib/server_events.ts +144 -0
- package/lib/sse_idle.ts +136 -0
- package/lib/stream_log.ts +69 -0
- package/package.json +1 -1
- package/viber-channel.ts +100 -18
- package/viber-codex-bridge.ts +3 -0
|
@@ -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
|
+
}
|
package/lib/sse_idle.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Idle guard for SSE readers (#751).
|
|
3
|
+
*
|
|
4
|
+
* Every SSE stream the channel holds (main conversation, agent DMs, instance
|
|
5
|
+
* control, runner control, Codex/Gemma bridge) used to `await reader.read()` with
|
|
6
|
+
* no deadline. A connection that dies WITHOUT a FIN (half-open behind the tunnel)
|
|
7
|
+
* then parks the reader forever: no reconnect, no log line (#751 step-01, measured
|
|
8
|
+
* with the real readers against a frozen local server).
|
|
9
|
+
*
|
|
10
|
+
* The server sends a byte at least every ~15 s on all of these streams
|
|
11
|
+
* (`: keepalive` or `event: ping`, viber/voice_pipeline.py). The guard therefore
|
|
12
|
+
* bounds the time spent WAITING for bytes: if one wait — the fetch until headers,
|
|
13
|
+
* or one `read()` — exceeds `idleMs`, it aborts the connection and rejects with
|
|
14
|
+
* {@link SseIdleTimeoutError}, and the caller's reconnect loop takes over.
|
|
15
|
+
*
|
|
16
|
+
* Only the WAIT is timed, never the processing between reads: a bridge that spends
|
|
17
|
+
* minutes inside a model turn between two reads must not be cut for it. Bytes the
|
|
18
|
+
* network buffered meanwhile come back on the next `read()` at once.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Three missed server beats (~15 s each). One constant for every reader. */
|
|
22
|
+
export const SSE_IDLE_TIMEOUT_MS = 45_000;
|
|
23
|
+
|
|
24
|
+
export class SseIdleTimeoutError extends Error {
|
|
25
|
+
constructor(readonly idleMs: number) {
|
|
26
|
+
super(`no bytes for ${idleMs} ms — stream presumed dead`);
|
|
27
|
+
this.name = "SseIdleTimeoutError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface IdleGuard {
|
|
32
|
+
/** Pass to `fetch` so a fire also aborts the connection itself. */
|
|
33
|
+
readonly signal: AbortSignal;
|
|
34
|
+
/** Await `p` (typically the fetch) under the idle deadline. */
|
|
35
|
+
race<T>(p: Promise<T>): Promise<T>;
|
|
36
|
+
/** One `reader.read()` under the idle deadline; cancels the reader on a fire. */
|
|
37
|
+
read(reader: ReadableStreamDefaultReader<Uint8Array>): ReturnType<ReadableStreamDefaultReader<Uint8Array>["read"]>;
|
|
38
|
+
/** Stop the timer and detach from the outer signal. Idempotent. */
|
|
39
|
+
dispose(): void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface IdleGuardOptions {
|
|
43
|
+
idleMs?: number;
|
|
44
|
+
/** Outer cancellation (shutdown). Its abort is forwarded, never treated as idle. */
|
|
45
|
+
signal?: AbortSignal;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function createIdleGuard(opts: IdleGuardOptions = {}): IdleGuard {
|
|
49
|
+
const idleMs = opts.idleMs ?? SSE_IDLE_TIMEOUT_MS;
|
|
50
|
+
const ac = new AbortController();
|
|
51
|
+
const outer = opts.signal;
|
|
52
|
+
const onOuterAbort = () => ac.abort(outer?.reason);
|
|
53
|
+
if (outer) {
|
|
54
|
+
if (outer.aborted) ac.abort(outer.reason);
|
|
55
|
+
else outer.addEventListener("abort", onOuterAbort, { once: true });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
59
|
+
let disposed = false;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Run `p` against a fresh deadline. The race guarantees we return even if the
|
|
63
|
+
* runtime never settles `p` after an abort (we do not rely on Bun propagating
|
|
64
|
+
* the abort into a pending `read()`); `onFire` still cancels the underlying
|
|
65
|
+
* resource so nothing keeps the socket.
|
|
66
|
+
*/
|
|
67
|
+
function withDeadline<T>(p: Promise<T>, onFire?: (err: unknown) => void): Promise<T> {
|
|
68
|
+
if (disposed) return p;
|
|
69
|
+
let fire!: (err: unknown) => void;
|
|
70
|
+
const expired = new Promise<never>((_, reject) => {
|
|
71
|
+
fire = reject;
|
|
72
|
+
});
|
|
73
|
+
// An abort (shutdown, or a fire) also ends the wait at once — a body that
|
|
74
|
+
// ignores the signal must not keep the caller parked (#751 review).
|
|
75
|
+
const onAbort = () => {
|
|
76
|
+
fire(ac.signal.reason);
|
|
77
|
+
onFire?.(ac.signal.reason);
|
|
78
|
+
};
|
|
79
|
+
if (ac.signal.aborted) onAbort();
|
|
80
|
+
else ac.signal.addEventListener("abort", onAbort, { once: true });
|
|
81
|
+
timer = setTimeout(() => {
|
|
82
|
+
const err = new SseIdleTimeoutError(idleMs);
|
|
83
|
+
// Reject FIRST: aborting can settle the pending read() as a clean `done`
|
|
84
|
+
// in the same tick, which would win the race and hide the timeout.
|
|
85
|
+
fire(err);
|
|
86
|
+
ac.abort(err);
|
|
87
|
+
}, idleMs);
|
|
88
|
+
return Promise.race([p, expired]).finally(() => {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
timer = undefined;
|
|
91
|
+
ac.signal.removeEventListener("abort", onAbort);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
signal: ac.signal,
|
|
97
|
+
race: (p) => withDeadline(p),
|
|
98
|
+
read: (reader) =>
|
|
99
|
+
withDeadline(reader.read(), (err) => {
|
|
100
|
+
reader.cancel(err).catch(() => {});
|
|
101
|
+
}),
|
|
102
|
+
dispose() {
|
|
103
|
+
if (disposed) return;
|
|
104
|
+
disposed = true;
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
outer?.removeEventListener("abort", onOuterAbort);
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Transient vs terminal classification for a failed SSE (re)connect (#751).
|
|
113
|
+
* Network errors, idle timeouts, 5xx (incl. the tunnel's 502), 408 and 429 are
|
|
114
|
+
* TRANSIENT: retry without a cap. Any other 4xx is TERMINAL for that stream.
|
|
115
|
+
*/
|
|
116
|
+
export class SseHttpError extends Error {
|
|
117
|
+
constructor(
|
|
118
|
+
readonly status: number,
|
|
119
|
+
label: string,
|
|
120
|
+
) {
|
|
121
|
+
super(`${label} connection failed: HTTP ${status}`);
|
|
122
|
+
this.name = "SseHttpError";
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function isTerminalSseError(err: unknown): boolean {
|
|
127
|
+
if (!(err instanceof SseHttpError)) return false;
|
|
128
|
+
const s = err.status;
|
|
129
|
+
return s >= 400 && s < 500 && s !== 408 && s !== 429;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Exponential reconnect backoff: base, 2×base, … capped at `maxMs`. */
|
|
133
|
+
export function backoffDelay(attempt: number, baseMs: number, maxMs: number): number {
|
|
134
|
+
if (attempt <= 1) return baseMs;
|
|
135
|
+
return Math.min(maxMs, baseMs * 2 ** Math.min(attempt - 1, 20));
|
|
136
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable lifecycle journal for the channel's SSE streams (#751).
|
|
3
|
+
*
|
|
4
|
+
* Claude Code's MCP log captures a server's stderr only around its START: on the
|
|
5
|
+
* 40 logs checked in #751 step-01, nothing written after startup ever reached it.
|
|
6
|
+
* A stream that gave up or froze was therefore indistinguishable from a quiet one.
|
|
7
|
+
* This journal writes the stream lifecycle (connect, end, idle timeout, retry,
|
|
8
|
+
* terminal stop) to one file per process, in addition to stderr:
|
|
9
|
+
*
|
|
10
|
+
* <lockDir>/stream-logs/<UTC start>-<pid>.log
|
|
11
|
+
*
|
|
12
|
+
* Only lifecycle lines go here — a handful per hour on a healthy agent — never
|
|
13
|
+
* message content. Files older than {@link STREAM_LOG_RETENTION_MS} are pruned at
|
|
14
|
+
* start. Writing never throws: a journal failure must not take a stream down.
|
|
15
|
+
*/
|
|
16
|
+
import { appendFileSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
|
|
19
|
+
export const STREAM_LOG_RETENTION_MS = 7 * 24 * 3600 * 1000;
|
|
20
|
+
|
|
21
|
+
let logFile: string | null = null;
|
|
22
|
+
|
|
23
|
+
/** Open this process's journal under `<lockDir>/stream-logs/`. Returns its path, or null. */
|
|
24
|
+
export function openStreamLog(lockDir: string, now: Date = new Date(), pid: number = process.pid): string | null {
|
|
25
|
+
try {
|
|
26
|
+
const dir = join(lockDir, "stream-logs");
|
|
27
|
+
mkdirSync(dir, { recursive: true });
|
|
28
|
+
pruneStreamLogs(dir, now.getTime());
|
|
29
|
+
const stamp = now.toISOString().replace(/[:.]/g, "-");
|
|
30
|
+
logFile = join(dir, `${stamp}-${pid}.log`);
|
|
31
|
+
appendFileSync(logFile, `${now.toISOString()} [stream-log] opened pid=${pid}\n`);
|
|
32
|
+
return logFile;
|
|
33
|
+
} catch {
|
|
34
|
+
logFile = null;
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function pruneStreamLogs(dir: string, nowMs: number): void {
|
|
40
|
+
for (const name of readdirSync(dir)) {
|
|
41
|
+
if (!name.endsWith(".log")) continue;
|
|
42
|
+
const p = join(dir, name);
|
|
43
|
+
try {
|
|
44
|
+
if (nowMs - statSync(p).mtimeMs > STREAM_LOG_RETENTION_MS) unlinkSync(p);
|
|
45
|
+
} catch {
|
|
46
|
+
/* raced with another process — ignore */
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Write one lifecycle line to stderr AND the journal (when open). `line` is the
|
|
53
|
+
* same text the stream already logged; a trailing newline is normalised.
|
|
54
|
+
*/
|
|
55
|
+
export function streamLog(line: string): void {
|
|
56
|
+
const text = line.endsWith("\n") ? line : `${line}\n`;
|
|
57
|
+
process.stderr.write(text);
|
|
58
|
+
if (!logFile) return;
|
|
59
|
+
try {
|
|
60
|
+
appendFileSync(logFile, `${new Date().toISOString()} ${text}`);
|
|
61
|
+
} catch {
|
|
62
|
+
/* never let the journal break a stream */
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Test hook: forget the open journal. */
|
|
67
|
+
export function _resetStreamLogForTests(): void {
|
|
68
|
+
logFile = null;
|
|
69
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "viber-channel",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.49",
|
|
4
4
|
"description": "Voice + text MCP channel between a Claude Code session and the Viber UI (https://viber.dgypx.dev). Push transcripts to Claude; send_message tool delivers text back to the UI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/viber-channel.ts
CHANGED
|
@@ -76,6 +76,10 @@ import { readLocalVersion } from "./lib/version_check.ts";
|
|
|
76
76
|
import { BOW_OUT_MESSAGE, shouldBowOutToPlugin } from "./lib/cli_bow_out.ts";
|
|
77
77
|
import { routeJoin } from "./lib/own_join.ts";
|
|
78
78
|
import { resolveLockDir } from "./lib/lock_dir.ts";
|
|
79
|
+
import { createIdleGuard, type IdleGuard } from "./lib/sse_idle.ts";
|
|
80
|
+
import { openStreamLog, streamLog } from "./lib/stream_log.ts";
|
|
81
|
+
import { ackServerEvent, createServerEventHandler } from "./lib/server_events.ts";
|
|
82
|
+
import { createLaunchConfirmer, postLaunched } from "./lib/launch_confirm.ts";
|
|
79
83
|
import { acquireLockFile, createLockSlot } from "./lib/bridge_lock.ts";
|
|
80
84
|
|
|
81
85
|
// ---- CLI subcommand dispatch (must happen before lock acquire + loadAuth) ----
|
|
@@ -425,7 +429,13 @@ import {
|
|
|
425
429
|
RefreshHttpError,
|
|
426
430
|
RefreshNetworkError,
|
|
427
431
|
} from "./lib/conversation.ts";
|
|
428
|
-
import { ackMessage, ConversationTokenExpiredError } from "./lib/messages.ts";
|
|
432
|
+
import { ackMessage, ConversationTokenExpiredError, fetchMessageWindow } from "./lib/messages.ts";
|
|
433
|
+
import { CATCHUP_PRIME_TIMEOUT_MS, MainConversationCatchUp, openWithCatchUp } from "./lib/main_catchup.ts";
|
|
434
|
+
// #751: one catch-up state for the main conversation, shared by every reconnect.
|
|
435
|
+
const mainCatchUp = new MainConversationCatchUp();
|
|
436
|
+
// #751: every instance id this process has carried (it changes on re-registration):
|
|
437
|
+
// a catch-up must not hand the agent its own earlier posts back.
|
|
438
|
+
const OWN_INSTANCE_IDS = new Set<string>();
|
|
429
439
|
import {
|
|
430
440
|
listAgents as libListAgents,
|
|
431
441
|
messageAgent as libMessageAgent,
|
|
@@ -585,6 +595,8 @@ process.stderr.write(
|
|
|
585
595
|
`[viber-channel] startup: pid=${process.pid}, fp=${LOCK_FINGERPRINT.slice(0, 8)}, sessionId=${sessionIdLogged}, acquiring lock\n`,
|
|
586
596
|
);
|
|
587
597
|
const blockingPid = acquireLock();
|
|
598
|
+
// #751: durable stream journal — the MCP log keeps stderr only around startup.
|
|
599
|
+
openStreamLog(LOCK_DIR());
|
|
588
600
|
process.stderr.write(`[viber-channel] startup: lock acquired (blockingPid=${blockingPid})\n`);
|
|
589
601
|
|
|
590
602
|
// Connect to Claude Code over stdio FIRST so notifications can be sent
|
|
@@ -700,6 +712,8 @@ try {
|
|
|
700
712
|
// token that instance_key may fall back to (Codex review P1). Undefined → ""
|
|
701
713
|
// → the guard is a no-op (delivers everything), which is the safe default.
|
|
702
714
|
OWN_INSTANCE_ID = acquired.instance_id ?? "";
|
|
715
|
+
if (OWN_INSTANCE_ID) OWN_INSTANCE_IDS.add(OWN_INSTANCE_ID);
|
|
716
|
+
streamLog(`[viber-channel] instance ${OWN_INSTANCE_ID} label ${process.env.VIBER_CHANNEL_LABEL ?? "-"}`);
|
|
703
717
|
|
|
704
718
|
// #400: a NAMED agent (VIBER_CHANNEL_LABEL, no env-injected VIBER_INSTANCE_TOKEN)
|
|
705
719
|
// re-registers a FRESH instance_id on every start (acquireInstance path 2), so
|
|
@@ -786,6 +800,8 @@ try {
|
|
|
786
800
|
persistInstanceCredentials(authFilePath(), reg.instance_id, reg.instance_token);
|
|
787
801
|
instanceToken = reg.instance_token;
|
|
788
802
|
OWN_INSTANCE_ID = reg.instance_id;
|
|
803
|
+
OWN_INSTANCE_IDS.add(OWN_INSTANCE_ID);
|
|
804
|
+
streamLog(`[viber-channel] re-registered as instance ${OWN_INSTANCE_ID}`);
|
|
789
805
|
// #398: re-attach the fresh (post-revocation) instance to its team.
|
|
790
806
|
await maybeAttachTeam(apiBase(), auth.project_id, auth.project_token, auth.client_fingerprint, reg.instance_id);
|
|
791
807
|
// #400: keep the SAME namespacing rule after a post-revocation re-register.
|
|
@@ -846,10 +862,15 @@ try {
|
|
|
846
862
|
projectId: auth.project_id,
|
|
847
863
|
getConversationId: () => CONVERSATION_ID || null,
|
|
848
864
|
});
|
|
865
|
+
const launchConfirmer = createLaunchConfirmer({
|
|
866
|
+
jobName: process.env.VIBER_JOB_NAME,
|
|
867
|
+
post: (job, sig) => postLaunched(apiBase(), OWN_INSTANCE_ID, instanceToken, job, sig),
|
|
868
|
+
log: streamLog,
|
|
869
|
+
});
|
|
849
870
|
const controlStream = runPersistentControlStream(
|
|
850
871
|
{ getBaseUrl: apiBase, instanceId: OWN_INSTANCE_ID, instanceToken },
|
|
851
872
|
{
|
|
852
|
-
log:
|
|
873
|
+
log: streamLog,
|
|
853
874
|
onJoin: (pushed) => {
|
|
854
875
|
// #687: a join for our OWN main conversation must never open a second stream on it.
|
|
855
876
|
if (routeJoin(pushed.conversation_id, CONVERSATION_ID) === "adopt-main-token") {
|
|
@@ -869,6 +890,25 @@ try {
|
|
|
869
890
|
// #627: this agent never beats on the network — its runner answers for it
|
|
870
891
|
// (Python no longer probes a runner-covered agent; an old server may still).
|
|
871
892
|
onBeatNow: () => {},
|
|
893
|
+
// #751: confirm WHICH launch this agent is, once its channel is connected
|
|
894
|
+
// server-side — the launcher then gets agent_connected (no-op if not launched
|
|
895
|
+
// by the gateway: VIBER_JOB_NAME is empty).
|
|
896
|
+
onConnected: launchConfirmer,
|
|
897
|
+
// #751: durable server events (delivery_failed, delivery_recovered,
|
|
898
|
+
// agent_connected): ACKed by this code on every arrival, shown to the model
|
|
899
|
+
// once — the callback that replaces waiting or polling.
|
|
900
|
+
onEvent: createServerEventHandler({
|
|
901
|
+
ack: (eventId) => ackServerEvent(apiBase(), OWN_INSTANCE_ID, instanceToken, eventId),
|
|
902
|
+
surface: async (ev, text) => {
|
|
903
|
+
await waitDeliverable("message");
|
|
904
|
+
await mcp.notification({
|
|
905
|
+
method: "notifications/claude/channel",
|
|
906
|
+
params: { content: text, meta: { source: "system", type: ev.event } },
|
|
907
|
+
});
|
|
908
|
+
streamLog(`[viber-channel] server event ${ev.eventId} shown to the model`);
|
|
909
|
+
},
|
|
910
|
+
log: streamLog,
|
|
911
|
+
}),
|
|
872
912
|
},
|
|
873
913
|
);
|
|
874
914
|
// Presence-only consumer: firstJoin ALWAYS settles (rejected at loop end) —
|
|
@@ -1222,7 +1262,7 @@ function startDmStream(minted: ConversationMintResponse): void {
|
|
|
1222
1262
|
// above does not replay history already delivered in the prior run (#427).
|
|
1223
1263
|
let watermark = dmWatermarks.get(minted.conversation_id);
|
|
1224
1264
|
if (!watermark) {
|
|
1225
|
-
watermark = { lastId: 0 };
|
|
1265
|
+
watermark = { lastId: 0, pendingAcks: new Set<string>() }; // #751: ACK tracking on
|
|
1226
1266
|
dmWatermarks.set(minted.conversation_id, watermark);
|
|
1227
1267
|
}
|
|
1228
1268
|
process.stderr.write(`[viber-channel] joining agent DM ${minted.conversation_id}\n`);
|
|
@@ -1234,7 +1274,9 @@ function startDmStream(minted: ConversationMintResponse): void {
|
|
|
1234
1274
|
getApiBaseUrl: apiBase,
|
|
1235
1275
|
conversationId: minted.conversation_id,
|
|
1236
1276
|
conversationToken: minted.conversation_token,
|
|
1237
|
-
log:
|
|
1277
|
+
log: streamLog,
|
|
1278
|
+
// #751: transport ACK of each peer message (never of our own).
|
|
1279
|
+
ownInstanceId: OWN_INSTANCE_ID,
|
|
1238
1280
|
signal: controller.signal,
|
|
1239
1281
|
watermark,
|
|
1240
1282
|
onMessage: (msg) => pushMessage(msg, { conversationId: minted.conversation_id }),
|
|
@@ -1254,24 +1296,58 @@ async function sseLoop(): Promise<void> {
|
|
|
1254
1296
|
|
|
1255
1297
|
process.stderr.write(`[viber-channel] Connecting to SSE: ${SSE_URL}\n`);
|
|
1256
1298
|
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1299
|
+
// #751: bound every wait for bytes (headers, then each read). The server sends
|
|
1300
|
+
// `: keepalive` every ~15 s, so a longer silence is a dead connection: throwing
|
|
1301
|
+
// hands control back to mainLoop, which reconnects. Before, a half-open socket
|
|
1302
|
+
// parked this read forever, with no log line.
|
|
1303
|
+
const guard = createIdleGuard();
|
|
1304
|
+
try {
|
|
1305
|
+
await sseLoopGuarded(headers, guard);
|
|
1306
|
+
} finally {
|
|
1307
|
+
guard.dispose();
|
|
1265
1308
|
}
|
|
1309
|
+
}
|
|
1266
1310
|
|
|
1267
|
-
|
|
1311
|
+
async function sseLoopGuarded(headers: Record<string, string>, guard: IdleGuard): Promise<void> {
|
|
1312
|
+
// #751: prime → open → catch-up (lib/main_catchup.ts openWithCatchUp). The two
|
|
1313
|
+
// REST phases run on their OWN bounded guards: a frozen Worker delays the live
|
|
1314
|
+
// read by at most CATCHUP_PRIME_TIMEOUT_MS per phase and never aborts this
|
|
1315
|
+
// healthy stream (Codex); the catch-up is retried on the next connect.
|
|
1316
|
+
const resp = await openWithCatchUp({
|
|
1317
|
+
catchUp: mainCatchUp,
|
|
1318
|
+
streamGuard: guard,
|
|
1319
|
+
open: (signal) => fetch(SSE_URL, { headers, signal }),
|
|
1320
|
+
fetchWindow: (q, signal) => fetchMessageWindow(apiBase(), CONVERSATION_ID, CONVERSATION_TOKEN, q, signal),
|
|
1321
|
+
makeRestGuard: () => createIdleGuard({ idleMs: CATCHUP_PRIME_TIMEOUT_MS }),
|
|
1322
|
+
onOpen: async (r) => {
|
|
1323
|
+
if (r.status === 401) {
|
|
1324
|
+
await handleConversationTokenExpired(mcp);
|
|
1325
|
+
}
|
|
1326
|
+
if (!r.ok || !r.body) {
|
|
1327
|
+
throw new Error(`SSE connection failed: HTTP ${r.status}`);
|
|
1328
|
+
}
|
|
1329
|
+
streamLog(`[viber-channel] SSE connected\n`);
|
|
1330
|
+
},
|
|
1331
|
+
deliver: async (raw) => {
|
|
1332
|
+
// REST ids are numbers, SSE ids strings: normalise so message_id reaches the meta.
|
|
1333
|
+
const msg = { ...raw, id: raw.id != null ? String(raw.id) : undefined } as Parameters<typeof pushMessage>[0] & {
|
|
1334
|
+
role?: string;
|
|
1335
|
+
};
|
|
1336
|
+
if (typeof msg.content !== "string" || !msg.content) return;
|
|
1337
|
+
ackInboundReceipt(msg);
|
|
1338
|
+
await pushMessage(msg);
|
|
1339
|
+
},
|
|
1340
|
+
isOwn: (sender) => typeof sender === "string" && OWN_INSTANCE_IDS.has(sender),
|
|
1341
|
+
log: streamLog,
|
|
1342
|
+
});
|
|
1343
|
+
if (!resp.body) throw new Error("SSE connection has no body");
|
|
1268
1344
|
|
|
1269
1345
|
const reader = resp.body.getReader();
|
|
1270
1346
|
const decoder = new TextDecoder();
|
|
1271
1347
|
let buffer = "";
|
|
1272
1348
|
|
|
1273
1349
|
while (true) {
|
|
1274
|
-
const { done, value } = await
|
|
1350
|
+
const { done, value } = await guard.read(reader);
|
|
1275
1351
|
if (done) break;
|
|
1276
1352
|
|
|
1277
1353
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -1341,9 +1417,15 @@ async function sseLoop(): Promise<void> {
|
|
|
1341
1417
|
};
|
|
1342
1418
|
if (msg.content) {
|
|
1343
1419
|
// #346: confirm receipt to the web BEFORE forwarding to the LLM
|
|
1344
|
-
// and independently of any reply — decoupled from reply latency
|
|
1420
|
+
// and independently of any reply — decoupled from reply latency
|
|
1421
|
+
// and from the catch-up dedup below (#751).
|
|
1345
1422
|
ackInboundReceipt(msg);
|
|
1346
|
-
|
|
1423
|
+
if (mainCatchUp.isDelivered(msg.id)) {
|
|
1424
|
+
process.stderr.write(`[viber-channel] message ${msg.id} already delivered by catch-up — skipped\n`);
|
|
1425
|
+
} else {
|
|
1426
|
+
await pushMessage(msg);
|
|
1427
|
+
mainCatchUp.markDelivered(msg.id);
|
|
1428
|
+
}
|
|
1347
1429
|
} else {
|
|
1348
1430
|
process.stderr.write(`[viber-channel] 'message' event has empty content\n`);
|
|
1349
1431
|
}
|
|
@@ -1369,9 +1451,9 @@ async function mainLoop(): Promise<void> {
|
|
|
1369
1451
|
try {
|
|
1370
1452
|
await sseLoop();
|
|
1371
1453
|
// If SSE ends cleanly, reconnect immediately
|
|
1372
|
-
|
|
1454
|
+
streamLog(`[viber-channel] SSE stream ended, reconnecting...\n`);
|
|
1373
1455
|
} catch (err) {
|
|
1374
|
-
|
|
1456
|
+
streamLog(`[viber-channel] SSE failed: ${String(err)}, retrying in 2s...\n`);
|
|
1375
1457
|
await sleep(2000);
|
|
1376
1458
|
}
|
|
1377
1459
|
}
|
package/viber-codex-bridge.ts
CHANGED
|
@@ -1409,6 +1409,9 @@ export async function acquireConversationViaInvite(
|
|
|
1409
1409
|
onBeatNow: () => {
|
|
1410
1410
|
void sendInstanceHeartbeat(apiBase(), instanceKey, instanceToken);
|
|
1411
1411
|
},
|
|
1412
|
+
// #751: no durable-event handler on this legacy (non-await) path on purpose:
|
|
1413
|
+
// ACKing without presenting would destroy the event. Unhandled, it stays
|
|
1414
|
+
// pending server-side until its TTL (the await-invite path presents it).
|
|
1412
1415
|
},
|
|
1413
1416
|
);
|
|
1414
1417
|
|