@sjawhar/claude-envoy 5.30.0 → 5.31.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.30.0"
5
+ "version": "5.31.0"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "5.30.0",
3
+ "version": "5.31.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
  }
@@ -23780,7 +23780,7 @@ function scrubProcessStreams() {
23780
23780
  import { spawn as spawn2 } from "child_process";
23781
23781
  import { unwatchFile as unwatchFile3, watchFile as watchFile3 } from "fs";
23782
23782
  import { homedir as homedir4 } from "os";
23783
- import { join as join22, resolve as resolve3 } from "path";
23783
+ import { join as join23, resolve as resolve4 } from "path";
23784
23784
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/core/core.js
23785
23785
  var NEVER = Object.freeze({
23786
23786
  status: "aborted"
@@ -63514,57 +63514,18 @@ var import_nats5 = __toESM(require_mod4(), 1);
63514
63514
 
63515
63515
  // package.json
63516
63516
  var name2 = "@sjawhar/claude-envoy";
63517
- var version2 = "5.30.0";
63518
- var legion = {
63519
- daemonApiVersion: 275
63520
- };
63517
+ var version2 = "5.31.0";
63521
63518
  var package_default = {
63522
63519
  name: name2,
63523
63520
  version: version2,
63524
63521
  license: "Apache-2.0",
63525
63522
  description: "Claude Code plugin for Legion's Envoy bus",
63526
63523
  type: "module",
63527
- files: [
63528
- ".claude-plugin/**",
63529
- ".mcp.json",
63530
- ".omp-plugin/**",
63531
- "bin/**",
63532
- "dist/**",
63533
- "hooks/**",
63534
- "legion/**",
63535
- "scripts/**",
63536
- "skills/**",
63537
- "src/**",
63538
- "README.md",
63539
- "AGENTS.md"
63540
- ],
63541
- legion,
63542
- repository: {
63543
- type: "git",
63544
- url: "https://github.com/cybermonklabs/legion"
63545
- },
63546
- scripts: {
63547
- channel: "bun bin/envoy-channel.ts",
63548
- "verify-build": "bash scripts/verify-build.sh",
63549
- prepack: "bash scripts/pack-skills.sh",
63550
- postpack: "bash scripts/pack-skills.sh --restore",
63551
- typecheck: "bunx tsc --noEmit",
63552
- test: "bun test --timeout=60000",
63553
- lint: "bunx biome check src/ hooks/ scripts/"
63554
- },
63555
- devDependencies: {
63556
- "@biomejs/biome": "^2.3.14",
63557
- "@legion/cipher-client": "workspace:*",
63558
- "@legion/contracts": "workspace:*",
63559
- "@legion/envoy-client": "workspace:*",
63560
- "@legion/pi-shared": "workspace:*",
63561
- "@legion/test-fixtures": "workspace:*",
63562
- "@modelcontextprotocol/sdk": "^1.30.0",
63563
- "bun-types": "latest",
63564
- nats: "^2.29.2",
63565
- typescript: "^5.3.0",
63566
- zod: "4.3.6"
63567
- }
63524
+ files: [".claude-plugin/**", ".mcp.json", ".omp-plugin/**", "bin/**", "dist/**", "hooks/**", "legion/**", "scripts/**", "skills/**", "src/**", "README.md", "AGENTS.md"],
63525
+ repository: { type: "git", url: "https://github.com/cybermonklabs/legion" },
63526
+ scripts: { channel: "bun bin/envoy-channel.ts", "verify-build": "bash scripts/verify-build.sh", prepack: "bash scripts/pack-skills.sh", postpack: "bash scripts/pack-skills.sh --restore", typecheck: "bunx tsc --noEmit", test: "bun test --timeout=60000", lint: "bunx biome check src/ hooks/ scripts/" },
63527
+ devDependencies: { "@biomejs/biome": "^2.3.14", "@legion/cipher-client": "workspace:*", "@legion/contracts": "workspace:*", "@legion/envoy-client": "workspace:*", "@legion/pi-shared": "workspace:*", "@legion/test-fixtures": "workspace:*", "@modelcontextprotocol/sdk": "^1.30.0", "bun-types": "latest", nats: "^2.29.2", typescript: "^5.3.0", zod: "4.3.6" },
63528
+ legion: { daemonApiVersion: 275 }
63568
63529
  };
63569
63530
 
63570
63531
  // ../envoy-client/src/inbound-card.ts
@@ -64948,9 +64909,42 @@ function channelConnectionName(name, bundlePath, packageName) {
64948
64909
 
64949
64910
  // src/legion-claim.ts
64950
64911
  import { readdir as readdir4, stat as stat5 } from "fs/promises";
64951
- import { join as join14 } from "path";
64912
+ import { join as join15 } from "path";
64952
64913
  import { setTimeout as delay2 } from "timers/promises";
64953
64914
 
64915
+ // ../contracts/src/daemon-contract.ts
64916
+ import { existsSync, readdirSync as readdirSync3, readFileSync as readFileSync7 } from "fs";
64917
+ import { dirname as dirname6, join as join13, resolve as resolve3 } from "path";
64918
+ var ENTRY_FIXTURE_NAME = /^[0-9]{14}_.+\.json$/;
64919
+ var DAEMON_API_FIXTURES = join13("packages", "contracts", "fixtures", "daemon-api");
64920
+ function daemonContract(manifest, from) {
64921
+ const declared = manifest.legion?.daemonApiVersion;
64922
+ if (declared !== undefined)
64923
+ return declared;
64924
+ for (let dir = resolve3(from);; dir = dirname6(dir)) {
64925
+ const fixtures = join13(dir, DAEMON_API_FIXTURES);
64926
+ const releasedFile = join13(fixtures, "released-contracts.json");
64927
+ if (existsSync(releasedFile)) {
64928
+ return lastReleased(releasedFile) + entryFixtures(join13(fixtures, "contracts"));
64929
+ }
64930
+ if (dirname6(dir) === dir)
64931
+ break;
64932
+ }
64933
+ throw new Error(`the plugin's package.json holds no legion.daemonApiVersion, which every pack writes, and ${from} is in no checkout: no directory from it up holds ${join13(DAEMON_API_FIXTURES, "released-contracts.json")}`);
64934
+ }
64935
+ function lastReleased(file) {
64936
+ const released = JSON.parse(readFileSync7(file, "utf8"));
64937
+ if (!Array.isArray(released) || released.length === 0 || !released.every((contract, at) => Number.isInteger(contract) && (at === 0 || contract > released[at - 1]))) {
64938
+ throw new Error(`${file} is not a list of contract numbers in strictly ascending order`);
64939
+ }
64940
+ return released[released.length - 1];
64941
+ }
64942
+ function entryFixtures(dir) {
64943
+ if (!existsSync(dir))
64944
+ return 0;
64945
+ return readdirSync3(dir).filter((name) => ENTRY_FIXTURE_NAME.test(name)).length;
64946
+ }
64947
+
64954
64948
  // ../pi-shared/src/stall-limits.ts
64955
64949
  var DEFAULT_STALL_LIMITS = {
64956
64950
  reminderMs: 300000,
@@ -66441,8 +66435,8 @@ function listenerAskedToClaimAgain(error) {
66441
66435
 
66442
66436
  // src/legion-phase-hook.ts
66443
66437
  import { randomUUID as randomUUID7 } from "crypto";
66444
- import { readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
66445
- import { dirname as dirname6, join as join13 } from "path";
66438
+ import { readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
66439
+ import { dirname as dirname7, join as join14 } from "path";
66446
66440
 
66447
66441
  // ../pi-shared/src/phase-reminder.ts
66448
66442
  import { randomUUID as randomUUID6 } from "crypto";
@@ -66907,7 +66901,7 @@ function phaseHookToolDefinition() {
66907
66901
  };
66908
66902
  }
66909
66903
  function phaseStallFile(configDir, sessionID) {
66910
- return join13(configDir, `legion-phase-stall-${sessionID}.json`);
66904
+ return join14(configDir, `legion-phase-stall-${sessionID}.json`);
66911
66905
  }
66912
66906
  function paneReminderLog(write) {
66913
66907
  const line = (level, message, context) => {
@@ -66922,7 +66916,7 @@ var NO_RECORD = { entry: undefined, recreatedNoticeSent: false };
66922
66916
  function readPhaseStallRecord(file, log) {
66923
66917
  let raw;
66924
66918
  try {
66925
- raw = readFileSync7(file, "utf8");
66919
+ raw = readFileSync8(file, "utf8");
66926
66920
  } catch (error) {
66927
66921
  const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
66928
66922
  if (!missing) {
@@ -66960,7 +66954,7 @@ function readPhaseStallRecord(file, log) {
66960
66954
  };
66961
66955
  }
66962
66956
  function writePhaseStallRecord(file, entry, recreatedNoticeSent, log) {
66963
- const temporary = join13(dirname6(file), `.legion-phase-stall-${randomUUID7()}`);
66957
+ const temporary = join14(dirname7(file), `.legion-phase-stall-${randomUUID7()}`);
66964
66958
  try {
66965
66959
  writeFileSync4(temporary, JSON.stringify({ ...entry, ...recreatedNoticeSent ? { recreatedNoticeSent } : {} }), { mode: 384 });
66966
66960
  renameSync3(temporary, file);
@@ -67134,6 +67128,7 @@ function createPhaseHookEndpoint(deps) {
67134
67128
  }
67135
67129
 
67136
67130
  // src/legion-claim.ts
67131
+ var PLUGIN_CONTRACT = daemonContract(package_default, import.meta.dir);
67137
67132
  async function legionPane(env) {
67138
67133
  const pointer = env["LEGION_BOOT_TOKEN_FILE"];
67139
67134
  if (pointer === undefined && configuredValue(env["LEGION_BOOT_TOKEN"]) === undefined) {
@@ -67154,7 +67149,7 @@ async function legionPane(env) {
67154
67149
  };
67155
67150
  }
67156
67151
  function paneDaemonClient(daemonUrl) {
67157
- return createLegionDaemonClient(daemonUrl, { pluginContract: legion.daemonApiVersion });
67152
+ return createLegionDaemonClient(daemonUrl, { pluginContract: PLUGIN_CONTRACT });
67158
67153
  }
67159
67154
  function logLegion(line) {
67160
67155
  process.stderr.write(`[legion] ${line}
@@ -67168,12 +67163,12 @@ function stopPane(why) {
67168
67163
  endPane();
67169
67164
  }
67170
67165
  async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
67171
- const projects = join14(configDir, "projects");
67166
+ const projects = join15(configDir, "projects");
67172
67167
  const name = `${sessionID}.jsonl`;
67173
67168
  for (;; ) {
67174
67169
  signal.throwIfAborted();
67175
67170
  for (const directory of await readdir4(projects).catch(() => [])) {
67176
- const file = join14(projects, directory, name);
67171
+ const file = join15(projects, directory, name);
67177
67172
  if (await isFile(file))
67178
67173
  return file;
67179
67174
  }
@@ -67212,7 +67207,7 @@ function startLegionClaim(deps) {
67212
67207
  sessionId: sessionID,
67213
67208
  ompSessionFile: transcript,
67214
67209
  agentId: sessionID,
67215
- pluginContract: legion.daemonApiVersion
67210
+ pluginContract: PLUGIN_CONTRACT
67216
67211
  },
67217
67212
  setCapability: (registered) => {
67218
67213
  capability = registered;
@@ -67453,11 +67448,11 @@ var STALE_ENTRY_INSTRUCTION = "End this turn without completing. The task of the
67453
67448
  function legionToolDescription(host) {
67454
67449
  return "Perform the workflow operation the Legion daemon assigned this role. The daemon advances phases; this tool cannot spawn workers. " + (host.before ?? "") + "handoff_complete (phase workers alone: the daemon refuses an architect's completion, with ACCEPTANCE_IS_SIGN_OFF where nothing else refuses it first, since an architect accepts with sign_off; " + "the daemon accepts a completion only from the role working the issue's current phase, " + "or a role's first completion of the phase it left, which it records and which moves nothing, " + "and the checking role's report on a look of its closed issue's production check) reports this phase complete: `summary` (two sentences for the " + "architect), `verdict` pass|fail from the tester alone on a phase completion (the daemon refuses a verdict from " + "any other role there) and pass|pending|fail on a production check report (pending: production does not carry the merge " + "yet, or carries it with a requirement only the deploy can show still unobserved and a look still to follow; on the check's last look, only for an issue with no such requirement). " + "A tester's fail may name `return_to`, the place of a step of the task its issue runs, 1 for its first: the step the task goes back " + "to; without it, the task goes back to the first implementation step before the step that failed. Only a completion with the verdict " + "fail names it (RETURN_TO_NEEDS_FAIL), a place below 1 is refused (INVALID_RETURN_TO), and so is a step the task cannot go back to " + "(RETURN_REFUSED). " + "A planning, implementing, testing or reviewing phase ends with a handoff record on the " + "Dispatch issue: write it with `dispatch handoff-write --issue <issue> --phase <plan|implement|test|review> --body-file <file>` before " + "calling. This call reads from Dispatch the newest record of the phase your role works or, once the issue has moved on, of the phase it left, " + "and reports it with `commit`, the head that record's body names " + "(`head`, the 40-character lower-case commit the work it reports was done against); in implementing, the implementer's must be the commit its " + "workspace stands on, `@-`, pushed to `legion/<issue>@origin`, so push the branch first; retro, the merger's completion and a phase you left with no record, or with an implement record naming no head, report the commit the workspace stands on. It " + "refuses, posting nothing, a phase you work with no record, a Dispatch that does not answer, and, in implementing, an implement record naming no head, an " + "implementer's `@-` not yet on `legion/<issue>@origin`, or an implement record whose head is not that pushed `@-`, each naming the remedy. A production check report " + "(the task whose first line is `Production check of <KEY>`, handed once the merge closed the issue to the role the check records) needs no " + "handoff and no commit: it carries its verdict and summary alone. A pending report also names `wake_at`, an RFC 3339 time: when you want the " + "next look. A pass, a fail, and a pending on the check's last look end the check, so none of them carries `wake_at` " + "(CHECK_WAKE_UNEXPECTED), and a pending on any other look is refused without one (CHECK_WAKE_REQUIRED). A report on an issue whose check is " + "closed or never opened is refused (CHECK_NOT_OPEN), and so is one from a role the check does not record (CHECK_ROLE_MISMATCH). " + `The completion that ends the retro carries \`plan_rating\` (${LEGION_PLAN_RATING_LEAST} to ${LEGION_PLAN_RATING_MOST}) and \`plan_reason\`, as ` + "skill://legion-retro says, and the daemon refuses a completion that breaks that skill's rating rule " + "(PLAN_RATING_REQUIRED, PLAN_RATING_UNEXPECTED or PLAN_RATING_INPUT). " + "The daemon refuses " + "HANDOFF_SESSION_MISMATCH (another session wrote the record), HANDOFF_NOT_NEW (the record is the one you named for your previous phase: " + "write this phase's handoff), " + "HANDOFF_STALE_ENTRY (this completion is of a phase entry behind the one your role's phases row names, because the phase was entered " + `again while your turn ran, and nothing was recorded. ${STALE_ENTRY_INSTRUCTION}), the implementer's completion of implementing with no open ` + "pull request on `legion/<issue>` and none recorded " + "merged (HANDOFF_NO_PULL_REQUEST: open it; one naming a closed pull request is the architect's to decide); a refused completion changed " + "nothing, so fix what it names and complete again. " + "ready_for_update answers the daemon's update message on this issue's pod: `round` is the round id that message names, and the " + "daemon takes your answer for that round alone. The reviewer creates no commit and pushes nothing, so each commit " + "and push this description names is not its own, and the merger pushes the merge of the base it made. Push every commit you want kept to the issue branch " + "first. Then let each subagent and each background job that you started finish, or stop it. Commit and push what it made " + "before you answer. The daemon replaces the pod and its disk when the round ends. The round ends at the moment the message " + "names. It can end earlier, once every role has answered, no role is in a turn and each role's last report names no running " + "subagent or background job. No answer delays that moment, and the end of a turn is no answer. If a subagent or a background " + "job finishes after you answer, commit and push what it made. Then call ready_for_update again with the same round. " + "The call ends no phase. The daemon holds your next task until your process comes back on the new pod, in this same session. " + (host.after ?? "") + `What a later phase needs goes in your handoff; a question for another live role goes to its role topic with ${host.envoyPublish}.`;
67455
67450
  }
67456
- function pluginBuildOf(manifest) {
67451
+ function pluginBuildOf(manifest, from) {
67457
67452
  return {
67458
67453
  name: manifest.name,
67459
67454
  version: manifest.version,
67460
- pluginContract: manifest.legion.daemonApiVersion
67455
+ pluginContract: daemonContract(manifest, from)
67461
67456
  };
67462
67457
  }
67463
67458
  async function mintClaimGrant(daemon, claim) {
@@ -67725,7 +67720,7 @@ async function completeHandoff(runtime, args, rating) {
67725
67720
  }
67726
67721
 
67727
67722
  // src/legion-tool.ts
67728
- var BUILD = pluginBuildOf(package_default);
67723
+ var BUILD = pluginBuildOf(package_default, import.meta.dir);
67729
67724
  var LEGION_TOOL_NAME = "legion";
67730
67725
  function legionToolDefinition() {
67731
67726
  return {
@@ -67760,7 +67755,7 @@ import {
67760
67755
  createServer,
67761
67756
  request as httpRequest
67762
67757
  } from "http";
67763
- import { dirname as dirname7 } from "path";
67758
+ import { dirname as dirname8 } from "path";
67764
67759
 
67765
67760
  // hooks/mod-protocol.ts
67766
67761
  var MOD_HEALTH_MARKER = "claude-envoy-mod";
@@ -67982,7 +67977,7 @@ async function privateDirectory(path) {
67982
67977
  }
67983
67978
  }
67984
67979
  async function bind(server, socketPath) {
67985
- await privateDirectory(dirname7(socketPath));
67980
+ await privateDirectory(dirname8(socketPath));
67986
67981
  if (await exists2(socketPath)) {
67987
67982
  if (await probeHealth(socketPath, MOD_PROBE_TIMEOUT_MS)) {
67988
67983
  throw new Error(`another claude-envoy server already serves this session at ${socketPath}`);
@@ -68373,7 +68368,7 @@ function modSession(options) {
68373
68368
  }
68374
68369
 
68375
68370
  // src/replay-state.ts
68376
- import { join as join15 } from "path";
68371
+ import { join as join16 } from "path";
68377
68372
 
68378
68373
  // src/state-file.ts
68379
68374
  import { readFile as readFile8 } from "fs/promises";
@@ -68403,7 +68398,7 @@ var ReplayStateFileSchema = LedgerSnapshotSchema.extend({
68403
68398
  consumer: ConsumerDeliverySnapshotSchema.optional()
68404
68399
  });
68405
68400
  function replayStateFile(stateDirectory, sessionId) {
68406
- return join15(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
68401
+ return join16(stateDirectory, `replay-${encodeURIComponent(sessionId)}.json`);
68407
68402
  }
68408
68403
  async function readReplayState(file) {
68409
68404
  return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no delivery state");
@@ -68435,12 +68430,12 @@ import { basename as basename4 } from "path";
68435
68430
 
68436
68431
  // ../envoy-client/src/process-ancestry.ts
68437
68432
  import { execFileSync } from "child_process";
68438
- import { readFileSync as readFileSync8 } from "fs";
68433
+ import { readFileSync as readFileSync9 } from "fs";
68439
68434
  var MAX_ANCESTORS = 64;
68440
68435
  var PARENT_LOOKUP_MS = 1000;
68441
68436
  function procParentPid(pid) {
68442
68437
  try {
68443
- const stat = readFileSync8(`/proc/${pid}/stat`, "utf8");
68438
+ const stat = readFileSync9(`/proc/${pid}/stat`, "utf8");
68444
68439
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
68445
68440
  return Number.isInteger(parent) ? parent : undefined;
68446
68441
  } catch {
@@ -68482,7 +68477,7 @@ function isAncestor(candidate, pid = process.pid) {
68482
68477
  }
68483
68478
  function procCommand(pid) {
68484
68479
  try {
68485
- return readFileSync8(`/proc/${pid}/comm`, "utf8").trim();
68480
+ return readFileSync9(`/proc/${pid}/comm`, "utf8").trim();
68486
68481
  } catch {
68487
68482
  return;
68488
68483
  }
@@ -68951,7 +68946,7 @@ function createUserTurnRouter(options) {
68951
68946
  }
68952
68947
 
68953
68948
  // src/user-turn-state.ts
68954
- import { join as join16 } from "path";
68949
+ import { join as join17 } from "path";
68955
68950
  var TURNS_DIRECTORY = "turns";
68956
68951
  var HANDLED_ATTEMPTS_MAX = 1000;
68957
68952
  var DELIVERED_ROWS_MAX = 1000;
@@ -68961,7 +68956,7 @@ var UserTurnStateSchema = object({
68961
68956
  rows: array(DeliveredRowSchema).default([])
68962
68957
  });
68963
68958
  function userTurnStateFile(stateDirectory, sessionId) {
68964
- return join16(stateDirectory, TURNS_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
68959
+ return join17(stateDirectory, TURNS_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
68965
68960
  }
68966
68961
  async function readUserTurnState(file) {
68967
68962
  return await readStateFile(file, UserTurnStateSchema, { handled: [], rows: [] }, "holds no record of this session's turns");
@@ -68999,7 +68994,7 @@ function userTurnState(file, restored) {
68999
68994
  };
69000
68995
  }
69001
68996
  async function pruneStaleSessionTurns(stateDirectory) {
69002
- await pruneStateDirectory(join16(stateDirectory, TURNS_DIRECTORY), writtenLongAgo);
68997
+ await pruneStateDirectory(join17(stateDirectory, TURNS_DIRECTORY), writtenLongAgo);
69003
68998
  }
69004
68999
 
69005
69000
  // src/envoy-channel-server.ts
@@ -70733,10 +70728,10 @@ function startCodexAgentStream(options) {
70733
70728
  // src/codex/codex-cli.ts
70734
70729
  import { spawn } from "child_process";
70735
70730
  import { randomBytes as randomBytes2 } from "crypto";
70736
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
70737
- import { join as join17 } from "path";
70731
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
70732
+ import { join as join18 } from "path";
70738
70733
  var QUEUE_TIMEOUT_MS = 30000;
70739
- function codexProcessEnv(pid, fallback, read = (path) => readFileSync9(path, "utf8")) {
70734
+ function codexProcessEnv(pid, fallback, read = (path) => readFileSync10(path, "utf8")) {
70740
70735
  let raw;
70741
70736
  try {
70742
70737
  raw = read(`/proc/${pid}/environ`);
@@ -70803,7 +70798,7 @@ function fitArgument(text, spillDirectory) {
70803
70798
  throw new Error(`the message is ${Buffer.byteLength(text)} bytes, over what codex queue takes`);
70804
70799
  }
70805
70800
  mkdirSync4(spillDirectory, { mode: 448, recursive: true });
70806
- const file = join17(spillDirectory, `${Date.now()}-${randomBytes2(4).toString("hex")}.txt`);
70801
+ const file = join18(spillDirectory, `${Date.now()}-${randomBytes2(4).toString("hex")}.txt`);
70807
70802
  writeFileSync5(file, text, { mode: 384 });
70808
70803
  return `${text.slice(0, QUEUE_HEAD_CHARS)}
70809
70804
 
@@ -70929,10 +70924,10 @@ function askSideQuestion(command, threadId, question, timeoutMs = SIDE_QUESTION_
70929
70924
  // src/codex/codex-inbox.ts
70930
70925
  import { randomBytes as randomBytes3 } from "crypto";
70931
70926
  import { mkdir as mkdir4, readdir as readdir5, readFile as readFile9, rename as rename4, rm as rm6, writeFile as writeFile2 } from "fs/promises";
70932
- import { join as join18 } from "path";
70927
+ import { join as join19 } from "path";
70933
70928
  var TAKEN_DIRECTORY = { hook: "taken", server: "queued" };
70934
70929
  function codexInboxDirectory(stateDirectory, sessionId) {
70935
- return join18(stateDirectory, "codex-inbox", encodeURIComponent(sessionId));
70930
+ return join19(stateDirectory, "codex-inbox", encodeURIComponent(sessionId));
70936
70931
  }
70937
70932
  var lastOrder = 0;
70938
70933
  function inboxItemName() {
@@ -70941,17 +70936,17 @@ function inboxItemName() {
70941
70936
  return `${String(order).padStart(15, "0")}-${randomBytes3(4).toString("hex")}.json`;
70942
70937
  }
70943
70938
  async function putInbox(directory, item, name = inboxItemName()) {
70944
- const waiting = join18(directory, "waiting");
70939
+ const waiting = join19(directory, "waiting");
70945
70940
  await mkdir4(waiting, { recursive: true, mode: 448 });
70946
- const temporary = join18(directory, `.${name}.tmp`);
70941
+ const temporary = join19(directory, `.${name}.tmp`);
70947
70942
  await writeFile2(temporary, JSON.stringify(item), { mode: 384 });
70948
- await rename4(temporary, join18(waiting, name));
70943
+ await rename4(temporary, join19(waiting, name));
70949
70944
  return name;
70950
70945
  }
70951
70946
  async function takenBy(directory, name) {
70952
70947
  for (const taker of ["hook", "server"]) {
70953
70948
  try {
70954
- await readFile9(join18(directory, TAKEN_DIRECTORY[taker], name));
70949
+ await readFile9(join19(directory, TAKEN_DIRECTORY[taker], name));
70955
70950
  return taker;
70956
70951
  } catch {}
70957
70952
  }
@@ -70959,14 +70954,14 @@ async function takenBy(directory, name) {
70959
70954
  }
70960
70955
  async function withdrawWaiting(directory, name) {
70961
70956
  try {
70962
- await rm6(join18(directory, "waiting", name));
70957
+ await rm6(join19(directory, "waiting", name));
70963
70958
  return true;
70964
70959
  } catch {
70965
70960
  return false;
70966
70961
  }
70967
70962
  }
70968
70963
  async function discardWaiting(directory, keep = () => false) {
70969
- const waiting = join18(directory, "waiting");
70964
+ const waiting = join19(directory, "waiting");
70970
70965
  let names;
70971
70966
  try {
70972
70967
  names = await readdir5(waiting);
@@ -70978,7 +70973,7 @@ async function discardWaiting(directory, keep = () => false) {
70978
70973
  if (!name.endsWith(".json") || keep(name))
70979
70974
  continue;
70980
70975
  try {
70981
- await rm6(join18(waiting, name));
70976
+ await rm6(join19(waiting, name));
70982
70977
  removed++;
70983
70978
  } catch {}
70984
70979
  }
@@ -70986,7 +70981,7 @@ async function discardWaiting(directory, keep = () => false) {
70986
70981
  }
70987
70982
  var HOOK_CONTEXT_MAX_BYTES = 8000;
70988
70983
  async function takeInbox(directory, taker, maxContextBytes) {
70989
- const waiting = join18(directory, "waiting");
70984
+ const waiting = join19(directory, "waiting");
70990
70985
  let names;
70991
70986
  try {
70992
70987
  names = (await readdir5(waiting)).filter((name) => name.endsWith(".json")).sort();
@@ -70995,14 +70990,14 @@ async function takeInbox(directory, taker, maxContextBytes) {
70995
70990
  }
70996
70991
  if (names.length === 0)
70997
70992
  return [];
70998
- const destination = join18(directory, TAKEN_DIRECTORY[taker]);
70993
+ const destination = join19(directory, TAKEN_DIRECTORY[taker]);
70999
70994
  await mkdir4(destination, { recursive: true, mode: 448 });
71000
70995
  const taken = [];
71001
70996
  for (const name of names) {
71002
70997
  if (maxContextBytes !== undefined) {
71003
70998
  let waitingItem;
71004
70999
  try {
71005
- waitingItem = JSON.parse(await readFile9(join18(waiting, name), "utf8"));
71000
+ waitingItem = JSON.parse(await readFile9(join19(waiting, name), "utf8"));
71006
71001
  } catch {
71007
71002
  continue;
71008
71003
  }
@@ -71013,12 +71008,12 @@ async function takeInbox(directory, taker, maxContextBytes) {
71013
71008
  break;
71014
71009
  }
71015
71010
  try {
71016
- await rename4(join18(waiting, name), join18(destination, name));
71011
+ await rename4(join19(waiting, name), join19(destination, name));
71017
71012
  } catch {
71018
71013
  continue;
71019
71014
  }
71020
71015
  try {
71021
- const parsed = JSON.parse(await readFile9(join18(destination, name), "utf8"));
71016
+ const parsed = JSON.parse(await readFile9(join19(destination, name), "utf8"));
71022
71017
  if (typeof parsed === "object" && parsed !== null && typeof parsed.content === "string") {
71023
71018
  taken.push({ item: parsed, name });
71024
71019
  }
@@ -71176,14 +71171,14 @@ function createCodexDelivery(options) {
71176
71171
 
71177
71172
  // src/codex/codex-owner.ts
71178
71173
  import { link as link2, mkdir as mkdir6, readdir as readdir6, readFile as readFile11, rm as rm7, stat as stat7, writeFile as writeFile4 } from "fs/promises";
71179
- import { join as join20 } from "path";
71174
+ import { join as join21 } from "path";
71180
71175
 
71181
71176
  // src/codex/codex-session-record.ts
71182
71177
  import { spawnSync } from "child_process";
71183
- import { readFileSync as readFileSync10, readlinkSync as readlinkSync2, unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
71178
+ import { readFileSync as readFileSync11, readlinkSync as readlinkSync2, unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
71184
71179
  import { mkdir as mkdir5, readFile as readFile10, rename as rename5, utimes as utimes3, writeFile as writeFile3 } from "fs/promises";
71185
71180
  import { homedir as homedir3 } from "os";
71186
- import { basename as basename5, dirname as dirname8, join as join19 } from "path";
71181
+ import { basename as basename5, dirname as dirname9, join as join20 } from "path";
71187
71182
  var CodexSessionRecord = object({
71188
71183
  session_id: string2().min(1),
71189
71184
  transcript_path: string2().nullable(),
@@ -71194,14 +71189,14 @@ var CodexSessionRecord = object({
71194
71189
  codex_started: string2().nullable().default(null)
71195
71190
  });
71196
71191
  function codexSessionRecordFile(stateDirectory, pid) {
71197
- return join19(stateDirectory, "codex-sessions", `${pid}.json`);
71192
+ return join20(stateDirectory, "codex-sessions", `${pid}.json`);
71198
71193
  }
71199
71194
  function codexEndedFile(stateDirectory, pid, sessionId) {
71200
- return join19(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`);
71195
+ return join20(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`);
71201
71196
  }
71202
71197
  async function markSessionEnded(stateDirectory, pid, sessionId) {
71203
71198
  const marker = codexEndedFile(stateDirectory, pid, sessionId);
71204
- await mkdir5(dirname8(marker), { mode: 448, recursive: true });
71199
+ await mkdir5(dirname9(marker), { mode: 448, recursive: true });
71205
71200
  await writeFile3(marker, "", { mode: 384 });
71206
71201
  const now = new Date;
71207
71202
  await utimes3(codexSessionRecordFile(stateDirectory, pid), now, now);
@@ -71227,7 +71222,7 @@ async function sessionEnded(file) {
71227
71222
  }
71228
71223
  }
71229
71224
  async function writeCodexSessionRecord(file, value) {
71230
- await mkdir5(dirname8(file), { recursive: true, mode: 448 });
71225
+ await mkdir5(dirname9(file), { recursive: true, mode: 448 });
71231
71226
  const temporary = `${file}.${process.pid}.tmp`;
71232
71227
  await writeFile3(temporary, JSON.stringify(value), { mode: 384 });
71233
71228
  await rename5(temporary, file);
@@ -71242,17 +71237,17 @@ async function readCodexSessionRecord(file) {
71242
71237
  }
71243
71238
  function codexHome(env) {
71244
71239
  const set = env["CODEX_HOME"];
71245
- return set !== undefined && set !== "" ? set : join19(env["HOME"] || homedir3(), ".codex");
71240
+ return set !== undefined && set !== "" ? set : join20(env["HOME"] || homedir3(), ".codex");
71246
71241
  }
71247
71242
  function codexPluginDataDirectory(pluginRoot) {
71248
71243
  const version = pluginRoot;
71249
- const plugin = dirname8(version);
71250
- const marketplace = dirname8(plugin);
71251
- const cache = dirname8(marketplace);
71252
- const plugins = dirname8(cache);
71244
+ const plugin = dirname9(version);
71245
+ const marketplace = dirname9(plugin);
71246
+ const cache = dirname9(marketplace);
71247
+ const plugins = dirname9(cache);
71253
71248
  if (basename5(cache) !== "cache" || basename5(plugins) !== "plugins")
71254
71249
  return;
71255
- return join19(plugins, "data", `${basename5(plugin)}-${basename5(marketplace)}`);
71250
+ return join20(plugins, "data", `${basename5(plugin)}-${basename5(marketplace)}`);
71256
71251
  }
71257
71252
  var MAX_ANCESTORS2 = 16;
71258
71253
  function codexProcessId(readComm = procComm, readParent = procParent) {
@@ -71266,14 +71261,14 @@ function codexProcessId(readComm = procComm, readParent = procParent) {
71266
71261
  }
71267
71262
  function procComm(pid) {
71268
71263
  try {
71269
- return readFileSync10(`/proc/${pid}/comm`, "utf8").trim();
71264
+ return readFileSync11(`/proc/${pid}/comm`, "utf8").trim();
71270
71265
  } catch {
71271
71266
  return;
71272
71267
  }
71273
71268
  }
71274
71269
  function procParent(pid) {
71275
71270
  try {
71276
- const stat = readFileSync10(`/proc/${pid}/stat`, "utf8");
71271
+ const stat = readFileSync11(`/proc/${pid}/stat`, "utf8");
71277
71272
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
71278
71273
  return Number.isInteger(parent) ? parent : undefined;
71279
71274
  } catch {
@@ -71287,7 +71282,7 @@ var PS_OPTIONS = {
71287
71282
  };
71288
71283
  function procStarted(pid) {
71289
71284
  try {
71290
- const stat = readFileSync10(`/proc/${pid}/stat`, "utf8");
71285
+ const stat = readFileSync11(`/proc/${pid}/stat`, "utf8");
71291
71286
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
71292
71287
  } catch {
71293
71288
  return;
@@ -71308,7 +71303,7 @@ function recordOfProcess(record, pid) {
71308
71303
  function sharedAppServer(pid) {
71309
71304
  let argv;
71310
71305
  try {
71311
- argv = readFileSync10(`/proc/${pid}/cmdline`, "utf8").split("\x00");
71306
+ argv = readFileSync11(`/proc/${pid}/cmdline`, "utf8").split("\x00");
71312
71307
  } catch {
71313
71308
  const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS);
71314
71309
  if (ps.status !== 0)
@@ -71354,11 +71349,11 @@ function codexSubcommand(args) {
71354
71349
  }
71355
71350
  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.";
71356
71351
  async function pruneCodexSessionRecords(stateDirectory) {
71357
- await pruneStateDirectory(join19(stateDirectory, "codex-sessions"), (file) => {
71352
+ await pruneStateDirectory(join20(stateDirectory, "codex-sessions"), (file) => {
71358
71353
  const match = /^(\d+)\.(?:json|.+\.ended)$/.exec(basename5(file));
71359
71354
  return match !== null && !processExists(Number(match[1]));
71360
71355
  });
71361
- await pruneStateDirectory(join19(stateDirectory, "codex-servers"), (file) => {
71356
+ await pruneStateDirectory(join20(stateDirectory, "codex-servers"), (file) => {
71362
71357
  const name = basename5(file);
71363
71358
  return /^\d+$/.test(name) && !processExists(Number(name));
71364
71359
  });
@@ -71373,7 +71368,7 @@ function codexExecutable(pid) {
71373
71368
 
71374
71369
  // src/codex/codex-owner.ts
71375
71370
  function codexServersDirectory(stateDirectory, codexPid) {
71376
- return join20(stateDirectory, "codex-servers", String(codexPid));
71371
+ return join21(stateDirectory, "codex-servers", String(codexPid));
71377
71372
  }
71378
71373
  var ENTRY_NAME = /^(\d+)\.json$/;
71379
71374
  var TEMPORARY_NAME = /^\.\d+\.\d+\.tmp$/;
@@ -71382,13 +71377,13 @@ function entryName(entry) {
71382
71377
  }
71383
71378
  async function registerServer(directory, pid, started, list = (path) => readdir6(path)) {
71384
71379
  await mkdir6(directory, { mode: 448, recursive: true });
71385
- const temporary = join20(directory, `.${pid}.${process.hrtime.bigint()}.tmp`);
71380
+ const temporary = join21(directory, `.${pid}.${process.hrtime.bigint()}.tmp`);
71386
71381
  await writeFile4(temporary, JSON.stringify({ pid, started }), { mode: 384 });
71387
71382
  try {
71388
71383
  let seq = Math.max(0, ...numbered(await list(directory)).map(({ seq: taken }) => taken)) + 1;
71389
71384
  for (;; ) {
71390
71385
  try {
71391
- await place(temporary, join20(directory, entryName({ seq })), pid, started);
71386
+ await place(temporary, join21(directory, entryName({ seq })), pid, started);
71392
71387
  return { pid, seq, started };
71393
71388
  } catch (error) {
71394
71389
  if (error.code !== "EEXIST")
@@ -71416,7 +71411,7 @@ async function place(temporary, target, pid, started) {
71416
71411
  await writeFile4(target, JSON.stringify({ pid, started }), { flag: "wx", mode: 384 });
71417
71412
  }
71418
71413
  async function unregisterServer(directory, self2) {
71419
- const file = join20(directory, entryName(self2));
71414
+ const file = join21(directory, entryName(self2));
71420
71415
  const named = await readFile11(file, "utf8").then(serverOf, () => {
71421
71416
  return;
71422
71417
  });
@@ -71480,7 +71475,7 @@ async function readEntries(directory, probe, now = Date.now) {
71480
71475
  for (const name of names.filter((each) => TEMPORARY_NAME.test(each))) {
71481
71476
  let text;
71482
71477
  try {
71483
- text = await readFile11(join20(directory, name), "utf8");
71478
+ text = await readFile11(join21(directory, name), "utf8");
71484
71479
  } catch {
71485
71480
  publishing = true;
71486
71481
  break;
@@ -71496,13 +71491,13 @@ async function readEntries(directory, probe, now = Date.now) {
71496
71491
  for (const { name, seq } of numbered(names)) {
71497
71492
  let text;
71498
71493
  try {
71499
- text = await readFile11(join20(directory, name), "utf8");
71494
+ text = await readFile11(join21(directory, name), "utf8");
71500
71495
  } catch {
71501
71496
  continue;
71502
71497
  }
71503
71498
  const server = serverOf(text);
71504
71499
  if (server === undefined) {
71505
- const written = await stat7(join20(directory, name)).then((info) => info.mtimeMs, () => {
71500
+ const written = await stat7(join21(directory, name)).then((info) => info.mtimeMs, () => {
71506
71501
  return;
71507
71502
  });
71508
71503
  if (written === undefined)
@@ -71530,7 +71525,7 @@ async function currentOwner(directory, probe = SYSTEM_PROBE) {
71530
71525
  const text = seen.held.get(seq);
71531
71526
  if (text === undefined)
71532
71527
  return;
71533
- const now = await readFile11(join20(directory, entryName({ seq })), "utf8").catch(() => {
71528
+ const now = await readFile11(join21(directory, entryName({ seq })), "utf8").catch(() => {
71534
71529
  return;
71535
71530
  });
71536
71531
  if (now !== text)
@@ -71591,7 +71586,7 @@ async function stillOwner(directory, self2, probe = SYSTEM_PROBE) {
71591
71586
  // src/codex/codex-transcript.ts
71592
71587
  import { watch } from "fs";
71593
71588
  import { open as open4 } from "fs/promises";
71594
- import { join as join21 } from "path";
71589
+ import { join as join22 } from "path";
71595
71590
  function record3(value) {
71596
71591
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
71597
71592
  }
@@ -71861,7 +71856,7 @@ async function findTranscript(home, threadId) {
71861
71856
  const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`);
71862
71857
  const found = [];
71863
71858
  try {
71864
- for await (const file of glob.scan({ absolute: true, cwd: join21(home, "sessions") })) {
71859
+ for await (const file of glob.scan({ absolute: true, cwd: join22(home, "sessions") })) {
71865
71860
  found.push(file);
71866
71861
  }
71867
71862
  } catch {
@@ -72002,7 +71997,7 @@ function runDispatchCommand(script, args, stdin, options) {
72002
71997
  });
72003
71998
  }
72004
71999
  function stateDirectoryFor(pluginRoot) {
72005
- return configuredValue(process.env["PLUGIN_DATA"]) ?? codexPluginDataDirectory(pluginRoot) ?? join22(configuredValue(process.env["XDG_STATE_HOME"]) ?? join22(homedir4(), ".local", "state"), "claude-envoy", "codex");
72000
+ return configuredValue(process.env["PLUGIN_DATA"]) ?? codexPluginDataDirectory(pluginRoot) ?? join23(configuredValue(process.env["XDG_STATE_HOME"]) ?? join23(homedir4(), ".local", "state"), "claude-envoy", "codex");
72006
72001
  }
72007
72002
  function waitForRecord(file, pid, signal, ended) {
72008
72003
  return new Promise((done) => {
@@ -72040,7 +72035,7 @@ async function runCodexEnvoyServer() {
72040
72035
  const configFile = sessionConfigFile("codex", process.env);
72041
72036
  const warn = (text) => void process.stderr.write(`envoy-channel: ${text}
72042
72037
  `);
72043
- const bundlePath = resolve3(pluginRoot, process.argv[1] ?? "");
72038
+ const bundlePath = resolve4(pluginRoot, process.argv[1] ?? "");
72044
72039
  let record;
72045
72040
  let runtime;
72046
72041
  let notReady = "this session's Envoy side starts at its first prompt";
@@ -72090,7 +72085,7 @@ async function runCodexEnvoyServer() {
72090
72085
  env["DISPATCH_HOST"] = "codex";
72091
72086
  if (configFile.path !== null)
72092
72087
  env["ENVOY_CONFIG_FILE"] = configFile.path;
72093
- const { code, output } = await runDispatchCommand(join22(pluginRoot, "dist", "dispatch.js"), parsed.data.args, parsed.data.stdin ?? "", { cwd: await latestTurnCwd(transcript) ?? own?.cwd ?? current?.cwd ?? homedir4(), env });
72088
+ const { code, output } = await runDispatchCommand(join23(pluginRoot, "dist", "dispatch.js"), parsed.data.args, parsed.data.stdin ?? "", { cwd: await latestTurnCwd(transcript) ?? own?.cwd ?? current?.cwd ?? homedir4(), env });
72094
72089
  return `${output}${output.endsWith(`
72095
72090
  `) || output === "" ? "" : `
72096
72091
  `}[exit ${code}]`;
@@ -72230,7 +72225,7 @@ async function runCodexEnvoyServer() {
72230
72225
  const runningSession = () => record?.session_id ?? bound.session_id;
72231
72226
  const codexDelivery = createCodexDelivery({
72232
72227
  inboxDirectory: (sessionId) => codexInboxDirectory(stateDirectory, sessionId),
72233
- queue: (text) => queueMessage(command(), runningSession(), text, join22(stateDirectory, "codex-long-messages")),
72228
+ queue: (text) => queueMessage(command(), runningSession(), text, join23(stateDirectory, "codex-long-messages")),
72234
72229
  sessionId: runningSession,
72235
72230
  taken: (item) => stream?.delivered(item.content, item.dispatchMessageId),
72236
72231
  warn
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "5.30.0",
3
+ "version": "5.31.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -18,9 +18,6 @@
18
18
  "README.md",
19
19
  "AGENTS.md"
20
20
  ],
21
- "legion": {
22
- "daemonApiVersion": 275
23
- },
24
21
  "repository": {
25
22
  "type": "git",
26
23
  "url": "https://github.com/cybermonklabs/legion"
@@ -46,5 +43,8 @@
46
43
  "nats": "^2.29.2",
47
44
  "typescript": "^5.3.0",
48
45
  "zod": "4.3.6"
46
+ },
47
+ "legion": {
48
+ "daemonApiVersion": 275
49
49
  }
50
50
  }
package/scripts/build.ts CHANGED
@@ -11,7 +11,8 @@
11
11
  // package. The one mode builds only on the Bun the repo-root `.bun-version`
12
12
  // pins, because bundler output depends on the exact Bun build (LEGION-568):
13
13
  // --out <dir> make <dir>, a new or empty directory outside the repository, a
14
- // runnable copy of the plugin built from this tree.
14
+ // runnable copy of the plugin built from this tree, whose package.json
15
+ // and bundles declare the tree's daemon API contract (`pluginManifest`).
15
16
  //
16
17
  // scripts/build-inputs.txt must name every file this build reads, since
17
18
  // release.yaml's $CLAUDE_ENVOY_VERSION_ARGS covers that list and a build input missing from it is
@@ -21,6 +22,7 @@
21
22
  // scripts it runs) is listed by hand.
22
23
  import { chmod, cp, lstat, mkdir, readdir, readFile, realpath, writeFile } from "node:fs/promises"
23
24
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
25
+ import { daemonContract, type PluginManifest } from "@legion/contracts/daemon-contract"
24
26
  import { thirdPartyNotices } from "../../../scripts/third-party-notices"
25
27
  import { PHASE_HOOK_TOOL_NAME } from "../src/legion-phase-hook"
26
28
 
@@ -31,6 +33,23 @@ const repoRoot = resolve(packageRoot, "..", "..")
31
33
  * itself without needing a real file on disk. */
32
34
  const pinnedBunVersion = (await readFile(join(repoRoot, ".bun-version"), "utf8")).trim()
33
35
 
36
+ /** The package's manifest as the plugin carries it: the committed one with this tree's daemon API
37
+ * contract as `legion.daemonApiVersion` (`daemonContract`), the number the daemon's boot gate
38
+ * holds the installed manifest to. The committed manifest names none; where the package's
39
+ * manifest holds one, as release.yaml's claude_envoy_build writes it before it builds
40
+ * (.github/scripts/release-claude-envoy-version.sh), that one is kept. `--out` writes this as the
41
+ * plugin's package.json, and every bundle inlines it in place of the committed one, so the code a
42
+ * pane runs states the contract its manifest declares. */
43
+ async function pluginManifest(): Promise<PluginManifest> {
44
+ const manifest = JSON.parse(
45
+ await readFile(join(packageRoot, "package.json"), "utf8"),
46
+ ) as PluginManifest
47
+ return {
48
+ ...manifest,
49
+ legion: { ...manifest.legion, daemonApiVersion: daemonContract(manifest, packageRoot) },
50
+ }
51
+ }
52
+
34
53
  /** Output name -> source entrypoint, relative to the package root. `dispatch` is the `dispatch`
35
54
  * CLI that `bin/dispatch` runs, built from the shared library's entry. `session-title-hook` is a
36
55
  * bundle of its own rather than a mode of `session-hook`, because Claude Code blocks the user's
@@ -310,6 +329,9 @@ export async function buildBundles(outdir: string): Promise<string[]> {
310
329
  }
311
330
 
312
331
  async function bundleFromPackageRoot(outdir: string): Promise<string[]> {
332
+ const manifestPath = join(packageRoot, "package.json")
333
+ const manifest = JSON.stringify(await pluginManifest())
334
+ let manifestInlined = false
313
335
  const result = await Bun.build({
314
336
  entrypoints: Object.values(BUNDLE_ENTRYPOINTS).map((entry) => join(packageRoot, entry)),
315
337
  outdir,
@@ -333,11 +355,30 @@ async function bundleFromPackageRoot(outdir: string): Promise<string[]> {
333
355
  sourcemap: "none",
334
356
  naming: "[name].[ext]",
335
357
  metafile: true,
358
+ // A bundle that imports the package's manifest inlines `pluginManifest()` in its place, so it
359
+ // states the contract the committed manifest leaves out; any other manifest loads as it is.
360
+ plugins: [
361
+ {
362
+ name: "plugin-manifest",
363
+ setup(build) {
364
+ build.onLoad({ filter: /[\\/]package\.json$/ }, async ({ path }) => {
365
+ if (path !== manifestPath) {
366
+ return { contents: await readFile(path, "utf8"), loader: "json" }
367
+ }
368
+ manifestInlined = true
369
+ return { contents: manifest, loader: "json" }
370
+ })
371
+ },
372
+ },
373
+ ],
336
374
  })
337
375
  if (!result.success) {
338
376
  throw new AggregateError(result.logs, "bundle build failed")
339
377
  }
340
378
  if (!result.metafile) throw new Error("Bun.build returned no metafile")
379
+ if (!manifestInlined) {
380
+ throw new Error(`no bundle imported ${manifestPath}, so none states this tree's contract`)
381
+ }
341
382
  // The metafile's keys are relative to the working directory, the package root.
342
383
  const inputs = Object.keys(result.metafile.inputs)
343
384
  await writeFile(join(outdir, "THIRD_PARTY_NOTICES"), await thirdPartyNotices(inputs, packageRoot))
@@ -393,12 +434,14 @@ async function outRefusal(out: string): Promise<string | null> {
393
434
 
394
435
  /** `out` as a runnable plugin directory: the package's plugin files, with each `skills/<name>`
395
436
  * link to the repository's skill copied as the files it points at (file modes kept, so
396
- * `bin/dispatch` stays executable), then a fresh `dist/` and `legion/`. */
437
+ * `bin/dispatch` stays executable) and its package.json as `pluginManifest()`, then a fresh
438
+ * `dist/` and `legion/`. */
397
439
  async function buildOut(out: string): Promise<void> {
398
440
  await mkdir(out, { recursive: true })
399
441
  for (const source of PLUGIN_SOURCES) {
400
442
  await cp(join(packageRoot, source), join(out, source), { recursive: true, dereference: true })
401
443
  }
444
+ await writeFile(join(out, "package.json"), `${JSON.stringify(await pluginManifest(), null, 2)}\n`)
402
445
  await buildBundles(join(out, "dist"))
403
446
  await buildLegionPlugin(join(out, "legion"))
404
447
  }
@@ -2,6 +2,7 @@ import { readdir, stat } from "node:fs/promises"
2
2
  import { join } from "node:path"
3
3
  import { setTimeout as delay } from "node:timers/promises"
4
4
  import { SESSION_LIVE_WINDOW_MS } from "@legion/contracts"
5
+ import { daemonContract } from "@legion/contracts/daemon-contract"
5
6
  import { messageFor } from "@legion/envoy-client/errors"
6
7
  import { readSecretFile } from "@legion/envoy-client/secret-file"
7
8
  import type { EnvoyClient } from "@legion/envoy-client/transport"
@@ -9,7 +10,7 @@ import { claimFirstTurnBoundMs } from "@legion/pi-shared/claim-first-turn-bound"
9
10
  import { createLegionDaemonClient, type LegionDaemonClient } from "@legion/pi-shared/daemon-client"
10
11
  import { bootLegionClaim, type LegionClaimBoot } from "@legion/pi-shared/legion-claim-core"
11
12
  import type { ClaimCapability } from "@legion/pi-shared/legion-phase-ops"
12
- import { legion } from "../package.json" with { type: "json" }
13
+ import pkg from "../package.json" with { type: "json" }
13
14
  import { configuredValue } from "./claude-session"
14
15
  import type { ChannelSession } from "./envoy-channel-server"
15
16
  import { paneReminderLog } from "./legion-phase-hook"
@@ -21,6 +22,12 @@ import { paneReminderLog } from "./legion-phase-hook"
21
22
  * its boot token (`LEGION_BOOT_TOKEN_FILE`) and its address (`LEGION_DAEMON_URL`).
22
23
  */
23
24
 
25
+ /** The daemon API contract this build speaks, read once as the module loads (`daemonContract`):
26
+ * the manifest of the module this process loaded names it once a pack or `scripts/build.ts --out`
27
+ * has written it, and a checkout's own fixtures decide it for code run from the checkout. A
28
+ * bundle installed with neither refuses to load here rather than speak a number it guessed. */
29
+ const PLUGIN_CONTRACT = daemonContract(pkg, import.meta.dir)
30
+
24
31
  /** What the daemon put on a Legion pane: its address, the boot token the registration spends, the
25
32
  * claim's own Claude Code directory (`CLAUDE_CONFIG_DIR`), which holds the transcript, and whether
26
33
  * its pod's launcher keeps that transcript in the session table (`LEGION_CLAUDE_SESSION_ID`, which
@@ -62,13 +69,12 @@ export async function legionPane(env: NodeJS.ProcessEnv): Promise<LegionPane | u
62
69
  }
63
70
 
64
71
  /**
65
- * The pane's client for the daemon. It states this build's own `legion.daemonApiVersion` on
66
- * every request, read from the manifest of the module this process loaded, as the claim's
67
- * registration below reads it: the daemon serves each answer in the shape the contract the
68
- * caller states describes, so a pane an older or newer daemon answers still reads its answers.
72
+ * The pane's client for the daemon. It states this build's own contract on every request, as the
73
+ * claim's registration below states it: the daemon serves each answer in the shape the contract
74
+ * the caller states describes, so a pane an older or newer daemon answers still reads its answers.
69
75
  */
70
76
  export function paneDaemonClient(daemonUrl: string): LegionDaemonClient {
71
- return createLegionDaemonClient(daemonUrl, { pluginContract: legion.daemonApiVersion })
77
+ return createLegionDaemonClient(daemonUrl, { pluginContract: PLUGIN_CONTRACT })
72
78
  }
73
79
 
74
80
  /** Writes one line to the pane's log, the server's stderr. */
@@ -200,7 +206,7 @@ export interface LegionClaim {
200
206
  * Boots the pane's claim in the background of the server (`bootLegionClaim`): waits for the
201
207
  * transcript, and in a pod whose launcher keeps it (`launcherSaves`) for the launcher's first save
202
208
  * of it too, registers with it as the session file (`agentId` is the session id,
203
- * `pluginContract` this package's `legion.daemonApiVersion`), sends `claims/ready` with no
209
+ * `pluginContract` this build's own contract), sends `claims/ready` with no
204
210
  * capability report, again each time the heartbeat regains the role, and claims the claim
205
211
  * token's Envoy role soft last of all — at this session's first turn (`onFirstTurn`) or at the
206
212
  * bound this pane's environment names, whichever comes first — recording it with the channel
@@ -275,7 +281,7 @@ export function startLegionClaim(deps: {
275
281
  sessionId: sessionID,
276
282
  ompSessionFile: transcript,
277
283
  agentId: sessionID,
278
- pluginContract: legion.daemonApiVersion,
284
+ pluginContract: PLUGIN_CONTRACT,
279
285
  },
280
286
  setCapability: (registered) => {
281
287
  capability = registered
@@ -18,8 +18,9 @@ import pkg from "../package.json" with { type: "json" }
18
18
  * process loaded, never a path read anywhere else. In a pod a Claude Code role installs no plugin
19
19
  * (the daemon's `NoPluginInstall`) and loads its image's own claude-envoy, so a relaunch keeps
20
20
  * this build and only the update round over the pod brings another. It is an Oh My Pi role's
21
- * relaunch that installs its plugin pair fresh under the role's state home. */
22
- const BUILD = pluginBuildOf(pkg)
21
+ * relaunch that installs its plugin pair fresh under the role's state home. Its contract is
22
+ * `daemonContract`'s, read as the module loads. */
23
+ const BUILD = pluginBuildOf(pkg, import.meta.dir)
23
24
 
24
25
  /** The tool's name: Claude Code shows it as `mcp__legion__legion`, under the pane's one server. */
25
26
  export const LEGION_TOOL_NAME = "legion"