viber-channel 0.8.45 → 0.8.46

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/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).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viber-channel",
3
- "version": "0.8.45",
3
+ "version": "0.8.46",
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": {