viber-channel 0.8.45 → 0.8.47

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.
@@ -13,7 +13,6 @@
13
13
  *
14
14
  * Pure (no I/O) so it is trivially testable and identical across hosts.
15
15
  */
16
- import { CODEX_DEFAULT_PAIR } from "./codex_default.js";
17
16
 
18
17
  export function capabilitiesText(channelVersion: string | null = null): string {
19
18
  return [
@@ -120,7 +119,8 @@ export function capabilitiesText(channelVersion: string | null = null): string {
120
119
  " only; all roles of one template must share one permission) · count optional;",
121
120
  " model/effort: on claude leave them OUT (runtime default) UNLESS the owner asks:",
122
121
  " model opus|sonnet|haiku|fable, effort low|medium|high|xhigh|max. On codex BOTH are",
123
- ` REQUIRED: ${CODEX_DEFAULT_PAIR} unless the owner asks for another listed pair.`,
122
+ " REQUIRED: a model the owner's codex lists (see CODEX MODELS below), effort low",
123
+ " unless the owner asks for another.",
124
124
  " (On the web, sidebar ⋯ → Add agent launches ONE named agent from the same library.)",
125
125
  "OLD ONE-ROLE TEMPLATES (#678): a template with a single role was only a workaround",
126
126
  " to launch one agent before launch-agent existed. Do not create new ones:",
@@ -191,15 +191,13 @@ export function capabilitiesText(channelVersion: string | null = null): string {
191
191
  " permission REQUIRED read-only | read-write (gemma: read-only only)",
192
192
  " rolePrompt REQUIRED non-empty, ≤ 600 chars AFTER {prefix} expands to 32 chars",
193
193
  " model claude: optional, opus | sonnet | haiku | fable (a family, never a",
194
- " version); codex: REQUIRED, one of gpt-6.1-sol gpt-6-astra",
195
- " gpt-6-sol gpt-6-luna gpt-5.6-sol gpt-5.6-terra gpt-5.6-luna",
196
- " gpt-5.5; gemma: ≤ 64, stored but not applied",
194
+ " version); codex: REQUIRED, a model of the owner's codex list",
195
+ " (CODEX MODELS below); gemma: ≤ 64, stored but not applied",
197
196
  " effort claude: optional, low | medium | high | xhigh | max;",
198
- " codex: REQUIRED, one the model accepts — low..xhigh on all,",
199
- " max except gpt-5.5, ultra except the luna models and gpt-5.5;",
197
+ " codex: REQUIRED, one that model accepts (low on all);",
200
198
  " gemma: refused",
201
199
  " claude: leave model/effort OUT (runtime default) unless the",
202
- ` owner asks; codex: ${CODEX_DEFAULT_PAIR} unless the owner asks`,
200
+ " owner asks; codex: the model the owner names, effort low unless they ask",
203
201
  " plugins claude only, optional: [\"name@marketplace\", …] ≤ 8, enabled for",
204
202
  " that agent's session only (e.g. playwright@claude-plugins-official)",
205
203
  " chrome claude only, optional: true launches it with Claude in Chrome",
@@ -242,6 +240,15 @@ export function capabilitiesText(channelVersion: string | null = null): string {
242
240
  "to them FIRST and read their reply on that DM. Their `gh` has no usable token in",
243
241
  "the sandbox (#525): run gh (labels, PR comments) for them.",
244
242
  "",
243
+ "CODEX MODELS (#747): no list is written anywhere — the owner's list is what `model/list`",
244
+ "of THEIR codex CLI answers, sent by the Viber app when it starts. A codex role naming a",
245
+ "model that list lacks is refused \"not available\", and the refusal names the known ones.",
246
+ "When the owner says a new codex model is out, or such a refusal names a model the owner",
247
+ "wants, run on the owner's machine:",
248
+ " viber-gateway refresh-models",
249
+ "It updates the codex CLI when npm has a newer one, reads model/list and sends it; it prints",
250
+ "the codex version and the models sent (exit 0), or why it failed (exit 1). Then retry.",
251
+ "",
245
252
  "Never launch agents by calling vibe-master yourself: launch-team / launch-agent (or the",
246
253
  "web) is the ONLY launch path (#660), the one the runner supervises and relaunches.",
247
254
  "viber-gateway has no --help: an unknown verb runs the startup command (exit 2",
@@ -93,14 +93,11 @@ async function collectCatalogue(fetchPage: ModelListFetch, expired: () => boolea
93
93
  }
94
94
 
95
95
  /**
96
- * Throw unless THIS codex's catalogue carries the pair. One deadline covers the whole pagination;
97
- * an RPC failure, a malformed answer or the deadline all throw — the caller stops the bridge.
96
+ * #747: THIS codex's whole catalogue (`model/list`, every page), model slug → efforts, in the
97
+ * order codex answers. One deadline covers the whole pagination; an RPC failure, a malformed
98
+ * answer or the deadline all throw.
98
99
  */
99
- export async function verifyCodexPair(
100
- pair: CodexPair,
101
- fetchPage: ModelListFetch,
102
- timeoutMs: number,
103
- ): Promise<void> {
100
+ export async function readCodexCatalogue(fetchPage: ModelListFetch, timeoutMs: number): Promise<Map<string, string[]>> {
104
101
  let timer: ReturnType<typeof setTimeout> | undefined;
105
102
  let expired = false;
106
103
  const deadline = new Promise<never>((_, reject) => {
@@ -111,20 +108,33 @@ export async function verifyCodexPair(
111
108
  });
112
109
  const walk = collectCatalogue(fetchPage, () => expired);
113
110
  walk.catch(() => {}); // after the deadline its own rejection has nobody left to tell
111
+ try {
112
+ return await Promise.race([walk, deadline]);
113
+ } finally {
114
+ clearTimeout(timer);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Throw unless THIS codex's catalogue carries the pair (the bridge, at startup).
120
+ */
121
+ export async function verifyCodexPair(
122
+ pair: CodexPair,
123
+ fetchPage: ModelListFetch,
124
+ timeoutMs: number,
125
+ ): Promise<void> {
114
126
  let catalogue: Map<string, string[]>;
115
127
  try {
116
- catalogue = await Promise.race([walk, deadline]);
128
+ catalogue = await readCodexCatalogue(fetchPage, timeoutMs);
117
129
  } catch (err) {
118
130
  const why = err instanceof Error ? err.message : String(err);
119
131
  throw new Error(`cannot check codex model ${pair.model} / effort ${pair.effort}: ${why}`);
120
- } finally {
121
- clearTimeout(timer);
122
132
  }
123
133
  const efforts = catalogue.get(pair.model);
124
134
  if (efforts === undefined) {
125
135
  throw new Error(
126
136
  `codex model ${pair.model} is absent from the catalogue of THIS codex (has: ${[...catalogue.keys()].join(", ")}) — ` +
127
- "update codex or re-edit the template",
137
+ "run `viber-gateway refresh-models` (it updates codex) or re-edit the template",
128
138
  );
129
139
  }
130
140
  if (!efforts.includes(pair.effort)) {
@@ -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
+ }
package/lib/macro_run.ts CHANGED
@@ -22,7 +22,7 @@ import { spawn } from "./hidden_proc.js";
22
22
  import { MACRO_NAME_RE, MACRO_SHA256_RE, macroSha256, readMacroList } from "./macro_list.js";
23
23
  import { MACRO_HOST_REFUSED_EXIT, MACRO_HOST_REFUSED_LINE, encodedHost } from "./macro_job_host.js";
24
24
  import { presenceRecordPath, readPresenceRecord } from "./presence_record.js";
25
- import { processStartTime } from "./process_start.js";
25
+ import { enumerateStartTimes } from "./process_start.js";
26
26
  import { readRegistry, registryPath } from "./runner_registry.js";
27
27
 
28
28
  /** Reasons a macro run is refused or fails on the runner (step-01 contract). PARITY: the server's
@@ -86,7 +86,7 @@ export interface MacroDeps {
86
86
  home: string;
87
87
  inflight: { has(id: string): boolean; mark(id: string, fencing: number): void; clear(id: string): void };
88
88
  /** The agent, if this runner launched it and it is alive; otherwise the refusal. */
89
- resolveAgent: (instanceId: string) => MacroAgent | { refused: "macro_agent_unknown" | "macro_agent_dead"; why: string };
89
+ resolveAgent: (instanceId: string) => MacroResolved | Promise<MacroResolved>;
90
90
  interpreter: () => string;
91
91
  runHost: (copyPath: string, interpreter: string, env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<HostOutcome>;
92
92
  timeoutMs?: number;
@@ -129,7 +129,7 @@ export async function executeMacroClaim(cmd: MacroClaim, deps: MacroDeps): Promi
129
129
  const entry = list.macros.get(name);
130
130
  if (!entry) return refuse("macro_unknown", `no local macro named ${name}`);
131
131
 
132
- const agent = deps.resolveAgent(instanceId);
132
+ const agent = await deps.resolveAgent(instanceId);
133
133
  if ("refused" in agent) return refuse(agent.refused, agent.why);
134
134
 
135
135
  const interpreter = deps.interpreter();
@@ -245,15 +245,22 @@ export function windowsPowerShell(source: NodeJS.ProcessEnv = process.env): stri
245
245
  return join(source.SystemRoot ?? "", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
246
246
  }
247
247
 
248
+ export type MacroResolved = MacroAgent | { refused: "macro_agent_unknown" | "macro_agent_dead"; why: string };
249
+
248
250
  /**
249
251
  * The agent, from the runner's registry (an entry it launched, still active) and its presence
250
252
  * record (pid alive WITH the same creation time). Unknown is refused, never assumed alive.
253
+ *
254
+ * #737: liveness comes from the SAME enumeration table the roster uses (positive control: it saw
255
+ * the runner itself). A probe that failed or timed out is `unknown`, never `dead` — the single
256
+ * synchronous probe used before turned a slow PowerShell into "the agent's process is gone"
257
+ * on a live, relaunched agent.
251
258
  */
252
- export function resolveAgentOnDisk(
259
+ export async function resolveAgentOnDisk(
253
260
  identity: string,
254
261
  instanceId: string,
255
- opts: { lockDir?: string; startTimeOf?: (pid: number) => number | undefined } = {},
256
- ): MacroAgent | { refused: "macro_agent_unknown" | "macro_agent_dead"; why: string } {
262
+ opts: { lockDir?: string; enumerate?: () => Promise<Map<number, number | undefined> | undefined> } = {},
263
+ ): Promise<MacroResolved> {
257
264
  const reg = readRegistry(registryPath(identity, opts.lockDir));
258
265
  if (reg.kind !== "ok") return { refused: "macro_agent_unknown", why: `runner registry ${reg.kind}` };
259
266
  const entry = Object.values(reg.registry.entries).find((e) => e.instance_id === instanceId);
@@ -263,8 +270,11 @@ export function resolveAgentOnDisk(
263
270
  if (rec.kind !== "ok") return { refused: "macro_agent_unknown", why: `presence record ${rec.kind}` };
264
271
  if (rec.record.state === "ended") return { refused: "macro_agent_dead", why: "the agent ended" };
265
272
  if (rec.record.start_time_ms === null) return { refused: "macro_agent_unknown", why: "the agent's start time is not known yet" };
266
- const observed = (opts.startTimeOf ?? processStartTime)(rec.record.pid);
267
- if (observed === undefined) return { refused: "macro_agent_dead", why: "the agent's process is gone" };
273
+ const table = await (opts.enumerate ?? (() => enumerateStartTimes()))();
274
+ if (table === undefined) return { refused: "macro_agent_unknown", why: "process enumeration failed: cannot tell whether the agent is alive" };
275
+ if (!table.has(rec.record.pid)) return { refused: "macro_agent_dead", why: "the agent's process is gone" };
276
+ const observed = table.get(rec.record.pid);
277
+ if (observed === undefined) return { refused: "macro_agent_unknown", why: `pid ${rec.record.pid} has no readable start time` };
268
278
  if (observed !== rec.record.start_time_ms) return { refused: "macro_agent_dead", why: "the agent's pid now belongs to another process" };
269
279
  return { name: entry.name, instanceId, projectId: entry.project_id, workspace: entry.workspace };
270
280
  }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * registry_prune.ts — #737 step-03: the ONE-SHOT cleanup of a runner registry that accumulated
3
+ * agents long gone (186 `active` measured on 2026-11-04).
4
+ *
5
+ * Rule (JP): an agent OFFLINE and already REVOKED (or unknown) on the server is closed now; an
6
+ * agent offline but not revoked is left to the runner's 7-day absence rule. NEVER a live agent:
7
+ * offline is proven by the presence record (absent or ended) or by its pid missing from a
8
+ * controlled process table, or carrying another start time. Anything not provable is KEPT.
9
+ *
10
+ * Nothing here writes the registry: the closes travel as #687 close requests, which the runner
11
+ * applies on its next beat inside its own write — the runner stays the registry's only writer.
12
+ */
13
+ import { presenceRecordPath, readPresenceRecord } from "./presence_record.js";
14
+ import type { ProcessTable } from "./runner_roster.js";
15
+ import type { Registry } from "./runner_registry.js";
16
+
17
+ export type PruneVerdict =
18
+ | { kind: "close"; why: string }
19
+ | { kind: "wait"; why: string }
20
+ | { kind: "keep"; why: string };
21
+
22
+ export interface PruneLine {
23
+ key: string;
24
+ name: string;
25
+ instance_id: string | null;
26
+ verdict: PruneVerdict;
27
+ }
28
+
29
+ type RecordRead = ReturnType<typeof readPresenceRecord>;
30
+
31
+ /** Is this entry's agent OFFLINE, provably? `null` = alive or not provable (kept). */
32
+ export function offlineBecause(read: RecordRead, table: ProcessTable): string | null {
33
+ if (read.kind === "absent") return "no presence record";
34
+ if (read.kind !== "ok") return null;
35
+ const rec = read.record;
36
+ if (rec.state === "ended") return `ended (${rec.ended_reason ?? "?"})`;
37
+ if (rec.start_time_ms === null) return null;
38
+ if (!table.has(rec.pid)) return `pid ${rec.pid} gone`;
39
+ const observed = table.get(rec.pid);
40
+ if (observed === undefined) return null;
41
+ return observed === rec.start_time_ms ? null : `pid ${rec.pid} recycled`;
42
+ }
43
+
44
+ /**
45
+ * Classify every ACTIVE entry. `overOnServer` = instances the server holds revoked or has no row
46
+ * for; `undefined` when the server was not asked (then nothing is closed, all offline ones wait).
47
+ */
48
+ export function planPrune(
49
+ registry: Registry,
50
+ readRecord: (instanceId: string) => RecordRead,
51
+ table: ProcessTable,
52
+ overOnServer: ReadonlySet<string> | undefined,
53
+ ): PruneLine[] {
54
+ const lines: PruneLine[] = [];
55
+ for (const [key, e] of Object.entries(registry.entries)) {
56
+ if (e.state !== "active") continue;
57
+ const line = (verdict: PruneVerdict): PruneLine => ({ key, name: e.name, instance_id: e.instance_id, verdict });
58
+ if (e.instance_id === null) {
59
+ lines.push(line({ kind: "wait", why: "no instance yet (relaunch starting?) — 7-day absence rule" }));
60
+ continue;
61
+ }
62
+ const read = readRecord(e.instance_id);
63
+ const offline = offlineBecause(read, table);
64
+ if (offline === null) {
65
+ lines.push(line({ kind: "keep", why: read.kind === "ok" ? "alive, or not provably gone" : `record ${read.kind}` }));
66
+ continue;
67
+ }
68
+ if (overOnServer?.has(e.instance_id)) {
69
+ lines.push(line({ kind: "close", why: `offline (${offline}) and revoked on the server` }));
70
+ continue;
71
+ }
72
+ lines.push(line({ kind: "wait", why: `offline (${offline}), not revoked — 7-day absence rule` }));
73
+ }
74
+ return lines;
75
+ }
76
+
77
+ /** The default record reader of one backend. */
78
+ export function recordReader(identity: string, lockDir?: string): (instanceId: string) => RecordRead {
79
+ return (id) => readPresenceRecord(presenceRecordPath(identity, id, lockDir));
80
+ }
@@ -41,6 +41,9 @@ export const REGISTRY_SCHEMA_VERSION = 1;
41
41
  /** Closed entries older than this are dropped, so the file cannot grow forever. */
42
42
  export const CLOSED_ENTRY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
43
43
 
44
+ /** #737 (JP): an active entry whose agent has been seen nowhere for this long is closed. */
45
+ export const ABSENT_CLOSE_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
46
+
44
47
  /**
45
48
  * The gateway's launch id of one member of one command — a COPY of
46
49
  * `attemptLaunchId` (`viber-gateway/lib/team_derivation.ts`): `launch-` + the first 32
@@ -122,6 +125,11 @@ export interface RegistryEntry {
122
125
  * after its handover was acknowledged or refused for good.
123
126
  */
124
127
  predecessors?: string[];
128
+ /**
129
+ * #737: since when no live agent carries this entry (epoch ms), as the runner OBSERVED it;
130
+ * null/absent while one runs. Drives the 7-day close of an agent that was never revoked.
131
+ */
132
+ absent_since?: number | null;
125
133
  }
126
134
 
127
135
  export interface Registry {
@@ -193,6 +201,7 @@ function isEntry(key: string, v: unknown): v is RegistryEntry {
193
201
  (v.pending_close === undefined || isStrOrNull(v.pending_close)) &&
194
202
  (v.handover_from === undefined || (Array.isArray(v.handover_from) && v.handover_from.every((x) => typeof x === "string"))) &&
195
203
  (v.predecessors === undefined || (Array.isArray(v.predecessors) && v.predecessors.every((x) => typeof x === "string"))) &&
204
+ (v.absent_since === undefined || v.absent_since === null || typeof v.absent_since === "number") &&
196
205
  (v.project_id === null || typeof v.project_id === "number");
197
206
  const okState = v.state === "active" || v.state === "closed";
198
207
  const okClosedAt = v.closed_at === null || typeof v.closed_at === "number";
@@ -428,6 +437,58 @@ export function markClosed(registry: Registry, instanceIds: readonly string[], n
428
437
  return changed;
429
438
  }
430
439
 
440
+ // ── #737: entries whose agent is over, found without a local end ─────────────────────────────
441
+
442
+ /**
443
+ * Track absence from an OBSERVED machine. `alive` = every instance seen present or not classifiable
444
+ * (uncertain counts as alive: an instrument that did not see never starts a clock). Call ONLY when the
445
+ * enumeration passed its control.
446
+ */
447
+ export function markAbsence(registry: Registry, alive: ReadonlySet<string>, now: number): boolean {
448
+ let changed = false;
449
+ for (const entry of Object.values(registry.entries)) {
450
+ if (entry.state !== "active") continue;
451
+ const running = entry.instance_id !== null && alive.has(entry.instance_id);
452
+ if (running) {
453
+ if (entry.absent_since !== undefined && entry.absent_since !== null) {
454
+ entry.absent_since = null;
455
+ changed = true;
456
+ }
457
+ } else if (entry.absent_since === undefined || entry.absent_since === null) {
458
+ // From the first OBSERVED absence, never from `launched_at`: a relaunch still starting has no
459
+ // instance yet, and a launch date (another clock, an old entry) must not close it at once.
460
+ entry.absent_since = now;
461
+ changed = true;
462
+ }
463
+ }
464
+ return changed;
465
+ }
466
+
467
+ /** Active entries whose agent is absent: the ids worth asking the server about. */
468
+ export function absentInstanceIds(registry: Registry): string[] {
469
+ return Object.values(registry.entries)
470
+ .filter((e) => e.state === "active" && e.instance_id !== null && e.absent_since !== undefined && e.absent_since !== null)
471
+ .map((e) => e.instance_id as string);
472
+ }
473
+
474
+ /**
475
+ * #737 (JP): close an ABSENT entry at once when the server says its instance is over (revoked, or no
476
+ * row at all), and after `ABSENT_CLOSE_AFTER_MS` otherwise. Never an entry whose agent runs:
477
+ * `absent_since` is only set by `markAbsence` from an observed machine.
478
+ */
479
+ export function closeAbsent(registry: Registry, overOnServer: ReadonlySet<string>, now: number): string[] {
480
+ const closed: string[] = [];
481
+ for (const [key, entry] of Object.entries(registry.entries)) {
482
+ if (entry.state !== "active" || entry.absent_since === undefined || entry.absent_since === null) continue;
483
+ const over = entry.instance_id !== null && overOnServer.has(entry.instance_id);
484
+ if (!over && now - entry.absent_since < ABSENT_CLOSE_AFTER_MS) continue;
485
+ entry.state = "closed";
486
+ entry.closed_at = now;
487
+ closed.push(key);
488
+ }
489
+ return closed;
490
+ }
491
+
431
492
  // ── #687: close requests — the runner stays the ONLY writer of its registry ──────────────────
432
493
  //
433
494
  // A dissolve kills, THEN revokes: by then the runner has reported the agent `down` (ambiguous:
@@ -163,6 +163,8 @@ export async function relaunchInstance(requestedId: string, deps: RelaunchDeps):
163
163
  e.instance_id = null;
164
164
  e.launched_at = now;
165
165
  e.state = "active";
166
+ // #737: the absence clock belongs to the OLD agent; the new one starts with none.
167
+ e.absent_since = null;
166
168
  // This relaunch has no gateway job name: the old launch id must not let an old
167
169
  // process's record join the NEW entry exactly (Opus I2). The new agent joins by
168
170
  // (project, name), then its own instance id.
@@ -81,6 +81,8 @@ export interface Roster {
81
81
  present: RosterPresent[];
82
82
  closed: string[];
83
83
  down: string[];
84
+ /** #735: "full" = the complete state (the server downs what it does not list); "delta" = changes only. */
85
+ mode?: "full" | "delta";
84
86
  }
85
87
 
86
88
  export interface CollectedRoster {
@@ -96,19 +98,32 @@ export interface CollectedRoster {
96
98
  ends: string[];
97
99
  /** #708: where to read what each PRESENT agent runs on — exactly the present this beat carries. */
98
100
  runtimeSources: RuntimeSource[];
101
+ /**
102
+ * #735 — did the runner SEE the machine? false when the directory could not be read or
103
+ * the enumeration failed its control: then nothing it reports may be read as an absence.
104
+ */
105
+ observed: boolean;
106
+ /** #735 — ids the runner could not classify (start time unknown…): neither present nor absent. */
107
+ uncertain: Set<string>;
108
+ /** #735 — true when `capRoster` deferred entries: the roster is then not the complete state. */
109
+ capped: boolean;
110
+ /** #735 — every present id OBSERVED, before the cap: what runs, whatever this beat carries. */
111
+ allPresent: Set<string>;
99
112
  }
100
113
 
101
114
  /** The process table: pid → start time, or `undefined` when the instrument did not see. */
102
115
  export type ProcessTable = Map<number, number | undefined>;
103
116
 
104
117
  export interface CollectDeps {
118
+ /** #735: present already acknowledged — a capped roster keeps the OTHERS first, so none starves (Codex). */
119
+ isKnown?: (p: RosterPresent) => boolean;
105
120
  identityBaseUrl: string;
106
121
  lockDir?: string;
107
122
  /** ONE enumeration of the machine (`enumerateStartTimes`); undefined = not seen. */
108
123
  enumerate: () => Promise<ProcessTable | undefined>;
109
124
  }
110
125
 
111
- function emptyCollected(note?: string): CollectedRoster {
126
+ function emptyCollected(note?: string, observed = true): CollectedRoster {
112
127
  return {
113
128
  roster: { present: [], closed: [], down: [] },
114
129
  seen: [],
@@ -116,6 +131,10 @@ function emptyCollected(note?: string): CollectedRoster {
116
131
  notes: note === undefined ? [] : [note],
117
132
  ends: [],
118
133
  runtimeSources: [],
134
+ observed,
135
+ uncertain: new Set(),
136
+ capped: false,
137
+ allPresent: new Set(),
119
138
  };
120
139
  }
121
140
 
@@ -174,24 +193,30 @@ export async function collectRoster(deps: CollectDeps): Promise<CollectedRoster>
174
193
  names = readdirSync(dir).filter((n) => RECORD_FILE_RE.test(n));
175
194
  } catch (err) {
176
195
  if ((err as NodeJS.ErrnoException).code === "ENOENT") return emptyCollected();
177
- return emptyCollected(`presence directory unreadable (${String(err)}): nothing reported`);
196
+ return emptyCollected(`presence directory unreadable (${String(err)}): nothing reported`, false);
178
197
  }
179
198
  if (names.length === 0) return emptyCollected();
180
199
 
181
200
  const table = await deps.enumerate();
182
- if (table === undefined) return emptyCollected("process enumeration failed its control: nothing reported");
201
+ // #735: NOT an empty machine — an instrument that did not see. Reported as such, so
202
+ // the beat sends no change and never a snapshot built from it (the waves of #735).
203
+ if (table === undefined) return emptyCollected("process enumeration failed its control: nothing reported", false);
183
204
 
184
205
  const out = emptyCollected();
185
206
  for (const name of names) {
186
207
  const path = join(dir, name);
187
208
  const read = readPresenceRecord(path);
188
209
  if (read.kind !== "ok") {
189
- if (read.kind === "unreadable") out.notes.push(`${name}: unreadable (${read.error})`);
210
+ if (read.kind === "unreadable") {
211
+ out.notes.push(`${name}: unreadable (${read.error})`);
212
+ out.uncertain.add(name.slice(0, 32));
213
+ }
190
214
  continue;
191
215
  }
192
216
  const c = classifyRecord(read.record, table);
193
217
  if (c.kind === "unknown") {
194
218
  out.notes.push(c.why);
219
+ out.uncertain.add(read.record.instance_id);
195
220
  continue;
196
221
  }
197
222
  const { record } = c;
@@ -216,11 +241,12 @@ export async function collectRoster(deps: CollectDeps): Promise<CollectedRoster>
216
241
  out.ends.push(endLine(record, c.kind));
217
242
  }
218
243
  }
219
- return capRoster(out);
244
+ for (const p of out.roster.present) out.allPresent.add(p.instance_id);
245
+ return capRoster(out, deps.isKnown);
220
246
  }
221
247
 
222
248
  /** Keep the beat under `ROSTER_MAX`: ended entries first (they must not be lost), then present. */
223
- function capRoster(c: CollectedRoster): CollectedRoster {
249
+ function capRoster(c: CollectedRoster, isKnown?: (p: RosterPresent) => boolean): CollectedRoster {
224
250
  const { present, closed, down } = c.roster;
225
251
  const total = present.length + closed.length + down.length;
226
252
  if (total <= ROSTER_MAX) return c;
@@ -229,7 +255,9 @@ function capRoster(c: CollectedRoster): CollectedRoster {
229
255
  room -= keptClosed.length;
230
256
  const keptDown = down.slice(0, room);
231
257
  room -= keptDown.length;
232
- const keptPresent = present.slice(0, room);
258
+ // #735: what the server does not hold yet goes first; the known ones are kept alive anyway.
259
+ const ordered = isKnown ? [...present.filter((p) => !isKnown(p)), ...present.filter((p) => isKnown(p))] : present;
260
+ const keptPresent = ordered.slice(0, room);
233
261
  const kept = new Set([...keptClosed, ...keptDown]);
234
262
  for (const id of [...c.endedFiles.keys()]) if (!kept.has(id)) c.endedFiles.delete(id);
235
263
  // The registry must only learn what this beat actually told the server (Codex).
@@ -237,6 +265,7 @@ function capRoster(c: CollectedRoster): CollectedRoster {
237
265
  c.seen = c.seen.filter((s) => sentPresent.has(s.instance_id));
238
266
  c.runtimeSources = c.runtimeSources.filter((s) => sentPresent.has(s.instance_id));
239
267
  c.roster = { present: keptPresent, closed: keptClosed, down: keptDown };
268
+ c.capped = true;
240
269
  c.notes.push(`roster capped at ${ROSTER_MAX} (had ${total}); the rest goes next beat`);
241
270
  return c;
242
271
  }
@@ -318,9 +347,15 @@ export interface ApplyAckDeps {
318
347
  * lease and a beat id), and — only when the presence was APPLIED — remove the
319
348
  * acknowledged closed/down records. Returns the ids whose record was removed.
320
349
  */
321
- export function applyAck(collected: CollectedRoster, ack: RosterAck, deps: ApplyAckDeps): string[] {
350
+ export function applyAck(
351
+ collected: CollectedRoster,
352
+ ack: RosterAck,
353
+ deps: ApplyAckDeps,
354
+ /** #735: the agents to cover — by default the present the runner just observed. */
355
+ coverFor: readonly RosterPresent[] = collected.roster.present,
356
+ ): string[] {
322
357
  if (ack.beat_id !== null) {
323
- for (const p of collected.roster.present) {
358
+ for (const p of coverFor) {
324
359
  if (!ack.instances.has(p.instance_id)) continue;
325
360
  const coverage: Coverage = {
326
361
  schema_version: 1,
@@ -445,10 +480,15 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
445
480
  const log = deps.log ?? ((l: string) => process.stderr.write(`${l}\n`));
446
481
  const now = deps.now ?? Date.now;
447
482
  const identity = runnerIdentity(auth);
483
+ const state = presenceState(identity, deps.lockDir);
448
484
  const collected = await collectRoster({
449
485
  identityBaseUrl: identity,
450
486
  lockDir: deps.lockDir,
451
487
  enumerate: deps.enumerate ?? (() => enumerateStartTimes()),
488
+ isKnown: (p) => {
489
+ const k = state.known.get(p.instance_id);
490
+ return k !== undefined && k.conversation_id === p.conversation_id && k.started_at === p.started_at;
491
+ },
452
492
  });
453
493
  for (const note of collected.notes) noteOnce(note, log);
454
494
  // Resent every beat until acknowledged: logged ONCE per distinct line.
@@ -457,6 +497,8 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
457
497
  // server acknowledges it — so no greyed ghost stays behind the new agent.
458
498
  const { closes: pendingCloses, replaced } = pendingClosesOf(identity, deps.lockDir, collected.roster);
459
499
  collected.roster.closed.push(...pendingCloses);
500
+ // #735: what this beat tells the server — a full snapshot, the changes, or nothing.
501
+ const plan = planPresence(state, collected, replaced);
460
502
 
461
503
  const beatBody: Record<string, unknown> = {
462
504
  capabilities: {
@@ -469,7 +511,7 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
469
511
  },
470
512
  // #627 (JP, decision A): the new instance of each pair takes the old one's
471
513
  // conversations — the server re-invites it once it is online.
472
- roster: replaced.length > 0 ? { ...collected.roster, replaced } : collected.roster,
514
+ roster: replaced.length > 0 ? { ...plan.roster, replaced } : plan.roster,
473
515
  };
474
516
  // #708: the roster first; runtime entries only take the room it leaves under the cap.
475
517
  const runtimeSent = withRuntime(beatBody, collected.runtimeSources, deps.runtime);
@@ -489,10 +531,12 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
489
531
  body,
490
532
  });
491
533
  } catch {
534
+ state.resync = true; // #735: back on the network → the complete state, once
492
535
  return "ok"; // best-effort: nothing acknowledged, nothing changed
493
536
  }
494
537
  if (resp.status === 401) return "revoked";
495
538
  if (resp.status < 200 || resp.status >= 300) {
539
+ state.resync = true;
496
540
  // Not swallowed: a 4xx here means the server refused the beat — the RUNNER itself
497
541
  // then goes offline after 90 s (Opus, step-03 review).
498
542
  noteOnce(`heartbeat refused: HTTP ${resp.status}`, log);
@@ -513,17 +557,30 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
513
557
  } else {
514
558
  unappliedBeats = 0;
515
559
  }
516
- const removed = applyAck(collected, ack, { identityBaseUrl: identity, lockDir: deps.lockDir, now, log });
560
+ // #735: an unseen machine still has its agents — covered from the last acknowledged state.
561
+ const coverFor = collected.observed ? collected.roster.present : [...state.known.values()];
562
+ const removed = applyAck(collected, ack, { identityBaseUrl: identity, lockDir: deps.lockDir, now, log }, coverFor);
563
+ settlePresence(state, plan, ack, collected);
517
564
  const closedNow = removed.filter((id) => collected.roster.closed.includes(id));
518
565
  // #687: closes REQUESTED by a dissolve (it revoked them after the kill) — applied in THIS write,
519
566
  // so the runner stays the registry's only writer, and dropped only once the write succeeded.
520
567
  const requested = reg.readCloseRequests(identity, deps.lockDir);
521
568
  let settled: string[] = [];
569
+ // #737: which absent entries the server holds over (revoked, or no row) — at most every 10 min.
570
+ const overOnServer = collected.observed ? await queryEndedOnServer(auth, deps, identity, now(), log) : new Set<string>();
571
+ const alive = new Set([...collected.allPresent, ...collected.uncertain]);
522
572
  const result = reg.updateRegistry(reg.registryPath(identity, deps.lockDir), (r) => {
523
573
  const synced = reg.syncFromRecords(r, collected.seen);
524
574
  const closed = reg.markClosed(r, [...closedNow, ...requested.map((q) => q.instance_id)], now());
525
575
  settled = reg.settledCloseRequests(r, requested, now());
526
- let cleared = false;
576
+ // #737: only from a machine the runner SAW — a failed enumeration starts no absence clock.
577
+ const absence = collected.observed && reg.markAbsence(r, alive, now());
578
+ const closedAbsent = collected.observed ? reg.closeAbsent(r, overOnServer, now()) : [];
579
+ if (closedAbsent.length > 0) log(`[runner] registry: closed ${closedAbsent.length} absent agent(s) (revoked on the server, or absent for 7 days)`);
580
+ const before = Object.keys(r.entries).length;
581
+ reg.pruneClosed(r, now());
582
+ const pruned = Object.keys(r.entries).length !== before;
583
+ let cleared = absence || closedAbsent.length > 0 || pruned;
527
584
  if (ack.presence_applied) {
528
585
  for (const e of Object.values(r.entries)) {
529
586
  // An older predecessor (handover_from) is done once the server no longer
@@ -569,6 +626,71 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
569
626
  return "ok";
570
627
  }
571
628
 
629
+ /** #737: how often the runner asks the server which absent instances are over. */
630
+ export const ENDED_QUERY_EVERY_MS = 10 * 60 * 1000;
631
+ /** Same bound as the server's `ENDED_QUERY_MAX_IDS`. */
632
+ export const ENDED_QUERY_BATCH = 200;
633
+ let lastEndedQueryAt: number | null = null;
634
+
635
+ /** Test seam: forget when the server was last asked. */
636
+ export function resetEndedQuery(): void {
637
+ lastEndedQueryAt = null;
638
+ }
639
+
640
+ /**
641
+ * #737: ask the server which of these instances are over for good (`revoked` or `missing`), in
642
+ * batches. Read-only. `undefined` when ANY batch failed: the caller then closes nothing it did not
643
+ * already have an answer for — an unanswered id is never read as ended.
644
+ */
645
+ export async function fetchEndedInstances(
646
+ auth: RosterBeatAuth,
647
+ ids: readonly string[],
648
+ opts: { fetchImpl?: typeof fetch; headers?: () => Record<string, string> } = {},
649
+ ): Promise<{ over: Set<string> } | { error: string }> {
650
+ const over = new Set<string>();
651
+ for (let i = 0; i < ids.length; i += ENDED_QUERY_BATCH) {
652
+ let resp: Response;
653
+ try {
654
+ resp = await (opts.fetchImpl ?? fetch)(`${auth.base_url}/api/runners/${auth.runner_id}/instances/ended`, {
655
+ method: "POST",
656
+ redirect: "error",
657
+ headers: { Authorization: `Bearer ${auth.runner_token}`, "Content-Type": "application/json", ...(opts.headers?.() ?? {}) },
658
+ body: JSON.stringify({ ids: ids.slice(i, i + ENDED_QUERY_BATCH) }),
659
+ });
660
+ } catch (err) {
661
+ return { error: String(err) };
662
+ }
663
+ // A server older than #737 answers 404: nothing closes early, the 7-day rule still holds.
664
+ if (!resp.ok) return { error: `HTTP ${resp.status}` };
665
+ const body = (await resp.json().catch(() => null)) as { revoked?: unknown; missing?: unknown } | null;
666
+ if (body === null || !Array.isArray(body.revoked) || !Array.isArray(body.missing)) return { error: "malformed answer" };
667
+ for (const id of [...body.revoked, ...body.missing]) if (typeof id === "string") over.add(id);
668
+ }
669
+ return { over };
670
+ }
671
+
672
+ /** The beat's throttled use of `fetchEndedInstances`, over the registry's ABSENT instances. */
673
+ async function queryEndedOnServer(
674
+ auth: RosterBeatAuth,
675
+ deps: RosterBeatDeps,
676
+ identity: string,
677
+ now: number,
678
+ log: (line: string) => void,
679
+ ): Promise<Set<string>> {
680
+ if (lastEndedQueryAt !== null && now - lastEndedQueryAt < ENDED_QUERY_EVERY_MS) return new Set();
681
+ const read = reg.readRegistry(reg.registryPath(identity, deps.lockDir));
682
+ if (read.kind !== "ok") return new Set();
683
+ const ids = reg.absentInstanceIds(read.registry);
684
+ lastEndedQueryAt = now;
685
+ if (ids.length === 0) return new Set();
686
+ const answer = await fetchEndedInstances(auth, ids, { fetchImpl: deps.fetchImpl, headers: deps.headers });
687
+ if ("error" in answer) {
688
+ noteOnce(`ended-instances query failed: ${answer.error}`, log);
689
+ return new Set();
690
+ }
691
+ return answer.over;
692
+ }
693
+
572
694
  /** A note logged at every 30 s beat would drown the log: once per distinct text. */
573
695
  const loggedNotes = new Set<string>();
574
696
  function noteOnce(note: string, log: (line: string) => void): void {
@@ -645,3 +767,105 @@ export function storedRuntime(sent: RuntimeDelta, ackBody: unknown): RuntimeDelt
645
767
  for (const id of ids) if (typeof id === "string" && id in sent) out[id] = sent[id] as RuntimeDelta[string];
646
768
  return out;
647
769
  }
770
+
771
+ /**
772
+ * #735 — what the server holds for this runner, as the runner believes it: the present
773
+ * instances it ACCEPTED (named in an answer). The runner sends only what differs from it,
774
+ * and a complete snapshot (`resync`) when it starts and each time it comes back.
775
+ */
776
+ export interface PresenceState {
777
+ known: Map<string, RosterPresent>;
778
+ resync: boolean;
779
+ /**
780
+ * Ids the server answered as live that the machine does not run: downed on the next beat.
781
+ * The reconciliation that does not depend on a full snapshot — so it holds past
782
+ * `ROSTER_MAX`, where a full snapshot cannot be sent (Codex review).
783
+ */
784
+ stale: Set<string>;
785
+ }
786
+
787
+ const presenceStates = new Map<string, PresenceState>();
788
+
789
+ function presenceState(identity: string, lockDir: string | undefined): PresenceState {
790
+ const key = `${identity}\u0000${lockDir ?? ""}`;
791
+ let st = presenceStates.get(key);
792
+ if (st === undefined) {
793
+ st = { known: new Map(), resync: true, stale: new Set() };
794
+ presenceStates.set(key, st);
795
+ }
796
+ return st;
797
+ }
798
+
799
+ /**
800
+ * #735 — ask for a complete snapshot on the next beat (the runner's stream reconnected:
801
+ * an event may have been lost while it was away).
802
+ */
803
+ export function requestPresenceResync(): void {
804
+ for (const st of presenceStates.values()) st.resync = true;
805
+ }
806
+
807
+ export interface PresencePlan {
808
+ roster: Roster;
809
+ /** Ids this beat downs because they vanished from the machine without a record. */
810
+ vanished: string[];
811
+ }
812
+
813
+ /**
814
+ * #735 — the roster ONE beat sends. PURE.
815
+ * - the machine was not seen → no change at all: the server keeps everyone alive;
816
+ * - a resync is due and the view is complete → the full snapshot;
817
+ * - otherwise → what differs from `known`: new or changed present, every ended record,
818
+ * and the known agents that vanished without one (down).
819
+ * A relaunch pair needs its new instance in the same roster: it is always carried.
820
+ */
821
+ export function planPresence(state: PresenceState, collected: CollectedRoster, replaced: readonly ReplacedPair[]): PresencePlan {
822
+ const { roster } = collected;
823
+ if (!collected.observed) {
824
+ return { roster: { present: [], closed: [...roster.closed], down: [], mode: "delta" }, vanished: [] };
825
+ }
826
+ if (state.resync && !collected.capped && collected.uncertain.size === 0) {
827
+ return { roster: { ...roster, mode: "full" }, vanished: [] };
828
+ }
829
+ const needed = new Set(replaced.map((r) => r.new));
830
+ const present = roster.present.filter((p) => {
831
+ const k = state.known.get(p.instance_id);
832
+ return needed.has(p.instance_id) || k === undefined || k.conversation_id !== p.conversation_id || k.started_at !== p.started_at;
833
+ });
834
+ const seen = new Set([...roster.present.map((p) => p.instance_id), ...roster.closed, ...roster.down]);
835
+ const listed = new Set([...seen, ...present.map((p) => p.instance_id)]);
836
+ const candidates = [
837
+ ...(collected.capped ? [] : [...state.known.keys()]),
838
+ ...state.stale,
839
+ ].filter((id) => !seen.has(id) && !collected.allPresent.has(id) && !collected.uncertain.has(id));
840
+ // Never past the server's cap: what does not fit goes next beat (it stays known / stale).
841
+ const room = Math.max(0, ROSTER_MAX - present.length - roster.closed.length - roster.down.length);
842
+ const vanished = [...new Set(candidates)].filter((id) => !listed.has(id)).slice(0, room);
843
+ return { roster: { present, closed: roster.closed, down: [...roster.down, ...vanished], mode: "delta" }, vanished };
844
+ }
845
+
846
+ /** #735 — after a 2xx: learn what the server accepted, forget what it applied as ended. */
847
+ export function settlePresence(state: PresenceState, plan: PresencePlan, ack: RosterAck, collected?: CollectedRoster): void {
848
+ const { roster } = plan;
849
+ // What the server holds live and the machine — SEEN — does not run: down next beat.
850
+ if (collected?.observed) {
851
+ // An id that runs again is not stale any more (Opus nit).
852
+ for (const id of [...state.stale]) if (collected.allPresent.has(id)) state.stale.delete(id);
853
+ const ended = new Set([...roster.closed, ...roster.down]);
854
+ for (const id of ack.instances.keys()) {
855
+ if (!collected.allPresent.has(id) && !collected.uncertain.has(id) && !ended.has(id)) state.stale.add(id);
856
+ }
857
+ }
858
+ if (ack.presence_applied) for (const id of [...roster.closed, ...roster.down]) state.stale.delete(id);
859
+ if (roster.mode === "full") {
860
+ if (!ack.presence_applied) return; // resent whole next beat
861
+ state.known.clear();
862
+ state.resync = false;
863
+ }
864
+ for (const p of roster.present) if (ack.instances.has(p.instance_id)) state.known.set(p.instance_id, p);
865
+ if (!ack.presence_applied) return;
866
+ for (const id of [...roster.closed, ...roster.down]) state.known.delete(id);
867
+ // Self-healing (Opus review): an applied answer that no longer names a known agent means
868
+ // the server stopped holding it live (downed, revoked, link moved…). Forget it: if it still
869
+ // runs, the next beat sends it again as present.
870
+ for (const id of [...state.known.keys()]) if (!ack.instances.has(id)) state.known.delete(id);
871
+ }
@@ -20,7 +20,7 @@ import { join } from "node:path";
20
20
  import { cfAccessHeaders } from "./cfAccess.js";
21
21
  import { isTrustedViberOrigin } from "./urls.js";
22
22
  import { type ExecDeps, reconcileOnce, runnerIdentity } from "./runner_exec.js";
23
- import { runRosterBeat } from "./runner_roster.js";
23
+ import { requestPresenceResync, runRosterBeat } from "./runner_roster.js";
24
24
  import { presenceDir } from "./presence_record.js";
25
25
  import { startPresenceTrigger } from "./presence_trigger.js";
26
26
  import { RuntimeTracker, startRuntimeTrigger } from "./runner_runtime.js";
@@ -225,6 +225,9 @@ export async function runPersistentRunnerStream(
225
225
  // while disconnected is recovered here (C6). safeReconcile is coalesced +
226
226
  // self-contained (its errors never trigger the SSE backoff below).
227
227
  await safeReconcile(auth, deps);
228
+ // #735: each (re)connect asks the next beat for the COMPLETE presence state — an
229
+ // arrival or an end may have been lost while the stream was away.
230
+ requestPresenceResync();
228
231
  // Close the tiny window where a heartbeat-detected revocation fired
229
232
  // against the PREVIOUS (now-null) controller: bail before opening a new
230
233
  // stream (Opus nit).
@@ -12,7 +12,6 @@
12
12
  */
13
13
  import type { AgentToolResult, AgentToolsContext } from "./agent_tools.js";
14
14
  import { callAgentAdmin, errorText, type AdminRequest } from "./agent_admin_call.js";
15
- import { CODEX_DEFAULT_PAIR } from "./codex_default.js";
16
15
 
17
16
  export const TEAM_ROLE_ACTIONS = ["list", "get", "create", "update", "delete"] as const;
18
17
  type Action = (typeof TEAM_ROLE_ACTIONS)[number];
@@ -64,7 +63,7 @@ export const TEAM_ROLES_TOOL_DEF = {
64
63
  type: ["string", "null"],
65
64
  description:
66
65
  "claude: leave model and effort OUT (the runtime picks its own default) UNLESS the owner explicitly asks; model is a family (opus, sonnet, haiku or fable). " +
67
- `codex: model AND effort are REQUIRED — use ${CODEX_DEFAULT_PAIR} unless the owner asks for another listed model and an effort it accepts. Full rules: the capabilities tool.`,
66
+ "codex: model AND effort are REQUIRED — a model the owner's codex lists (a refusal names them; `viber-gateway refresh-models` sends a new one), effort low unless the owner asks. Full rules: the capabilities tool.",
68
67
  },
69
68
  effort: {
70
69
  type: ["string", "null"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viber-channel",
3
- "version": "0.8.45",
3
+ "version": "0.8.47",
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": {
@@ -42,7 +42,7 @@
42
42
  "typecheck": "tsc --noEmit"
43
43
  },
44
44
  "dependencies": {
45
- "@modelcontextprotocol/sdk": "^1.0.0",
45
+ "@modelcontextprotocol/sdk": "^1.32.2",
46
46
  "proper-lockfile": "^4.1.2"
47
47
  },
48
48
  "devDependencies": {
@@ -1,11 +0,0 @@
1
- /**
2
- * The codex model/effort pair an agent uses when the owner names none (#665) — ONE
3
- * place in the channel. It was written as prose three times (capabilities twice, the
4
- * team_roles description once; debt noted in PR 675, closed in #673). It must equal the
5
- * API's `CODEX_DEFAULT_MODEL` / `CODEX_DEFAULT_EFFORT` (viber-api/src/db/roleFields.ts):
6
- * a test reads them from there.
7
- */
8
- export const CODEX_DEFAULT_MODEL = "gpt-5.6-sol";
9
- export const CODEX_DEFAULT_EFFORT = "low";
10
- /** As the texts write it: `gpt-5.6-sol / low`. */
11
- export const CODEX_DEFAULT_PAIR = `${CODEX_DEFAULT_MODEL} / ${CODEX_DEFAULT_EFFORT}`;