viber-channel 0.8.40 → 0.8.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,353 @@
1
+ /**
2
+ * macro_run.ts — the runner executes ONE claimed `macro` command (#709 step-05).
3
+ *
4
+ * The runner only runs bytes whose SHA-256 equals BOTH the local list's AND the web's (the hash
5
+ * the server pinned at the click and sent with the claim), for an agent it launched itself and
6
+ * that is alive now. Order, and why:
7
+ * 1. checks with no side effect — list, name, agent, interpreter, ONE read of the bytes, both
8
+ * hashes. Any refusal is reported and nothing runs.
9
+ * 2. `starting` accepted by the server (only a 2xx proves the claim is still ours).
10
+ * 3. durable marker (`runner-inflight/<command_id>.json`) — a marker that cannot be written
11
+ * refuses the run. A command found marked is NEVER run again (at most once).
12
+ * 4. private copy of the bytes that were hashed, then the host (job object) runs THE COPY.
13
+ * 5. the terminal report; the marker is cleared only once that report is accepted.
14
+ *
15
+ * The step-01 contract fixes the names: env allowlist, interpreter, refusal reasons, 30 s.
16
+ */
17
+ import { randomBytes } from "node:crypto";
18
+ import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
19
+ import { join } from "node:path";
20
+ import type { ChildProcess } from "node:child_process";
21
+ import { spawn } from "./hidden_proc.js";
22
+ import { MACRO_NAME_RE, MACRO_SHA256_RE, macroSha256, readMacroList } from "./macro_list.js";
23
+ import { MACRO_HOST_REFUSED_EXIT, MACRO_HOST_REFUSED_LINE, encodedHost } from "./macro_job_host.js";
24
+ import { presenceRecordPath, readPresenceRecord } from "./presence_record.js";
25
+ import { processStartTime } from "./process_start.js";
26
+ import { readRegistry, registryPath } from "./runner_registry.js";
27
+
28
+ /** Reasons a macro run is refused or fails on the runner (step-01 contract). PARITY: the server's
29
+ * `SPAWN_REFUSAL_REASONS` (`viber-api/src/routes/runners.ts`) and its test list them too. */
30
+ export const MACRO_REASONS = [
31
+ "macro_list_unreadable",
32
+ "macro_unknown",
33
+ "macro_hash_local_mismatch",
34
+ "macro_hash_web_mismatch",
35
+ "macro_agent_unknown",
36
+ "macro_agent_dead",
37
+ "macro_already_started",
38
+ "macro_marker_failed",
39
+ "macro_interpreter_unavailable",
40
+ "macro_copy_failed",
41
+ "macro_job_failed",
42
+ "macro_timeout",
43
+ "macro_exit_nonzero",
44
+ ] as const;
45
+ export type MacroReason = (typeof MACRO_REASONS)[number];
46
+
47
+ export const MACRO_TIMEOUT_MS = 30_000;
48
+ /**
49
+ * Budget for the HOST to set its job up, before the macro starts (`job=entered`). Separate from
50
+ * the macro's own 30 s: `Add-Type` compiles C# on every run — under a second on a warm machine,
51
+ * but MEASURED at 44.4 s on a cold GitHub Windows runner (CI, PR 712: host=started 05:37:53.274 →
52
+ * job=entered 05:38:37.653), and seconds on the next run. 120 s = that measure × 2.7. A first macro
53
+ * on a cold machine must not fail on a delay that is not its own.
54
+ */
55
+ export const MACRO_SETUP_TIMEOUT_MS = 120_000;
56
+ export const MACRO_HOST_READY_LINE = "job=entered";
57
+ const INSTANCE_ID_RE = /^[0-9a-f]{32}$/;
58
+ const OUTPUT_CAP = 64 * 1024;
59
+
60
+ export interface MacroClaim {
61
+ id: string;
62
+ fencing_token: number;
63
+ macro_name?: string | null;
64
+ macro_instance_id?: string | null;
65
+ macro_sha256?: string | null;
66
+ }
67
+
68
+ /** Who the macro runs for, resolved HERE from the runner's own state — never from the claim. */
69
+ export interface MacroAgent {
70
+ name: string;
71
+ instanceId: string;
72
+ projectId: number | null;
73
+ workspace: string;
74
+ }
75
+
76
+ export type HostOutcome =
77
+ | { kind: "exited"; code: number | null; output: string }
78
+ | { kind: "timeout"; output: string }
79
+ /** The host never finished setting up its job: the macro did NOT start. */
80
+ | { kind: "setup_timeout"; output: string };
81
+
82
+ export interface MacroDeps {
83
+ /** POST the report; returns the HTTP status. */
84
+ report: (body: Record<string, unknown>) => Promise<number>;
85
+ /** The app home holding `.viber/macros.json` and `.viber/macro-runs/`. */
86
+ home: string;
87
+ inflight: { has(id: string): boolean; mark(id: string, fencing: number): void; clear(id: string): void };
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 };
90
+ interpreter: () => string;
91
+ runHost: (copyPath: string, interpreter: string, env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<HostOutcome>;
92
+ timeoutMs?: number;
93
+ log?: (line: string) => void;
94
+ writeLog?: (commandId: string, text: string) => void;
95
+ }
96
+
97
+ type Outcome = "succeeded" | "failed" | "aborted";
98
+
99
+ function refusal(cmd: MacroClaim, reason: MacroReason, error: string): Record<string, unknown> {
100
+ return { fencing_token: cmd.fencing_token, status: "failed", reason, error };
101
+ }
102
+
103
+ const ok = (status: number) => status >= 200 && status < 300;
104
+
105
+ export async function executeMacroClaim(cmd: MacroClaim, deps: MacroDeps): Promise<Outcome> {
106
+ const log = deps.log ?? ((l: string) => process.stderr.write(`${l}\n`));
107
+ const refuse = async (reason: MacroReason, error: string): Promise<Outcome> => {
108
+ log(`[runner] macro ${cmd.id.slice(0, 8)} refused: ${reason} — ${error}`);
109
+ await deps.report(refusal(cmd, reason, error));
110
+ return "failed";
111
+ };
112
+
113
+ // At most once: a marker means a prior attempt reached step 3 on this machine.
114
+ if (deps.inflight.has(cmd.id)) {
115
+ const s = await deps.report(refusal(cmd, "macro_already_started", "this macro run already started on this machine — never run twice"));
116
+ if (ok(s)) deps.inflight.clear(cmd.id);
117
+ return "failed";
118
+ }
119
+
120
+ const name = cmd.macro_name ?? "";
121
+ const instanceId = cmd.macro_instance_id ?? "";
122
+ const webHash = cmd.macro_sha256 ?? "";
123
+ if (!MACRO_NAME_RE.test(name)) return refuse("macro_unknown", "the claim carries no valid macro name");
124
+ if (!INSTANCE_ID_RE.test(instanceId)) return refuse("macro_agent_unknown", "the claim carries no valid agent id");
125
+ if (!MACRO_SHA256_RE.test(webHash)) return refuse("macro_hash_web_mismatch", "the claim carries no valid reference hash");
126
+
127
+ const list = readMacroList(deps.home);
128
+ if (list.kind === "invalid") return refuse("macro_list_unreadable", list.reason);
129
+ const entry = list.macros.get(name);
130
+ if (!entry) return refuse("macro_unknown", `no local macro named ${name}`);
131
+
132
+ const agent = deps.resolveAgent(instanceId);
133
+ if ("refused" in agent) return refuse(agent.refused, agent.why);
134
+
135
+ const interpreter = deps.interpreter();
136
+ try {
137
+ if (!statSync(interpreter).isFile()) return refuse("macro_interpreter_unavailable", "PowerShell is not a file");
138
+ } catch {
139
+ return refuse("macro_interpreter_unavailable", "PowerShell 5.1 is not reachable on this machine");
140
+ }
141
+
142
+ // ONE read: these bytes are hashed, compared, and they are what runs (via the copy).
143
+ let bytes: Buffer;
144
+ try {
145
+ bytes = readFileSync(entry.path);
146
+ } catch (err) {
147
+ return refuse("macro_unknown", `cannot read the script: ${(err as Error).message}`);
148
+ }
149
+ const actual = macroSha256(bytes);
150
+ if (actual !== entry.sha256) return refuse("macro_hash_local_mismatch", "the script changed since `viber-gateway macro add`");
151
+ if (actual !== webHash) return refuse("macro_hash_web_mismatch", "the script's hash differs from the one registered in the web");
152
+
153
+ if (!ok(await deps.report({ fencing_token: cmd.fencing_token, status: "starting" }))) return "aborted";
154
+
155
+ try {
156
+ deps.inflight.mark(cmd.id, cmd.fencing_token);
157
+ } catch (err) {
158
+ return reportFinal(cmd, deps, refusal(cmd, "macro_marker_failed", `cannot write the run marker: ${(err as Error).message}`), false);
159
+ }
160
+
161
+ const runDir = join(deps.home, ".viber", "macro-runs", randomBytes(16).toString("hex"));
162
+ const copyPath = join(runDir, `${name}.ps1`);
163
+ try {
164
+ try {
165
+ // %LOCALAPPDATA% is the user's own; the folder name is unpredictable and created
166
+ // exclusively (mkdir fails if it exists), the file too (`wx`).
167
+ mkdirSync(join(deps.home, ".viber", "macro-runs"), { recursive: true });
168
+ mkdirSync(runDir, { mode: 0o700 });
169
+ writeFileSync(copyPath, bytes, { flag: "wx", mode: 0o600 });
170
+ } catch (err) {
171
+ return reportFinal(cmd, deps, refusal(cmd, "macro_copy_failed", `cannot write the private copy: ${(err as Error).message}`), true);
172
+ }
173
+ const env = macroEnv({ name, origin: entry.path, agent });
174
+ const outcome = await deps.runHost(copyPath, interpreter, env, deps.timeoutMs ?? MACRO_TIMEOUT_MS);
175
+ if (outcome.output) deps.writeLog?.(cmd.id, outcome.output);
176
+ return reportFinal(cmd, deps, bodyFor(cmd, outcome), true);
177
+ } finally {
178
+ rmSync(runDir, { recursive: true, force: true });
179
+ }
180
+ }
181
+
182
+ /** The terminal report. The marker stays until the server ACCEPTS it — a lost report must
183
+ * never turn into a second run. */
184
+ async function reportFinal(cmd: MacroClaim, deps: MacroDeps, body: Record<string, unknown>, ranOrTried: boolean): Promise<Outcome> {
185
+ const status = await deps.report(body);
186
+ if (!ok(status)) return "aborted";
187
+ if (ranOrTried) deps.inflight.clear(cmd.id);
188
+ return body.status === "succeeded" ? "succeeded" : "failed";
189
+ }
190
+
191
+ function bodyFor(cmd: MacroClaim, outcome: HostOutcome): Record<string, unknown> {
192
+ if (outcome.kind === "timeout") return refusal(cmd, "macro_timeout", "the macro ran past its time limit; it and everything it started were stopped");
193
+ if (outcome.kind === "setup_timeout") {
194
+ return refusal(cmd, "macro_job_failed", "the process guard took too long to set up; the macro did not run");
195
+ }
196
+ if (outcome.code === MACRO_HOST_REFUSED_EXIT && outcome.output.includes(MACRO_HOST_REFUSED_LINE)) {
197
+ return refusal(cmd, "macro_job_failed", "the process guard (job object) could not be set up; the macro did not run");
198
+ }
199
+ if (outcome.code !== 0) return refusal(cmd, "macro_exit_nonzero", `the macro exited with code ${outcome.code ?? "?"}`);
200
+ return { fencing_token: cmd.fencing_token, status: "succeeded", result: { message: "macro ran" } };
201
+ }
202
+
203
+ /**
204
+ * The Windows basics a PowerShell needs to start, copied when the runner has them. None is a
205
+ * secret. On JP's machine Windows rebuilds these from the user profile when they are missing
206
+ * (step-01), but NOT under a service account: on the GitHub Windows runner a host given only
207
+ * `SystemRoot` never reached the macro within 20 s (CI, PR 712).
208
+ */
209
+ const WINDOWS_BASE_ENV = [
210
+ "SystemRoot",
211
+ "SystemDrive",
212
+ "windir",
213
+ "ComSpec",
214
+ "PATHEXT",
215
+ "TEMP",
216
+ "TMP",
217
+ "USERPROFILE",
218
+ "HOMEDRIVE",
219
+ "HOMEPATH",
220
+ "APPDATA",
221
+ "LOCALAPPDATA",
222
+ "USERNAME",
223
+ "USERDOMAIN",
224
+ ] as const;
225
+
226
+ /** The ENTIRE environment of the host and the macro: an allowlist, never `process.env`. */
227
+ export function macroEnv(opts: { name: string; origin: string; agent: MacroAgent }, source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
228
+ const env: NodeJS.ProcessEnv = {
229
+ VIBER_MACRO_NAME: opts.name,
230
+ VIBER_MACRO_ORIGIN: opts.origin,
231
+ VIBER_AGENT_NAME: opts.agent.name,
232
+ VIBER_INSTANCE_ID: opts.agent.instanceId,
233
+ VIBER_AGENT_WORKSPACE: opts.agent.workspace,
234
+ };
235
+ for (const name of WINDOWS_BASE_ENV) {
236
+ const value = source[name];
237
+ if (value) env[name] = value;
238
+ }
239
+ if (opts.agent.projectId !== null) env.VIBER_PROJECT_ID = String(opts.agent.projectId);
240
+ return env;
241
+ }
242
+
243
+ /** `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe`, built with join (never a literal). */
244
+ export function windowsPowerShell(source: NodeJS.ProcessEnv = process.env): string {
245
+ return join(source.SystemRoot ?? "", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
246
+ }
247
+
248
+ /**
249
+ * The agent, from the runner's registry (an entry it launched, still active) and its presence
250
+ * record (pid alive WITH the same creation time). Unknown is refused, never assumed alive.
251
+ */
252
+ export function resolveAgentOnDisk(
253
+ identity: string,
254
+ instanceId: string,
255
+ opts: { lockDir?: string; startTimeOf?: (pid: number) => number | undefined } = {},
256
+ ): MacroAgent | { refused: "macro_agent_unknown" | "macro_agent_dead"; why: string } {
257
+ const reg = readRegistry(registryPath(identity, opts.lockDir));
258
+ if (reg.kind !== "ok") return { refused: "macro_agent_unknown", why: `runner registry ${reg.kind}` };
259
+ const entry = Object.values(reg.registry.entries).find((e) => e.instance_id === instanceId);
260
+ if (!entry) return { refused: "macro_agent_unknown", why: "this runner did not launch this agent" };
261
+ if (entry.state !== "active") return { refused: "macro_agent_dead", why: "the agent is closed" };
262
+ const rec = readPresenceRecord(presenceRecordPath(identity, instanceId, opts.lockDir));
263
+ if (rec.kind !== "ok") return { refused: "macro_agent_unknown", why: `presence record ${rec.kind}` };
264
+ if (rec.record.state === "ended") return { refused: "macro_agent_dead", why: "the agent ended" };
265
+ 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" };
268
+ if (observed !== rec.record.start_time_ms) return { refused: "macro_agent_dead", why: "the agent's pid now belongs to another process" };
269
+ return { name: entry.name, instanceId, projectId: entry.project_id, workspace: entry.workspace };
270
+ }
271
+
272
+ /** Durable marker per command id; its content records the fencing that started it. */
273
+ export function fsMacroInflight(home: string): MacroDeps["inflight"] {
274
+ const dir = join(home, ".viber", "runner-inflight");
275
+ const path = (id: string) => join(dir, `${id}.json`);
276
+ return {
277
+ has: (id) => {
278
+ try {
279
+ statSync(path(id));
280
+ return true;
281
+ } catch {
282
+ return false;
283
+ }
284
+ },
285
+ mark: (id, fencing) => {
286
+ mkdirSync(dir, { recursive: true });
287
+ writeFileSync(path(id), JSON.stringify({ started: true, kind: "macro", fencing_token: fencing }), { flag: "wx", mode: 0o600 });
288
+ },
289
+ clear: (id) => rmSync(path(id), { force: true }),
290
+ };
291
+ }
292
+
293
+ /** Start the host (job object) on the copy; on timeout kill the HOST — the job kills the rest. */
294
+ export function runHostProcess(
295
+ copyPath: string,
296
+ interpreter: string,
297
+ env: NodeJS.ProcessEnv,
298
+ timeoutMs: number,
299
+ setupTimeoutMs: number = MACRO_SETUP_TIMEOUT_MS,
300
+ ): Promise<HostOutcome> {
301
+ return new Promise((resolve) => {
302
+ let output = "";
303
+ let stopped: "setup" | "macro" | null = null;
304
+ let ready = false;
305
+ let child: ChildProcess;
306
+ try {
307
+ child = spawn(interpreter, ["-NoProfile", "-NonInteractive", "-EncodedCommand", encodedHost()], {
308
+ env: { ...env, VIBER_MACRO_COPY: copyPath, VIBER_MACRO_INTERPRETER: interpreter },
309
+ cwd: join(copyPath, ".."),
310
+ stdio: ["ignore", "pipe", "pipe"],
311
+ });
312
+ } catch (err) {
313
+ resolve({ kind: "exited", code: MACRO_HOST_REFUSED_EXIT, output: `${MACRO_HOST_REFUSED_LINE} spawn: ${(err as Error).message}` });
314
+ return;
315
+ }
316
+ // Two clocks: the host's setup, then the macro's own time from the `job=entered` line on.
317
+ let timer = setTimeout(() => {
318
+ stopped = "setup";
319
+ child.kill();
320
+ }, setupTimeoutMs);
321
+ // The ready line is looked for on the RAW stdout (a short rolling tail), never on the capped
322
+ // copy kept for the log: warnings flooding the log must not hide it (review Opus).
323
+ let tail = "";
324
+ const take = (chunk: Buffer) => {
325
+ if (output.length < OUTPUT_CAP) output += chunk.toString("utf-8").slice(0, OUTPUT_CAP - output.length);
326
+ };
327
+ const watch = (chunk: Buffer) => {
328
+ take(chunk);
329
+ if (ready) return;
330
+ tail = (tail + chunk.toString("utf-8")).slice(-4096);
331
+ if (tail.includes(MACRO_HOST_READY_LINE)) {
332
+ ready = true;
333
+ clearTimeout(timer);
334
+ timer = setTimeout(() => {
335
+ stopped = "macro";
336
+ child.kill();
337
+ }, timeoutMs);
338
+ }
339
+ };
340
+ child.stdout?.on("data", watch);
341
+ child.stderr?.on("data", take);
342
+ child.on("error", (err) => {
343
+ clearTimeout(timer);
344
+ resolve({ kind: "exited", code: MACRO_HOST_REFUSED_EXIT, output: `${MACRO_HOST_REFUSED_LINE} spawn: ${err.message}` });
345
+ });
346
+ child.on("close", (code) => {
347
+ clearTimeout(timer);
348
+ if (stopped === "setup") resolve({ kind: "setup_timeout", output });
349
+ else if (stopped === "macro") resolve({ kind: "timeout", output });
350
+ else resolve({ kind: "exited", code, output });
351
+ });
352
+ });
353
+ }
@@ -164,6 +164,8 @@ export interface ParentWatchdogOptions {
164
164
 
165
165
  export interface ParentWatchdogHandle {
166
166
  stop: () => void;
167
+ /** The agent ancestor resolved at startup (#708: the runner reads its session log). */
168
+ agent: AgentIdentity | null;
167
169
  }
168
170
 
169
171
  const DEFAULT_INTERVAL_MS = 5000;
@@ -233,7 +235,7 @@ export function startParentWatchdog(
233
235
 
234
236
  if (!identity) {
235
237
  log("[viber-channel] parent watchdog disabled (no resolvable agent ancestor)\n");
236
- return { stop: () => {} };
238
+ return { stop: () => {}, agent: null };
237
239
  }
238
240
 
239
241
  const watched = identity;
@@ -272,5 +274,6 @@ export function startParentWatchdog(
272
274
  stopped = true;
273
275
  clearTimer(handle);
274
276
  },
277
+ agent: watched,
275
278
  };
276
279
  }
@@ -47,7 +47,7 @@ export interface PresenceTrigger {
47
47
  stop: () => void;
48
48
  }
49
49
 
50
- /** The agent records of a presence folder: `<instance_id>.json`, never `*.coverage.json`. */
50
+ /** The agent records of a presence folder: `<instance_id>.json`, never `*.coverage.json` nor `*.runtime.json`. */
51
51
  export function listPresenceRecords(dir: string): Map<string, number> | null {
52
52
  let names: string[];
53
53
  try {
@@ -57,7 +57,9 @@ export function listPresenceRecords(dir: string): Map<string, number> | null {
57
57
  }
58
58
  const out = new Map<string, number>();
59
59
  for (const name of names) {
60
- if (!name.endsWith(".json") || name.endsWith(".coverage.json")) continue;
60
+ // #708: runtime files have their own trigger (runner_runtime.ts) — counted twice they would
61
+ // queue a second beat for one change.
62
+ if (!name.endsWith(".json") || name.endsWith(".coverage.json") || name.endsWith(".runtime.json")) continue;
61
63
  try {
62
64
  out.set(name, statSync(join(dir, name)).mtimeMs);
63
65
  } catch {
@@ -24,6 +24,8 @@ import { messageForReason, rosterNames, type SpawnReason } from "./spawn_reason.
24
24
  import { identityBaseUrl } from "./base_urls.js";
25
25
  import { recordSpawn, registryPath, type SpawnForRegistry, updateRegistry } from "./runner_registry.js";
26
26
  import { relaunchInstance } from "./runner_relaunch.js";
27
+ import { executeMacroClaim, fsMacroInflight, resolveAgentOnDisk, runHostProcess, windowsPowerShell, type MacroDeps } from "./macro_run.js";
28
+ import { appHome } from "./machine_projects.js";
27
29
 
28
30
  /** A validated role from the server snapshot (allowlisted shape). */
29
31
  export interface SnapshotRole {
@@ -33,6 +35,9 @@ export interface SnapshotRole {
33
35
  rolePrompt?: string;
34
36
  model?: string;
35
37
  effort?: string;
38
+ /** #717: plugins the claude session enables, and `--chrome`. */
39
+ plugins?: string[];
40
+ chrome?: boolean;
36
41
  count?: number;
37
42
  }
38
43
 
@@ -47,8 +52,13 @@ export interface ClaimedCommand {
47
52
  /** From the LIST entry (the claim response does not carry it). #632: the app
48
53
  * mode maps it to a local folder; the source runner ignores it. */
49
54
  project_id?: number;
50
- /** #627: `relaunch` brings back ONE agent from the runner's registry; absent = team. */
51
- kind?: "team" | "relaunch";
55
+ /** #627: `relaunch` brings back ONE agent from the runner's registry; absent = team.
56
+ * #709: `macro` runs a user macro for one agent (`macro_run.ts`). */
57
+ kind?: "team" | "relaunch" | "macro";
58
+ /** #709: set on a `macro` claim — the stored name, the agent, the hash PINNED at the click. */
59
+ macro_name?: string | null;
60
+ macro_instance_id?: string | null;
61
+ macro_sha256?: string | null;
52
62
  relaunch_instance_id?: string | null;
53
63
  /** #647: a ONE-agent spawn — its role and chosen label (both or neither, server-side). */
54
64
  agent_role?: string | null;
@@ -629,6 +639,8 @@ export interface ExecDeps {
629
639
  runSingleSpawn?: (args: string[]) => Promise<{ ok: boolean; recap: string }>;
630
640
  /** #627: relaunch seams (tests). */
631
641
  relaunchLockDir?: string;
642
+ /** #709: macro seams (tests); absent = the real machine. */
643
+ macro?: Partial<Omit<MacroDeps, "report">>;
632
644
  relaunchEnumerate?: () => Promise<Map<number, number | undefined> | undefined>;
633
645
  }
634
646
 
@@ -753,7 +765,10 @@ export async function executeClaim(
753
765
  // ({@link execFileVibeMasterSpawn}).
754
766
  const runTeamSpawn = deps.runTeamSpawn ?? execFileGatewayTeamSpawn;
755
767
  const fetchImpl = deps.apiFetch ?? fetch;
756
- if (cmd.kind === "relaunch") return executeRelaunchClaim(auth, cmd, deps, fetchImpl);
768
+ // One handler per kind (architecture rule 3); a team is the default.
769
+ // `Object.hasOwn`: a kind like `constructor` must not find a prototype member (review Opus).
770
+ const special = cmd.kind !== undefined && Object.hasOwn(KIND_HANDLERS, cmd.kind) ? KIND_HANDLERS[cmd.kind as keyof typeof KIND_HANDLERS] : undefined;
771
+ if (special) return special(auth, cmd, deps, fetchImpl);
757
772
  const inflight = deps.inflight ?? fsInflightStore();
758
773
 
759
774
  // P1-4: a PRESENT-but-invalid local policy REFUSES execution (never the
@@ -1124,3 +1139,40 @@ async function executeRelaunchClaim(
1124
1139
  inflight.clear(cmd.id);
1125
1140
  return outcome.kind === "refused" ? "failed" : "succeeded";
1126
1141
  }
1142
+
1143
+ type KindHandler = (
1144
+ auth: RunnerAuthLite,
1145
+ cmd: ClaimedCommand,
1146
+ deps: ExecDeps,
1147
+ fetchImpl: typeof fetch,
1148
+ ) => Promise<"succeeded" | "failed" | "aborted">;
1149
+
1150
+ /**
1151
+ * #709 — a MACRO command: the user's script for one agent. The decision and the run are
1152
+ * `executeMacroClaim`'s; this binds it to this runner's reports and its state on disk.
1153
+ */
1154
+ function executeMacroCommand(
1155
+ auth: RunnerAuthLite,
1156
+ cmd: ClaimedCommand,
1157
+ deps: ExecDeps,
1158
+ fetchImpl: typeof fetch,
1159
+ ): Promise<"succeeded" | "failed" | "aborted"> {
1160
+ const home = deps.macro?.home ?? appHome();
1161
+ const identity = runnerIdentity(auth);
1162
+ return executeMacroClaim(cmd, {
1163
+ report: (body) => report(auth, cmd.id, body, fetchImpl),
1164
+ home,
1165
+ inflight: deps.macro?.inflight ?? fsMacroInflight(home),
1166
+ resolveAgent: deps.macro?.resolveAgent ?? ((id) => resolveAgentOnDisk(identity, id)),
1167
+ interpreter: deps.macro?.interpreter ?? (() => windowsPowerShell()),
1168
+ runHost: deps.macro?.runHost ?? runHostProcess,
1169
+ ...(deps.macro?.timeoutMs !== undefined ? { timeoutMs: deps.macro.timeoutMs } : {}),
1170
+ writeLog: deps.macro?.writeLog ?? ((id, text) => deps.writeLog ? deps.writeLog(id, text) : writeRunnerLog(id, text)),
1171
+ });
1172
+ }
1173
+
1174
+ /** Kinds that are not a team launch. Declared after their handlers (function hoisting). */
1175
+ const KIND_HANDLERS: Record<"relaunch" | "macro", KindHandler> = {
1176
+ relaunch: executeRelaunchClaim,
1177
+ macro: executeMacroCommand,
1178
+ };
@@ -76,6 +76,9 @@ export interface RegistryRole {
76
76
  model?: string;
77
77
  /** #656 claude / #665 codex reasoning effort, replayed as `--effort` on a relaunch. */
78
78
  effort?: string;
79
+ /** #717: claude plugins and Claude in Chrome, replayed as `--plugins` / `--chrome`. */
80
+ plugins?: string[];
81
+ chrome?: boolean;
79
82
  }
80
83
 
81
84
  export type RegistryEntryState = "active" | "closed";
@@ -54,6 +54,10 @@ export function relaunchArgs(entry: RegistryEntry): string[] {
54
54
  if (entry.env) args.push("--env", entry.env);
55
55
  if (entry.role.model) args.push("--model", entry.role.model);
56
56
  if (entry.role.effort) args.push("--effort", entry.role.effort);
57
+ // #717: what the role enables for its session — a relaunch without them would come back
58
+ // without the tools the web launch had.
59
+ if (entry.role.plugins && entry.role.plugins.length > 0) args.push("--plugins", entry.role.plugins.join(","));
60
+ if (entry.role.chrome) args.push("--chrome");
57
61
  if (entry.conversation_id && RELOADS_CONVERSATION.has(runtime)) args.push("--conversation", entry.conversation_id);
58
62
  // Last: free text, nothing appended after it (same rule as the gateway's argv).
59
63
  if (entry.role.rolePrompt) args.push("--role", entry.role.rolePrompt);
@@ -30,6 +30,8 @@ import {
30
30
  readPresenceRecord,
31
31
  } from "./presence_record.js";
32
32
  import { enumerateStartTimes } from "./process_start.js";
33
+ import { runtimeFilePath } from "./codex_runtime.js";
34
+ import { type RuntimeDelta, type RuntimeSource, type RuntimeTracker } from "./runner_runtime.js";
33
35
  import { announcedCapabilitiesVersion } from "./gateway_features.js";
34
36
  import { runnerIdentity } from "./runner_exec.js";
35
37
  import * as reg from "./runner_registry.js";
@@ -92,6 +94,8 @@ export interface CollectedRoster {
92
94
  notes: string[];
93
95
  /** #687: one line per ended agent OBSERVED (logged even if `capRoster` defers its report), for the runner's log (`endLine`). */
94
96
  ends: string[];
97
+ /** #708: where to read what each PRESENT agent runs on — exactly the present this beat carries. */
98
+ runtimeSources: RuntimeSource[];
95
99
  }
96
100
 
97
101
  /** The process table: pid → start time, or `undefined` when the instrument did not see. */
@@ -111,6 +115,7 @@ function emptyCollected(note?: string): CollectedRoster {
111
115
  endedFiles: new Map(),
112
116
  notes: note === undefined ? [] : [note],
113
117
  ends: [],
118
+ runtimeSources: [],
114
119
  };
115
120
  }
116
121
 
@@ -204,6 +209,7 @@ export async function collectRoster(deps: CollectDeps): Promise<CollectedRoster>
204
209
  created_at: record.created_at,
205
210
  job_name: record.job_name,
206
211
  });
212
+ out.runtimeSources.push({ instance_id: record.instance_id });
207
213
  } else {
208
214
  out.roster[c.kind].push(record.instance_id);
209
215
  out.endedFiles.set(record.instance_id, { path, content: JSON.stringify(record) });
@@ -229,6 +235,7 @@ function capRoster(c: CollectedRoster): CollectedRoster {
229
235
  // The registry must only learn what this beat actually told the server (Codex).
230
236
  const sentPresent = new Set(keptPresent.map((p) => p.instance_id));
231
237
  c.seen = c.seen.filter((s) => sentPresent.has(s.instance_id));
238
+ c.runtimeSources = c.runtimeSources.filter((s) => sentPresent.has(s.instance_id));
232
239
  c.roster = { present: keptPresent, closed: keptClosed, down: keptDown };
233
240
  c.notes.push(`roster capped at ${ROSTER_MAX} (had ${total}); the rest goes next beat`);
234
241
  return c;
@@ -349,6 +356,11 @@ export function applyAck(collected: CollectedRoster, ack: RosterAck, deps: Apply
349
356
  } catch {
350
357
  // no coverage for it: nothing to clean
351
358
  }
359
+ try {
360
+ unlinkSync(runtimeFilePath(deps.identityBaseUrl, id, deps.lockDir));
361
+ } catch {
362
+ // #708: no runtime file for it (an agent that never reported)
363
+ }
352
364
  }
353
365
  return removed;
354
366
  }
@@ -369,6 +381,8 @@ export interface RosterBeatDeps {
369
381
  headers?: () => Record<string, string>;
370
382
  /** #647: the announced capabilities version (default: the cached gateway probe). */
371
383
  capabilitiesVersion?: () => 1 | 2;
384
+ /** #708: what each present agent runs on; absent = the beat carries no `runtime`. */
385
+ runtime?: RuntimeTracker;
372
386
  }
373
387
 
374
388
  /**
@@ -444,6 +458,23 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
444
458
  const { closes: pendingCloses, replaced } = pendingClosesOf(identity, deps.lockDir, collected.roster);
445
459
  collected.roster.closed.push(...pendingCloses);
446
460
 
461
+ const beatBody: Record<string, unknown> = {
462
+ capabilities: {
463
+ runtimes: ["claude-code", "codex", "gemma"],
464
+ platform: process.platform,
465
+ version: (deps.capabilitiesVersion ?? announcedCapabilitiesVersion)(),
466
+ // #709: this runner can run user macros (macro_run.ts). Windows only: the guard is a
467
+ // Windows job object. The server refuses a macro to a runner that does not say 1.
468
+ macros: process.platform === "win32" ? 1 : 0,
469
+ },
470
+ // #627 (JP, decision A): the new instance of each pair takes the old one's
471
+ // conversations — the server re-invites it once it is online.
472
+ roster: replaced.length > 0 ? { ...collected.roster, replaced } : collected.roster,
473
+ };
474
+ // #708: the roster first; runtime entries only take the room it leaves under the cap.
475
+ const runtimeSent = withRuntime(beatBody, collected.runtimeSources, deps.runtime);
476
+ const body = JSON.stringify(beatBody);
477
+
447
478
  let resp: Response;
448
479
  try {
449
480
  resp = await (deps.fetchImpl ?? fetch)(`${auth.base_url}/api/runners/${auth.runner_id}/heartbeat`, {
@@ -455,12 +486,7 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
455
486
  "Content-Type": "application/json",
456
487
  ...(deps.headers?.() ?? {}),
457
488
  },
458
- body: JSON.stringify({
459
- capabilities: { runtimes: ["claude-code", "codex", "gemma"], platform: process.platform, version: (deps.capabilitiesVersion ?? announcedCapabilitiesVersion)() },
460
- // #627 (JP, decision A): the new instance of each pair takes the old one's
461
- // conversations — the server re-invites it once it is online.
462
- roster: replaced.length > 0 ? { ...collected.roster, replaced } : collected.roster,
463
- }),
489
+ body,
464
490
  });
465
491
  } catch {
466
492
  return "ok"; // best-effort: nothing acknowledged, nothing changed
@@ -473,7 +499,10 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
473
499
  return "ok";
474
500
  }
475
501
 
476
- const ack = parseRosterAck(await resp.json().catch(() => null));
502
+ const ackBody: unknown = await resp.json().catch(() => null);
503
+ const ack = parseRosterAck(ackBody);
504
+ // #708: an entry counts as sent only once the server names it as stored.
505
+ if (runtimeSent) deps.runtime?.ack(storedRuntime(runtimeSent, ackBody));
477
506
  // A beat whose ended records are never acknowledged is not dangerous (coverage and
478
507
  // leases are still served) but it is SILENT: say it once it lasts (Opus, step-05).
479
508
  if (collected.endedFiles.size > 0 && !ack.presence_applied) {
@@ -584,3 +613,35 @@ export function pendingClosesOf(
584
613
  }
585
614
  return { closes, replaced };
586
615
  }
616
+
617
+ /** `,"runtime":{}` — what the field costs before its first entry. */
618
+ const RUNTIME_FIELD_BYTES = Buffer.byteLength(',"runtime":{}', "utf8");
619
+
620
+ /**
621
+ * #708: add the runtime delta to a beat body, in the room the rest leaves under
622
+ * `HEARTBEAT_MAX_BODY_BYTES`. Returns what was added (to acknowledge on success), or
623
+ * undefined when nothing was.
624
+ */
625
+ export function withRuntime(
626
+ body: Record<string, unknown>,
627
+ sources: readonly RuntimeSource[],
628
+ tracker: RuntimeTracker | undefined,
629
+ ): RuntimeDelta | undefined {
630
+ if (!tracker) return undefined;
631
+ tracker.setSources(sources);
632
+ tracker.poll();
633
+ const room = HEARTBEAT_MAX_BODY_BYTES - Buffer.byteLength(JSON.stringify(body), "utf8") - RUNTIME_FIELD_BYTES;
634
+ const delta = room > 0 ? tracker.delta(room) : {};
635
+ if (Object.keys(delta).length === 0) return undefined;
636
+ body.runtime = delta;
637
+ return delta;
638
+ }
639
+
640
+ /** #708: the entries of `sent` the server answered as stored (`runtime_applied: [ids]`). */
641
+ export function storedRuntime(sent: RuntimeDelta, ackBody: unknown): RuntimeDelta {
642
+ const ids = (ackBody as { runtime_applied?: unknown } | null)?.runtime_applied;
643
+ if (!Array.isArray(ids)) return {};
644
+ const out: RuntimeDelta = {};
645
+ for (const id of ids) if (typeof id === "string" && id in sent) out[id] = sent[id] as RuntimeDelta[string];
646
+ return out;
647
+ }