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,326 @@
1
+ /**
2
+ * #747 — the ONE function that refreshes the codex model catalogue of this machine's owner.
3
+ *
4
+ * Called by exactly two triggers, never anything else (JP, 2026-11-18):
5
+ * - the Viber app at startup (in the background: it never delays the runner);
6
+ * - `viber-gateway refresh-models`, which the owner's agent runs when told a model came out,
7
+ * or when a role write is refused "not available".
8
+ * No periodic check, no second path.
9
+ *
10
+ * Steps: update the codex CLI when npm has a newer one (only when codex came from npm) →
11
+ * `model/list` of the installed codex → PUT the catalogue to viber-api with the runner token.
12
+ */
13
+
14
+ import { readCodexCatalogue, type ModelListPage } from "./codex_model_pair.ts";
15
+ import { cfAccessHeaders } from "./cfAccess.ts";
16
+ import { exec, execFile, spawn } from "./hidden_proc.ts";
17
+ import { loadRunnerAuth } from "./runner_stream.ts";
18
+
19
+ export const CODEX_NPM_PACKAGE = "@openai/codex";
20
+ /** One deadline over the WHOLE app-server exchange, initialize included (Opus review). */
21
+ const APP_SERVER_TIMEOUT_MS = 30_000;
22
+ const SHELL_TIMEOUT_MS = 5 * 60_000;
23
+
24
+ export type Catalogue = Record<string, string[]>;
25
+
26
+ export interface RefreshDeps {
27
+ /** `codex --version` → "0.170.0", or null when codex is not installed. */
28
+ installedVersion(): Promise<string | null>;
29
+ /** The version npm calls latest, or null when npm cannot answer. */
30
+ npmLatest(): Promise<string | null>;
31
+ /** The codex on PATH, and whether it lives in npm's global prefix (only then do we update it). */
32
+ pathCodex(): Promise<{ path: string | null; npmOwned: boolean }>;
33
+ /** `npm i -g @openai/codex@<version>`; throws on failure. */
34
+ npmInstall(version: string): Promise<void>;
35
+ /** `model/list` of the installed codex, in its order. */
36
+ readCatalogue(): Promise<Catalogue>;
37
+ /** PUT the catalogue; answers the model names it replaced (null: none before). Throws on a refusal. */
38
+ upload(cliVersion: string, models: Catalogue): Promise<string[] | null>;
39
+ }
40
+
41
+ export interface RefreshReport {
42
+ ok: boolean;
43
+ /** One line per fact, in order — what the verb prints and the app logs. */
44
+ lines: string[];
45
+ before?: string | null;
46
+ after?: string;
47
+ added: string[];
48
+ removed: string[];
49
+ }
50
+
51
+ /** Numeric dotted compare; a pre-release tag (0.171.0-alpha.1) is never "newer" than its release. */
52
+ export function isNewer(candidate: string, installed: string): boolean {
53
+ const parse = (v: string): number[] | null => {
54
+ if (!/^\d+(\.\d+)*$/.test(v)) return null;
55
+ return v.split(".").map(Number);
56
+ };
57
+ const a = parse(candidate);
58
+ const b = parse(installed);
59
+ if (a === null || b === null) return false;
60
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
61
+ const d = (a[i] ?? 0) - (b[i] ?? 0);
62
+ if (d !== 0) return d > 0;
63
+ }
64
+ return false;
65
+ }
66
+
67
+ function why(err: unknown): string {
68
+ return err instanceof Error ? err.message : String(err);
69
+ }
70
+
71
+ /** Update the CLI when npm has newer; returns the version installed afterwards (or null). */
72
+ async function updateCli(deps: RefreshDeps, before: string | null, lines: string[]): Promise<string | null> {
73
+ // Opus review: an absent codex is never installed — the refresh updates, it does not provision.
74
+ if (before === null) return null;
75
+ const latest = await deps.npmLatest().catch(() => null);
76
+ if (latest === null) {
77
+ lines.push("npm: latest codex version unknown — CLI left as is");
78
+ return before;
79
+ }
80
+ if (!isNewer(latest, before)) {
81
+ lines.push(`codex ${before} is up to date (npm latest ${latest})`);
82
+ return before;
83
+ }
84
+ const onPath = await deps.pathCodex().catch(() => ({ path: null, npmOwned: false }));
85
+ if (!onPath.npmOwned) {
86
+ lines.push(`codex ${before} on PATH (${onPath.path ?? "unknown"}) is not npm's global install — not updated (npm latest ${latest})`);
87
+ return before;
88
+ }
89
+ // JP (2026-11-18): updated even while codex agents run. On Windows a running codex.exe is
90
+ // locked and the install may fail — the failure is said in clear (the owner then stops the
91
+ // codex agents and re-runs), never skipped in silence.
92
+ try {
93
+ await deps.npmInstall(latest);
94
+ } catch (err) {
95
+ lines.push(
96
+ `codex update to ${latest} FAILED: ${why(err)} — if codex agents are running, stop them and run viber-gateway refresh-models again`,
97
+ );
98
+ return before;
99
+ }
100
+ const after = await deps.installedVersion();
101
+ lines.push(`codex updated: ${before} -> ${after ?? "absent"}`);
102
+ return after;
103
+ }
104
+
105
+ export async function refreshCodexModels(deps: RefreshDeps): Promise<RefreshReport> {
106
+ const lines: string[] = [];
107
+ const report = (ok: boolean, extra: Partial<RefreshReport> = {}): RefreshReport => ({
108
+ ok,
109
+ lines,
110
+ added: [],
111
+ removed: [],
112
+ ...extra,
113
+ });
114
+ const before = await deps.installedVersion();
115
+ const version = await updateCli(deps, before, lines);
116
+ if (version === null) {
117
+ lines.push("codex is not installed: no model list to send");
118
+ return report(false, { before });
119
+ }
120
+ let models: Catalogue;
121
+ try {
122
+ models = await deps.readCatalogue();
123
+ } catch (err) {
124
+ lines.push(`model/list of codex ${version} FAILED: ${why(err)} — nothing sent`);
125
+ return report(false, { before, after: version });
126
+ }
127
+ if (Object.keys(models).length === 0) {
128
+ lines.push(`model/list of codex ${version} is empty — nothing sent`);
129
+ return report(false, { before, after: version });
130
+ }
131
+ let previous: string[] | null;
132
+ try {
133
+ previous = await deps.upload(version, models);
134
+ } catch (err) {
135
+ lines.push(`sending the model list FAILED: ${why(err)}`);
136
+ return report(false, { before, after: version });
137
+ }
138
+ const names = Object.keys(models);
139
+ const added = previous === null ? names : names.filter((m) => !previous.includes(m));
140
+ const removed = previous === null ? [] : previous.filter((m) => !(m in models));
141
+ lines.push(`codex ${version}: ${names.length} model(s) sent — ${names.join(", ")}`);
142
+ if (previous !== null) {
143
+ lines.push(`added: ${added.length > 0 ? added.join(", ") : "none"}; removed: ${removed.length > 0 ? removed.join(", ") : "none"}`);
144
+ }
145
+ return report(true, { before, after: version, added, removed });
146
+ }
147
+
148
+ // ── production deps ────────────────────────────────────────────────────────────────────────
149
+
150
+ function shell(command: string): Promise<string> {
151
+ return new Promise((resolve, reject) => {
152
+ exec(command, { timeout: SHELL_TIMEOUT_MS }, (err, stdout, stderr) => {
153
+ if (err) reject(new Error(`${command}: ${String(stderr || err.message).trim().split("\n")[0]}`));
154
+ else resolve(String(stdout).trim());
155
+ });
156
+ });
157
+ }
158
+
159
+ /** Whether `path` lies inside `dir` (case-insensitive on Windows). */
160
+ export function isUnder(path: string, dir: string, win: boolean = process.platform === "win32"): boolean {
161
+ const norm = (p: string): string => {
162
+ const q = p.replace(/\\/g, "/").replace(/\/+$/, "");
163
+ return win ? q.toLowerCase() : q;
164
+ };
165
+ return norm(path).startsWith(`${norm(dir)}/`);
166
+ }
167
+
168
+ /** The file `bin` runs: a path as given, a bare name through `lookup` (PATH); null if unknown. */
169
+ export async function resolveCodexBin(bin: string, lookup: (name: string) => Promise<string | null>): Promise<string | null> {
170
+ if (/[\\/]/.test(bin)) return bin;
171
+ if (!/^[A-Za-z0-9._-]+$/.test(bin)) return null; // never hand an odd name to a shell
172
+ return lookup(bin);
173
+ }
174
+
175
+ /**
176
+ * `<bin> --version` → its version, or null. The binary runs WITHOUT a shell (Codex review): an
177
+ * override with spaces (C:/Program Files/…) stays one argument, and no metacharacter reaches a shell.
178
+ */
179
+ export async function codexVersionOf(
180
+ bin: string,
181
+ run: (file: string, args: string[]) => Promise<string>,
182
+ ): Promise<string | null> {
183
+ return parseCodexVersion(await run(bin, ["--version"]).catch(() => ""));
184
+ }
185
+
186
+ function runFile(file: string, args: string[]): Promise<string> {
187
+ return new Promise((resolve, reject) => {
188
+ execFile(file, args, { timeout: SHELL_TIMEOUT_MS }, (err, stdout) => {
189
+ if (err) reject(err);
190
+ else resolve(String(stdout).trim());
191
+ });
192
+ });
193
+ }
194
+
195
+ function codexBin(): string {
196
+ return process.env.VIBER_CODEX_BIN?.trim() || "codex";
197
+ }
198
+
199
+ /** `codex-cli 0.170.0` → "0.170.0". */
200
+ export function parseCodexVersion(out: string): string | null {
201
+ return /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(out)?.[1] ?? null;
202
+ }
203
+
204
+ /**
205
+ * One `codex app-server`, initialize, walk `model/list`, then kill it. Spawned like the bridge
206
+ * spawns it (no shell): with a shell, `kill()` would end the shell and orphan the app-server.
207
+ */
208
+ async function readCatalogueFromAppServer(): Promise<Catalogue> {
209
+ const child = spawn(codexBin(), ["app-server"], { stdio: ["pipe", "pipe", "pipe"] });
210
+ let timer: ReturnType<typeof setTimeout> | undefined;
211
+ const deadline = new Promise<never>((_, reject) => {
212
+ timer = setTimeout(
213
+ () => reject(new Error(`codex app-server did not answer within ${APP_SERVER_TIMEOUT_MS} ms`)),
214
+ APP_SERVER_TIMEOUT_MS,
215
+ );
216
+ });
217
+ const pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
218
+ let buffer = "";
219
+ let nextId = 1;
220
+ child.stdout.setEncoding("utf-8");
221
+ child.stdout.on("data", (chunk: string) => {
222
+ buffer += chunk;
223
+ for (let nl = buffer.indexOf("\n"); nl !== -1; nl = buffer.indexOf("\n")) {
224
+ const line = buffer.slice(0, nl).trim();
225
+ buffer = buffer.slice(nl + 1);
226
+ if (line === "") continue;
227
+ let msg: { id?: unknown; result?: unknown; error?: { message?: string } };
228
+ try {
229
+ msg = JSON.parse(line);
230
+ } catch {
231
+ continue;
232
+ }
233
+ const waiter = typeof msg.id === "number" ? pending.get(msg.id) : undefined;
234
+ if (waiter === undefined) continue;
235
+ pending.delete(msg.id as number);
236
+ if (msg.error) waiter.reject(new Error(msg.error.message ?? "RPC error"));
237
+ else waiter.resolve(msg.result);
238
+ }
239
+ });
240
+ child.on("exit", (code) => {
241
+ for (const w of pending.values()) w.reject(new Error(`codex app-server exited (${code})`));
242
+ pending.clear();
243
+ });
244
+ child.on("error", (err) => {
245
+ for (const w of pending.values()) w.reject(err);
246
+ pending.clear();
247
+ });
248
+ const request = (method: string, params: unknown): Promise<unknown> =>
249
+ new Promise((resolve, reject) => {
250
+ const id = nextId++;
251
+ pending.set(id, { resolve, reject });
252
+ child.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
253
+ });
254
+ const exchange = async (): Promise<Catalogue> => {
255
+ await request("initialize", { clientInfo: { name: "viber-refresh-models", title: "Viber", version: "0.1.0" } });
256
+ child.stdin.write(`${JSON.stringify({ method: "initialized" })}\n`);
257
+ const catalogue = await readCodexCatalogue(
258
+ async (cursor) => (await request("model/list", { cursor, includeHidden: false })) as ModelListPage,
259
+ APP_SERVER_TIMEOUT_MS,
260
+ );
261
+ return Object.fromEntries(catalogue);
262
+ };
263
+ const run = exchange();
264
+ run.catch(() => {}); // past the deadline its own rejection has nobody left to tell
265
+ try {
266
+ return await Promise.race([run, deadline]);
267
+ } finally {
268
+ clearTimeout(timer);
269
+ child.kill();
270
+ }
271
+ }
272
+
273
+ /** The production deps, against this machine's runner identity (`<home>/.viber/runner.json`). */
274
+ export function productionRefreshDeps(home: string): RefreshDeps {
275
+ const auth = loadRunnerAuth(home);
276
+ const url = `${auth.base_url}/api/runners/${auth.runner_id}/codex-models`;
277
+ const headers = () => ({ Authorization: `Bearer ${auth.runner_token}`, ...cfAccessHeaders() });
278
+ return {
279
+ installedVersion: () => codexVersionOf(codexBin(), runFile),
280
+ npmLatest: async () => parseCodexVersion(await shell(`npm view ${CODEX_NPM_PACKAGE} version`)),
281
+ pathCodex: async () => {
282
+ // Codex review: the codex judged is the one model/list runs — codexBin(), the
283
+ // VIBER_CODEX_BIN override included. Only a bare name is looked up on PATH.
284
+ const found = await resolveCodexBin(codexBin(), async (name) => {
285
+ const where = process.platform === "win32" ? `where ${name}` : `command -v ${name}`;
286
+ return (await shell(where).catch(() => "")).split(/\r?\n/)[0]?.trim() || null;
287
+ });
288
+ const prefix = await shell("npm prefix -g").catch(() => "");
289
+ return { path: found, npmOwned: found !== null && prefix !== "" && isUnder(found, prefix) };
290
+ },
291
+ npmInstall: async (version) => {
292
+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`refusing to install version "${version}"`);
293
+ await shell(`npm i -g ${CODEX_NPM_PACKAGE}@${version}`);
294
+ },
295
+ readCatalogue: readCatalogueFromAppServer,
296
+ upload: async (cliVersion, models) => {
297
+ const res = await fetch(url, {
298
+ method: "PUT",
299
+ redirect: "error",
300
+ headers: { ...headers(), "Content-Type": "application/json" },
301
+ body: JSON.stringify({ cli_version: cliVersion, models }),
302
+ });
303
+ if (!res.ok) throw new Error(`${res.status} ${(await res.text()).slice(0, 200)}`);
304
+ const body = (await res.json()) as { previous?: unknown };
305
+ return Array.isArray(body.previous) ? body.previous.filter((m): m is string => typeof m === "string") : null;
306
+ },
307
+ };
308
+ }
309
+
310
+ /**
311
+ * THE entry point both triggers call — the app at startup and `viber-gateway refresh-models` —
312
+ * so they cannot drift apart. Never throws: a missing runner.json is a failed report too.
313
+ */
314
+ export async function refreshCodexModelsFor(home: string): Promise<RefreshReport> {
315
+ let deps: RefreshDeps;
316
+ try {
317
+ deps = productionRefreshDeps(home);
318
+ } catch (err) {
319
+ return { ok: false, lines: [`this machine is not enrolled (${why(err)}) — nothing sent`], added: [], removed: [] };
320
+ }
321
+ try {
322
+ return await refreshCodexModels(deps);
323
+ } catch (err) {
324
+ return { ok: false, lines: [`refresh FAILED: ${why(err)}`], added: [], removed: [] };
325
+ }
326
+ }
@@ -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);