@sjawhar/claude-envoy 5.4.0 → 5.5.0

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.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "5.4.0"
5
+ "version": "5.5.0"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "5.4.0",
3
+ "version": "5.5.0",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
@@ -19253,6 +19253,13 @@ function readSecretFile(variable, filePath) {
19253
19253
 
19254
19254
  // ../envoy-client/src/envoy-config.ts
19255
19255
  var COMMAND_TIMEOUT_MS = 1e4;
19256
+ var COMMAND_TIMEOUT_VARIABLE = "ENVOY_COMMAND_TIMEOUT_MS";
19257
+ var LONGEST_TIMEOUT_MS = 2147483647;
19258
+ function commandTimeoutMs(env) {
19259
+ const text = env[COMMAND_TIMEOUT_VARIABLE] ?? "";
19260
+ const ms = /^[1-9]\d*$/.test(text) ? Number(text) : Number.NaN;
19261
+ return ms <= LONGEST_TIMEOUT_MS ? ms : COMMAND_TIMEOUT_MS;
19262
+ }
19256
19263
  function nonEmpty(value) {
19257
19264
  return value === undefined || value === "" ? undefined : value;
19258
19265
  }
@@ -19411,6 +19418,7 @@ var processGlobal = globalThis;
19411
19418
  var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
19412
19419
  processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
19413
19420
  function runCommand(command, env, cwd) {
19421
+ const timeoutMs = commandTimeoutMs(env);
19414
19422
  const childEnv = {};
19415
19423
  for (const [name, variable] of Object.entries(env)) {
19416
19424
  if (variable !== undefined)
@@ -19429,7 +19437,7 @@ function runCommand(command, env, cwd) {
19429
19437
  stdin: "ignore",
19430
19438
  stdout: fd,
19431
19439
  stderr: "ignore",
19432
- timeout: COMMAND_TIMEOUT_MS,
19440
+ timeout: timeoutMs,
19433
19441
  detached: true
19434
19442
  });
19435
19443
  } catch (error) {
@@ -19442,7 +19450,7 @@ function runCommand(command, env, cwd) {
19442
19450
  } catch {}
19443
19451
  if (result.exitedDueToTimeout) {
19444
19452
  return {
19445
- failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
19453
+ failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
19446
19454
  timedOut: true
19447
19455
  };
19448
19456
  }
@@ -32218,16 +32226,22 @@ var PS_OPTIONS = {
32218
32226
  env: { LC_ALL: "C", PATH: process.env["PATH"] ?? "/usr/bin:/bin", TZ: "UTC" },
32219
32227
  timeout: 1000
32220
32228
  };
32221
- function processStarted(pid) {
32229
+ function procStarted(pid) {
32222
32230
  try {
32223
32231
  const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
32224
32232
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
32225
32233
  } catch {
32226
- const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS);
32227
- const started = ps.status === 0 ? ps.stdout.trim() : "";
32228
- return started === "" ? undefined : `ps:${started}`;
32234
+ return;
32229
32235
  }
32230
32236
  }
32237
+ function processStarted(pid) {
32238
+ const started = procStarted(pid);
32239
+ if (started !== undefined)
32240
+ return started;
32241
+ const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS);
32242
+ const fromPs = ps.status === 0 ? ps.stdout.trim() : "";
32243
+ return fromPs === "" ? undefined : `ps:${fromPs}`;
32244
+ }
32231
32245
  function recordOfProcess(record, pid) {
32232
32246
  const started = processStarted(pid);
32233
32247
  return record.codex_started !== null && started !== undefined && record.codex_started === started;
package/dist/dispatch.js CHANGED
@@ -19506,6 +19506,13 @@ function readSecretFile(variable, filePath) {
19506
19506
 
19507
19507
  // ../envoy-client/src/envoy-config.ts
19508
19508
  var COMMAND_TIMEOUT_MS = 1e4;
19509
+ var COMMAND_TIMEOUT_VARIABLE = "ENVOY_COMMAND_TIMEOUT_MS";
19510
+ var LONGEST_TIMEOUT_MS = 2147483647;
19511
+ function commandTimeoutMs(env) {
19512
+ const text = env[COMMAND_TIMEOUT_VARIABLE] ?? "";
19513
+ const ms = /^[1-9]\d*$/.test(text) ? Number(text) : Number.NaN;
19514
+ return ms <= LONGEST_TIMEOUT_MS ? ms : COMMAND_TIMEOUT_MS;
19515
+ }
19509
19516
  function nonEmpty(value) {
19510
19517
  return value === undefined || value === "" ? undefined : value;
19511
19518
  }
@@ -19664,6 +19671,7 @@ var processGlobal = globalThis;
19664
19671
  var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
19665
19672
  processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
19666
19673
  function runCommand(command, env, cwd) {
19674
+ const timeoutMs = commandTimeoutMs(env);
19667
19675
  const childEnv = {};
19668
19676
  for (const [name, variable] of Object.entries(env)) {
19669
19677
  if (variable !== undefined)
@@ -19682,7 +19690,7 @@ function runCommand(command, env, cwd) {
19682
19690
  stdin: "ignore",
19683
19691
  stdout: fd,
19684
19692
  stderr: "ignore",
19685
- timeout: COMMAND_TIMEOUT_MS,
19693
+ timeout: timeoutMs,
19686
19694
  detached: true
19687
19695
  });
19688
19696
  } catch (error) {
@@ -19695,7 +19703,7 @@ function runCommand(command, env, cwd) {
19695
19703
  } catch {}
19696
19704
  if (result.exitedDueToTimeout) {
19697
19705
  return {
19698
- failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
19706
+ failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
19699
19707
  timedOut: true
19700
19708
  };
19701
19709
  }
@@ -40167,6 +40167,13 @@ function readSecretFile(variable, filePath) {
40167
40167
 
40168
40168
  // ../envoy-client/src/envoy-config.ts
40169
40169
  var COMMAND_TIMEOUT_MS = 1e4;
40170
+ var COMMAND_TIMEOUT_VARIABLE = "ENVOY_COMMAND_TIMEOUT_MS";
40171
+ var LONGEST_TIMEOUT_MS = 2147483647;
40172
+ function commandTimeoutMs(env) {
40173
+ const text = env[COMMAND_TIMEOUT_VARIABLE] ?? "";
40174
+ const ms = /^[1-9]\d*$/.test(text) ? Number(text) : Number.NaN;
40175
+ return ms <= LONGEST_TIMEOUT_MS ? ms : COMMAND_TIMEOUT_MS;
40176
+ }
40170
40177
  function nonEmpty(value) {
40171
40178
  return value === undefined || value === "" ? undefined : value;
40172
40179
  }
@@ -40325,6 +40332,7 @@ var processGlobal = globalThis;
40325
40332
  var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
40326
40333
  processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
40327
40334
  function runCommand(command, env, cwd) {
40335
+ const timeoutMs = commandTimeoutMs(env);
40328
40336
  const childEnv = {};
40329
40337
  for (const [name, variable] of Object.entries(env)) {
40330
40338
  if (variable !== undefined)
@@ -40343,7 +40351,7 @@ function runCommand(command, env, cwd) {
40343
40351
  stdin: "ignore",
40344
40352
  stdout: fd,
40345
40353
  stderr: "ignore",
40346
- timeout: COMMAND_TIMEOUT_MS,
40354
+ timeout: timeoutMs,
40347
40355
  detached: true
40348
40356
  });
40349
40357
  } catch (error) {
@@ -40356,7 +40364,7 @@ function runCommand(command, env, cwd) {
40356
40364
  } catch {}
40357
40365
  if (result.exitedDueToTimeout) {
40358
40366
  return {
40359
- failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
40367
+ failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
40360
40368
  timedOut: true
40361
40369
  };
40362
40370
  }
@@ -60547,7 +60555,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
60547
60555
 
60548
60556
  // package.json
60549
60557
  var name2 = "@sjawhar/claude-envoy";
60550
- var version2 = "5.4.0";
60558
+ var version2 = "5.5.0";
60551
60559
  var legion = {
60552
60560
  daemonApiVersion: 213
60553
60561
  };
@@ -67990,16 +67998,22 @@ var PS_OPTIONS = {
67990
67998
  env: { LC_ALL: "C", PATH: process.env["PATH"] ?? "/usr/bin:/bin", TZ: "UTC" },
67991
67999
  timeout: 1000
67992
68000
  };
67993
- function processStarted(pid) {
68001
+ function procStarted(pid) {
67994
68002
  try {
67995
68003
  const stat = readFileSync10(`/proc/${pid}/stat`, "utf8");
67996
68004
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
67997
68005
  } catch {
67998
- const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS);
67999
- const started = ps.status === 0 ? ps.stdout.trim() : "";
68000
- return started === "" ? undefined : `ps:${started}`;
68006
+ return;
68001
68007
  }
68002
68008
  }
68009
+ function processStarted(pid) {
68010
+ const started = procStarted(pid);
68011
+ if (started !== undefined)
68012
+ return started;
68013
+ const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS);
68014
+ const fromPs = ps.status === 0 ? ps.stdout.trim() : "";
68015
+ return fromPs === "" ? undefined : `ps:${fromPs}`;
68016
+ }
68003
68017
  function recordOfProcess(record, pid) {
68004
68018
  const started = processStarted(pid);
68005
68019
  return record.codex_started !== null && started !== undefined && record.codex_started === started;
@@ -980,8 +980,8 @@ __export(exports_coerce, {
980
980
  });
981
981
 
982
982
  // hooks/session-hook.ts
983
- import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
984
- import { join as join10 } from "path";
983
+ import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync7, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
984
+ import { join as join11 } from "path";
985
985
 
986
986
  // ../contracts/src/held-secrets.ts
987
987
  var WITHHELD = "<withheld>";
@@ -19254,6 +19254,13 @@ function readSecretFile(variable, filePath) {
19254
19254
 
19255
19255
  // ../envoy-client/src/envoy-config.ts
19256
19256
  var COMMAND_TIMEOUT_MS = 1e4;
19257
+ var COMMAND_TIMEOUT_VARIABLE = "ENVOY_COMMAND_TIMEOUT_MS";
19258
+ var LONGEST_TIMEOUT_MS = 2147483647;
19259
+ function commandTimeoutMs(env) {
19260
+ const text = env[COMMAND_TIMEOUT_VARIABLE] ?? "";
19261
+ const ms = /^[1-9]\d*$/.test(text) ? Number(text) : Number.NaN;
19262
+ return ms <= LONGEST_TIMEOUT_MS ? ms : COMMAND_TIMEOUT_MS;
19263
+ }
19257
19264
  function nonEmpty(value) {
19258
19265
  return value === undefined || value === "" ? undefined : value;
19259
19266
  }
@@ -19412,6 +19419,7 @@ var processGlobal = globalThis;
19412
19419
  var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
19413
19420
  processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
19414
19421
  function runCommand(command, env, cwd) {
19422
+ const timeoutMs = commandTimeoutMs(env);
19415
19423
  const childEnv = {};
19416
19424
  for (const [name, variable] of Object.entries(env)) {
19417
19425
  if (variable !== undefined)
@@ -19430,7 +19438,7 @@ function runCommand(command, env, cwd) {
19430
19438
  stdin: "ignore",
19431
19439
  stdout: fd,
19432
19440
  stderr: "ignore",
19433
- timeout: COMMAND_TIMEOUT_MS,
19441
+ timeout: timeoutMs,
19434
19442
  detached: true
19435
19443
  });
19436
19444
  } catch (error) {
@@ -19443,7 +19451,7 @@ function runCommand(command, env, cwd) {
19443
19451
  } catch {}
19444
19452
  if (result.exitedDueToTimeout) {
19445
19453
  return {
19446
- failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
19454
+ failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
19447
19455
  timedOut: true
19448
19456
  };
19449
19457
  }
@@ -32138,6 +32146,13 @@ function claudeProjectDirectory(environment, fallback) {
32138
32146
  return configuredValue(environment.CLAUDE_PROJECT_DIR) ?? fallback;
32139
32147
  }
32140
32148
 
32149
+ // src/codex/codex-session-record.ts
32150
+ import { spawnSync } from "child_process";
32151
+ import { readFileSync as readFileSync6, readlinkSync as readlinkSync2, unwatchFile, watchFile } from "fs";
32152
+ import { mkdir as mkdir4, readFile as readFile5, rename as rename5, utimes as utimes3, writeFile as writeFile3 } from "fs/promises";
32153
+ import { homedir as homedir3 } from "os";
32154
+ import { basename as basename4, dirname as dirname5, join as join10 } from "path";
32155
+
32141
32156
  // src/session-identity.ts
32142
32157
  import { readFile as readFile4 } from "fs/promises";
32143
32158
  import { basename as basename3, join as join9 } from "path";
@@ -32299,6 +32314,194 @@ async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
32299
32314
  await pruneStateDirectory(join9(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
32300
32315
  }
32301
32316
 
32317
+ // src/codex/codex-session-record.ts
32318
+ var CodexSessionRecord = object({
32319
+ session_id: string2().min(1),
32320
+ transcript_path: string2().nullable(),
32321
+ codex_home: string2().min(1),
32322
+ cwd: string2().min(1),
32323
+ source: string2().nullable(),
32324
+ codex_executable: string2().nullable(),
32325
+ codex_started: string2().nullable().default(null)
32326
+ });
32327
+ function codexSessionRecordFile(stateDirectory, pid) {
32328
+ return join10(stateDirectory, "codex-sessions", `${pid}.json`);
32329
+ }
32330
+ function codexEndedFile(stateDirectory, pid, sessionId) {
32331
+ return join10(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`);
32332
+ }
32333
+ async function markSessionEnded(stateDirectory, pid, sessionId) {
32334
+ const marker = codexEndedFile(stateDirectory, pid, sessionId);
32335
+ await mkdir4(dirname5(marker), { mode: 448, recursive: true });
32336
+ await writeFile3(marker, "", { mode: 384 });
32337
+ const now = new Date;
32338
+ await utimes3(codexSessionRecordFile(stateDirectory, pid), now, now);
32339
+ }
32340
+ function watchRecord(file, pid, ended, changed, intervalMs) {
32341
+ const look = () => {
32342
+ readCodexSessionRecord(file).then(async (record) => {
32343
+ if (record === undefined || !recordOfProcess(record, pid))
32344
+ return;
32345
+ changed(record, await ended(record.session_id));
32346
+ });
32347
+ };
32348
+ watchFile(file, { interval: intervalMs }, look);
32349
+ look();
32350
+ return () => unwatchFile(file, look);
32351
+ }
32352
+ async function sessionEnded(file) {
32353
+ try {
32354
+ await readFile5(file);
32355
+ return true;
32356
+ } catch {
32357
+ return false;
32358
+ }
32359
+ }
32360
+ async function writeCodexSessionRecord(file, value) {
32361
+ await mkdir4(dirname5(file), { recursive: true, mode: 448 });
32362
+ const temporary = `${file}.${process.pid}.tmp`;
32363
+ await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
32364
+ await rename5(temporary, file);
32365
+ }
32366
+ async function readCodexSessionRecord(file) {
32367
+ try {
32368
+ const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile5(file, "utf8")));
32369
+ return parsed.success ? parsed.data : undefined;
32370
+ } catch {
32371
+ return;
32372
+ }
32373
+ }
32374
+ function codexHome(env) {
32375
+ const set = env["CODEX_HOME"];
32376
+ return set !== undefined && set !== "" ? set : join10(env["HOME"] || homedir3(), ".codex");
32377
+ }
32378
+ function codexPluginDataDirectory(pluginRoot) {
32379
+ const version = pluginRoot;
32380
+ const plugin = dirname5(version);
32381
+ const marketplace = dirname5(plugin);
32382
+ const cache = dirname5(marketplace);
32383
+ const plugins = dirname5(cache);
32384
+ if (basename4(cache) !== "cache" || basename4(plugins) !== "plugins")
32385
+ return;
32386
+ return join10(plugins, "data", `${basename4(plugin)}-${basename4(marketplace)}`);
32387
+ }
32388
+ var MAX_ANCESTORS = 16;
32389
+ function codexProcessId(readComm = procComm, readParent = procParent) {
32390
+ let pid = process.ppid;
32391
+ for (let step = 0;pid !== undefined && pid > 1 && step < MAX_ANCESTORS; step++) {
32392
+ if (readComm(pid) === "codex")
32393
+ return pid;
32394
+ pid = readParent(pid);
32395
+ }
32396
+ return process.ppid;
32397
+ }
32398
+ function procComm(pid) {
32399
+ try {
32400
+ return readFileSync6(`/proc/${pid}/comm`, "utf8").trim();
32401
+ } catch {
32402
+ return;
32403
+ }
32404
+ }
32405
+ function procParent(pid) {
32406
+ try {
32407
+ const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
32408
+ const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
32409
+ return Number.isInteger(parent) ? parent : undefined;
32410
+ } catch {
32411
+ return;
32412
+ }
32413
+ }
32414
+ var PS_OPTIONS = {
32415
+ encoding: "utf8",
32416
+ env: { LC_ALL: "C", PATH: process.env["PATH"] ?? "/usr/bin:/bin", TZ: "UTC" },
32417
+ timeout: 1000
32418
+ };
32419
+ function procStarted(pid) {
32420
+ try {
32421
+ const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
32422
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
32423
+ } catch {
32424
+ return;
32425
+ }
32426
+ }
32427
+ function processStarted(pid) {
32428
+ const started = procStarted(pid);
32429
+ if (started !== undefined)
32430
+ return started;
32431
+ const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS);
32432
+ const fromPs = ps.status === 0 ? ps.stdout.trim() : "";
32433
+ return fromPs === "" ? undefined : `ps:${fromPs}`;
32434
+ }
32435
+ function recordOfProcess(record, pid) {
32436
+ const started = processStarted(pid);
32437
+ return record.codex_started !== null && started !== undefined && record.codex_started === started;
32438
+ }
32439
+ function sharedAppServer(pid) {
32440
+ let argv;
32441
+ try {
32442
+ argv = readFileSync6(`/proc/${pid}/cmdline`, "utf8").split("\x00");
32443
+ } catch {
32444
+ const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS);
32445
+ if (ps.status !== 0)
32446
+ return false;
32447
+ argv = ps.stdout.trim().split(/\s+/);
32448
+ }
32449
+ return SHARED_SUBCOMMANDS.has(codexSubcommand(argv.slice(1)) ?? "");
32450
+ }
32451
+ var SHARED_SUBCOMMANDS = new Set(["agents", "app-server"]);
32452
+ var VALUE_OPTIONS = new Set([
32453
+ "-c",
32454
+ "--config",
32455
+ "--enable",
32456
+ "--disable",
32457
+ "--remote",
32458
+ "--remote-auth-token-env",
32459
+ "-i",
32460
+ "--image",
32461
+ "-m",
32462
+ "--model",
32463
+ "--local-provider",
32464
+ "-p",
32465
+ "--profile",
32466
+ "-s",
32467
+ "--sandbox",
32468
+ "-a",
32469
+ "--ask-for-approval",
32470
+ "-C",
32471
+ "--cd",
32472
+ "--add-dir"
32473
+ ]);
32474
+ function codexSubcommand(args) {
32475
+ for (let index = 0;index < args.length; index++) {
32476
+ const arg = args[index] ?? "";
32477
+ if (arg === "--")
32478
+ return args[index + 1];
32479
+ if (!arg.startsWith("-"))
32480
+ return arg;
32481
+ if (VALUE_OPTIONS.has(arg))
32482
+ index++;
32483
+ }
32484
+ return;
32485
+ }
32486
+ var SHARED_APP_SERVER_NOTE = "Codex runs this session in its shared app server (`codex app-server`), which runs several sessions in one process, so the Envoy plugin does not register it with Envoy: it receives no Envoy messages and does not show on Dispatch's Agents page. Its `dispatch` tool works, acting as this session.";
32487
+ async function pruneCodexSessionRecords(stateDirectory) {
32488
+ await pruneStateDirectory(join10(stateDirectory, "codex-sessions"), (file) => {
32489
+ const match = /^(\d+)\.(?:json|.+\.ended)$/.exec(basename4(file));
32490
+ return match !== null && !processExists(Number(match[1]));
32491
+ });
32492
+ await pruneStateDirectory(join10(stateDirectory, "codex-servers"), (file) => {
32493
+ const name = basename4(file);
32494
+ return /^\d+$/.test(name) && !processExists(Number(name));
32495
+ });
32496
+ }
32497
+ function codexExecutable(pid) {
32498
+ try {
32499
+ return readlinkSync2(`/proc/${pid}/exe`);
32500
+ } catch {
32501
+ return;
32502
+ }
32503
+ }
32504
+
32302
32505
  // hooks/hook-arguments.ts
32303
32506
  function parseHookArguments(argv) {
32304
32507
  const at = argv.indexOf("--host");
@@ -32345,6 +32548,28 @@ var RefreshOutcome = object({
32345
32548
  notice: string2().nullable().optional()
32346
32549
  });
32347
32550
  var ANSWERS_TIMING_FILE = "ENVOY_ANSWERS_TIMING_FILE";
32551
+ var startedRefresher = null;
32552
+ var armedWaits = [];
32553
+ function armedWait(kind, limit, { capMs = Number.POSITIVE_INFINITY, leastMs = 0, at = performance.now() } = {}) {
32554
+ const ms = Math.max(leastMs, Math.min(capMs, Math.max(0, Math.round(limit - at))));
32555
+ if (process.env[ANSWERS_TIMING_FILE] !== undefined)
32556
+ armedWaits.push({ kind, at, ms, limit });
32557
+ return ms;
32558
+ }
32559
+ function writeAnswersTiming(timing) {
32560
+ const timingFile = process.env[ANSWERS_TIMING_FILE];
32561
+ if (timingFile === undefined)
32562
+ return;
32563
+ try {
32564
+ writeAtomically(timingFile, JSON.stringify({ ...timing, waits: armedWaits, refresher: startedRefresher }));
32565
+ } catch {}
32566
+ }
32567
+ function nameRefresher(pid) {
32568
+ if (process.env[ANSWERS_TIMING_FILE] === undefined)
32569
+ return;
32570
+ startedRefresher = { pid, started: procStarted(pid) ?? null };
32571
+ writeAnswersTiming({});
32572
+ }
32348
32573
  var DISPATCH_HOST_LINE = "export DISPATCH_HOST=claude";
32349
32574
  var JJ_CONFIG_EXPORT = "export JJ_CONFIG=";
32350
32575
  var JJ_BASE_CHAIN_TIMEOUT_MS = 3000;
@@ -32353,7 +32578,7 @@ function singleQuoted(value) {
32353
32578
  }
32354
32579
  function envFileText(envFile) {
32355
32580
  try {
32356
- return readFileSync6(envFile, "utf8");
32581
+ return readFileSync7(envFile, "utf8");
32357
32582
  } catch (error) {
32358
32583
  if (!hasErrnoCode(error, "ENOENT"))
32359
32584
  throw error;
@@ -32470,19 +32695,16 @@ function dispatchFirst(raw) {
32470
32695
  process.stdout.write(JSON.stringify({
32471
32696
  hookSpecificOutput: {
32472
32697
  hookEventName: input.hook_event_name,
32473
- additionalContext: readDispatchFirstContext(dispatchFirstSkillFile(join10(pluginRoot, "skills")))
32698
+ additionalContext: readDispatchFirstContext(dispatchFirstSkillFile(join11(pluginRoot, "skills")))
32474
32699
  }
32475
32700
  }));
32476
32701
  }
32477
- function remainingUntil(at) {
32478
- return Math.max(0, Math.round(at - performance.now()));
32479
- }
32480
32702
  function refreshLockHeld(lock) {
32481
32703
  let age;
32482
32704
  let text;
32483
32705
  try {
32484
32706
  age = Date.now() - statSync2(lock).mtimeMs;
32485
- text = readFileSync6(lock, "utf8");
32707
+ text = readFileSync7(lock, "utf8");
32486
32708
  } catch (error) {
32487
32709
  if (hasErrnoCode(error, "ENOENT"))
32488
32710
  return false;
@@ -32518,7 +32740,7 @@ function takeRefreshLock(lock) {
32518
32740
  function refreshOutcome(file, since) {
32519
32741
  let value;
32520
32742
  try {
32521
- value = JSON.parse(readFileSync6(file, "utf8"));
32743
+ value = JSON.parse(readFileSync7(file, "utf8"));
32522
32744
  } catch {
32523
32745
  return;
32524
32746
  }
@@ -32532,16 +32754,13 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
32532
32754
  } catch (error) {
32533
32755
  return { reason: messageFor(error) };
32534
32756
  }
32535
- const lock = join10(directory, REFRESH_LOCK);
32757
+ const lock = join11(directory, REFRESH_LOCK);
32536
32758
  if (!refreshLockHeld(lock)) {
32537
- Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd, "--host", HOST], {
32538
- stdin: "ignore",
32539
- stdout: "ignore",
32540
- stderr: "ignore",
32541
- detached: true
32542
- }).unref();
32759
+ const refresher = Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd, "--host", HOST], { stdin: "ignore", stdout: "ignore", stderr: "ignore", detached: true });
32760
+ refresher.unref();
32761
+ nameRefresher(refresher.pid);
32543
32762
  }
32544
- const file = join10(directory, REFRESH_OUTCOME);
32763
+ const file = join11(directory, REFRESH_OUTCOME);
32545
32764
  for (;; ) {
32546
32765
  const outcome = refreshOutcome(file, startedAt);
32547
32766
  if (outcome !== undefined) {
@@ -32553,13 +32772,13 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
32553
32772
  reason: `the refresher read ${read}, not the Dispatch envoy.json names now`
32554
32773
  };
32555
32774
  }
32556
- const left = remainingUntil(by);
32557
- if (left === 0) {
32775
+ const now = performance.now();
32776
+ if (Math.round(by - now) <= 0) {
32558
32777
  return {
32559
32778
  reason: `a "!" command in envoy.json had not finished ${Math.round(by)} ms after the hook started`
32560
32779
  };
32561
32780
  }
32562
- await Bun.sleep(Math.min(REFRESH_POLL_MS, left));
32781
+ await Bun.sleep(armedWait("refresher", by, { capMs: REFRESH_POLL_MS, at: now }));
32563
32782
  }
32564
32783
  }
32565
32784
  async function answersMessage(session, cwd, startedAt, by) {
@@ -32584,7 +32803,7 @@ async function answersMessage(session, cwd, startedAt, by) {
32584
32803
  dispatch,
32585
32804
  dispatchUrl,
32586
32805
  env: process.env,
32587
- deadlineMs: Math.max(ANSWERS_LEAST_WAIT_MS, remainingUntil(by))
32806
+ deadlineMs: armedWait("read", by, { leastMs: ANSWERS_LEAST_WAIT_MS })
32588
32807
  });
32589
32808
  }
32590
32809
  async function answers(text) {
@@ -32610,24 +32829,19 @@ async function answers(text) {
32610
32829
  printed = performance.now();
32611
32830
  await Promise.race([
32612
32831
  sessionAnswersSettled(input.session_id),
32613
- Bun.sleep(remainingUntil(by + ANSWERS_SETTLE_MS))
32832
+ Bun.sleep(armedWait("settle", by + ANSWERS_SETTLE_MS))
32614
32833
  ]);
32615
32834
  } catch (error) {
32616
32835
  process.stderr.write(`envoy: people's answers were not added \u2014 ${messageFor(error)}
32617
32836
  `);
32618
32837
  }
32619
- const timingFile = process.env[ANSWERS_TIMING_FILE];
32620
- if (timingFile !== undefined) {
32621
- try {
32622
- writeFileSync2(timingFile, JSON.stringify({ began, printed, ended: performance.now() }));
32623
- } catch {}
32624
- }
32838
+ writeAnswersTiming({ began, printed, ended: performance.now(), deadline: by });
32625
32839
  process.exit(0);
32626
32840
  }
32627
32841
  async function answersRefresh(session, cwd) {
32628
32842
  const directory = sessionDirectory(process.env, session);
32629
32843
  mkdirSync2(directory, { recursive: true, mode: 448 });
32630
- const lock = join10(directory, REFRESH_LOCK);
32844
+ const lock = join11(directory, REFRESH_LOCK);
32631
32845
  if (takeRefreshLock(lock)) {
32632
32846
  try {
32633
32847
  const file = sessionConfigFile(HOST, process.env);
@@ -32645,7 +32859,7 @@ async function answersRefresh(session, cwd) {
32645
32859
  text: read.text ?? null,
32646
32860
  notice: read.notice ?? null
32647
32861
  };
32648
- writeAtomically(join10(directory, REFRESH_OUTCOME), JSON.stringify(outcome));
32862
+ writeAtomically(join11(directory, REFRESH_OUTCOME), JSON.stringify(outcome));
32649
32863
  } finally {
32650
32864
  rmSync3(lock, { force: true });
32651
32865
  }
@@ -116,6 +116,7 @@ import {
116
116
  } from "@legion/pi-shared/jj-attribution"
117
117
  import { z } from "zod"
118
118
  import { claudeProjectDirectory, configuredValue } from "../src/claude-session"
119
+ import { procStarted } from "../src/codex/codex-session-record"
119
120
  import { sessionHandoffFile, writeSessionHandoff } from "../src/session-identity"
120
121
  import { recordChosenTitle } from "../src/session-state"
121
122
  import { parseHookArguments } from "./hook-arguments"
@@ -184,9 +185,66 @@ const RefreshOutcome = z.object({
184
185
  })
185
186
  /** Tests only: the file the answers hook writes its own timing to, `{ began, printed, ended }` in
186
187
  * ms after its process started (when its code began, when it printed or found nothing to print,
187
- * and when it exits), so a test can hold the hook to its deadline rather than to bun's start-up.
188
- * Unset, as Claude Code runs it, the hook writes nothing. */
188
+ * and when it exits), `deadline`, the print deadline it applied, and `waits`, each wait it armed
189
+ * on the way (`armedWait`), so a test holds the hook to its deadline by what the hook did rather
190
+ * than by the time bun's start-up or the host's scheduling took; and `refresher`, the refresher it
191
+ * started (null when it started none), so a test waits on that process's end rather than on a
192
+ * scan of every process on the machine. The hook writes the file whole (`writeAtomically`) as
193
+ * soon as it started a refresher, naming it, so a test that ended the hook before it exited
194
+ * still knows that refresher, and again as it exits.
195
+ * Unset, as Claude Code runs it, the hook writes nothing and records nothing. */
189
196
  const ANSWERS_TIMING_FILE = "ENVOY_ANSWERS_TIMING_FILE"
197
+ /** The refresher this hook process started, for `ANSWERS_TIMING_FILE`: its pid, and when it
198
+ * started (`procStarted`), which a later process given the same pid does not share, or null where
199
+ * /proc does not give it at once; null when it started none. */
200
+ let startedRefresher: { readonly pid: number; readonly started: string | null } | null = null
201
+ /** Each wait the answers hook armed, for `ANSWERS_TIMING_FILE`: a look at the refresher's outcome,
202
+ * the Dispatch read, or the read left in flight after printing; when it armed it (ms after the
203
+ * process started), for how long, and the time it was armed against (`limit`). */
204
+ const armedWaits: {
205
+ readonly kind: "refresher" | "read" | "settle"
206
+ readonly at: number
207
+ readonly ms: number
208
+ readonly limit: number
209
+ }[] = []
210
+
211
+ /** How long a wait of `kind` armed at `at` (a `performance.now()` reading, now by default) lasts:
212
+ * until `limit`, another such reading, in whole ms because the failure line names the wait, at
213
+ * most `capMs` and at least `leastMs`. Recorded for `ANSWERS_TIMING_FILE`. */
214
+ function armedWait(
215
+ kind: "refresher" | "read" | "settle",
216
+ limit: number,
217
+ { capMs = Number.POSITIVE_INFINITY, leastMs = 0, at = performance.now() } = {},
218
+ ): number {
219
+ const ms = Math.max(leastMs, Math.min(capMs, Math.max(0, Math.round(limit - at))))
220
+ if (process.env[ANSWERS_TIMING_FILE] !== undefined) armedWaits.push({ kind, at, ms, limit })
221
+ return ms
222
+ }
223
+
224
+ /** Writes `timing`, `armedWaits` and `startedRefresher` to `ANSWERS_TIMING_FILE` when that is set. */
225
+ function writeAnswersTiming(timing: Record<string, number | null>): void {
226
+ const timingFile = process.env[ANSWERS_TIMING_FILE]
227
+ if (timingFile === undefined) return
228
+ try {
229
+ writeAtomically(
230
+ timingFile,
231
+ JSON.stringify({ ...timing, waits: armedWaits, refresher: startedRefresher }),
232
+ )
233
+ } catch {
234
+ // The tests' seam only: a path it cannot write never changes what the hook printed or its exit.
235
+ }
236
+ }
237
+
238
+ /** Names the refresher `pid` in `ANSWERS_TIMING_FILE` at once, when that is set: right after its
239
+ * spawn, while it can be no other process's pid. Its start comes from `/proc/<pid>/stat` alone (a
240
+ * 1 to 3 ms read), never `ps`, which can take seconds (procps `ps -p` reads every process: 0.76 to
241
+ * 0.98 s unloaded on the dev box, up to 8.2 s under load), time no part of the hook's deadline
242
+ * is for. With no /proc the start is null, and the test tells the refresher's end by its pid. */
243
+ function nameRefresher(pid: number): void {
244
+ if (process.env[ANSWERS_TIMING_FILE] === undefined) return
245
+ startedRefresher = { pid, started: procStarted(pid) ?? null }
246
+ writeAnswersTiming({})
247
+ }
190
248
 
191
249
  const DISPATCH_HOST_LINE = "export DISPATCH_HOST=claude"
192
250
  /** What an overlay export line starts with: the one line of the env file this hook replaces
@@ -367,12 +425,6 @@ function dispatchFirst(raw: unknown): void {
367
425
  )
368
426
  }
369
427
 
370
- /** The ms left until `at`, a `performance.now()` reading, in whole ms because the failure line
371
- * names the wait. */
372
- function remainingUntil(at: number): number {
373
- return Math.max(0, Math.round(at - performance.now()))
374
- }
375
-
376
428
  /** Whether a refresher holds `lock`: it exists, is younger than `REFRESH_LOCK_STALE_MS`, and the
377
429
  * pid in it is alive or not yet written. A lock its refresher died holding is stale at once. */
378
430
  function refreshLockHeld(lock: string): boolean {
@@ -452,12 +504,12 @@ async function refreshedAnswers(
452
504
  }
453
505
  const lock = join(directory, REFRESH_LOCK)
454
506
  if (!refreshLockHeld(lock)) {
455
- Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd, "--host", HOST], {
456
- stdin: "ignore",
457
- stdout: "ignore",
458
- stderr: "ignore",
459
- detached: true,
460
- }).unref()
507
+ const refresher = Bun.spawn(
508
+ [process.execPath, Bun.main, "answers-refresh", session, cwd, "--host", HOST],
509
+ { stdin: "ignore", stdout: "ignore", stderr: "ignore", detached: true },
510
+ )
511
+ refresher.unref()
512
+ nameRefresher(refresher.pid)
461
513
  }
462
514
  const file = join(directory, REFRESH_OUTCOME)
463
515
  for (;;) {
@@ -476,13 +528,14 @@ async function refreshedAnswers(
476
528
  reason: `the refresher read ${read}, not the Dispatch envoy.json names now`,
477
529
  }
478
530
  }
479
- const left = remainingUntil(by)
480
- if (left === 0) {
531
+ // One reading of the clock both decides that the deadline has come and arms the next look.
532
+ const now = performance.now()
533
+ if (Math.round(by - now) <= 0) {
481
534
  return {
482
535
  reason: `a "!" command in envoy.json had not finished ${Math.round(by)} ms after the hook started`,
483
536
  }
484
537
  }
485
- await Bun.sleep(Math.min(REFRESH_POLL_MS, left))
538
+ await Bun.sleep(armedWait("refresher", by, { capMs: REFRESH_POLL_MS, at: now }))
486
539
  }
487
540
  }
488
541
 
@@ -522,7 +575,7 @@ async function answersMessage(
522
575
  env: process.env,
523
576
  // The read itself always gets the least wait, so a start-up and a resolution that spent the
524
577
  // budget on a loaded host never cost a list Dispatch answers at once.
525
- deadlineMs: Math.max(ANSWERS_LEAST_WAIT_MS, remainingUntil(by)),
578
+ deadlineMs: armedWait("read", by, { leastMs: ANSWERS_LEAST_WAIT_MS }),
526
579
  })
527
580
  }
528
581
 
@@ -562,19 +615,12 @@ async function answers(text: string): Promise<never> {
562
615
  printed = performance.now()
563
616
  await Promise.race([
564
617
  sessionAnswersSettled(input.session_id),
565
- Bun.sleep(remainingUntil(by + ANSWERS_SETTLE_MS)),
618
+ Bun.sleep(armedWait("settle", by + ANSWERS_SETTLE_MS)),
566
619
  ])
567
620
  } catch (error) {
568
621
  process.stderr.write(`envoy: people's answers were not added — ${messageFor(error)}\n`)
569
622
  }
570
- const timingFile = process.env[ANSWERS_TIMING_FILE]
571
- if (timingFile !== undefined) {
572
- try {
573
- writeFileSync(timingFile, JSON.stringify({ began, printed, ended: performance.now() }))
574
- } catch {
575
- // The tests' seam only: a path it cannot write never changes what the hook printed or its exit.
576
- }
577
- }
623
+ writeAnswersTiming({ began, printed, ended: performance.now(), deadline: by })
578
624
  // Exits rather than returns: a read still running would hold the process open.
579
625
  process.exit(0)
580
626
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "5.4.0",
3
+ "version": "5.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -192,23 +192,31 @@ const PS_OPTIONS = {
192
192
  timeout: 1_000,
193
193
  } as const
194
194
 
195
- /** When process `pid` started: the 22nd field of `/proc/<pid>/stat` (clock ticks since boot), or
196
- * where there is no /proc, `ps`'s start time to the second, prefixed `ps:`; undefined where
197
- * neither can be read. Two processes that had one id never share it. */
198
- export function processStarted(pid: number): string | undefined {
195
+ /** When process `pid` started by `/proc/<pid>/stat` alone: its 22nd field (clock ticks since
196
+ * boot); undefined where that file cannot be read (no /proc, or no such process). */
197
+ export function procStarted(pid: number): string | undefined {
199
198
  try {
200
199
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8")
201
200
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]
202
201
  } catch {
203
- // No /proc (macOS): `ps` names the start to the second, which a reused pid does not repeat
204
- // within a second of the process it replaced exiting, and the hook and the server read it
205
- // the same way.
206
- const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS)
207
- const started = ps.status === 0 ? ps.stdout.trim() : ""
208
- return started === "" ? undefined : `ps:${started}`
202
+ return undefined
209
203
  }
210
204
  }
211
205
 
206
+ /** When process `pid` started: `procStarted`, or where that cannot be read (macOS has no /proc),
207
+ * `ps`'s start time to the second, prefixed `ps:`; undefined where neither can be read. Two
208
+ * processes that had one id never share it. */
209
+ export function processStarted(pid: number): string | undefined {
210
+ const started = procStarted(pid)
211
+ if (started !== undefined) return started
212
+ // No /proc (macOS): `ps` names the start to the second, which a reused pid does not repeat
213
+ // within a second of the process it replaced exiting, and the hook and the server read it the
214
+ // same way.
215
+ const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS)
216
+ const fromPs = ps.status === 0 ? ps.stdout.trim() : ""
217
+ return fromPs === "" ? undefined : `ps:${fromPs}`
218
+ }
219
+
212
220
  /** Whether `record` belongs to the `codex` process `pid` now runs, rather than to an earlier
213
221
  * process that had the same id. A record or a process whose start cannot be read is not taken:
214
222
  * records outlive their process, and a new `codex` that reused the pid would otherwise bind to the