@sjawhar/claude-envoy 1.28.0 → 1.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.omp-plugin/plugin.json +1 -1
- package/AGENTS.md +8 -4
- package/dist/envoy-channel.js +311 -248
- package/package.json +1 -1
- package/skills/envoy/SKILL.md +1 -1
- package/skills/envoy/references/legion.md +1 -1
- package/src/envoy-channel-server.ts +27 -0
- package/src/legion-claim.ts +69 -32
- package/src/legion-phase-hook.ts +15 -0
package/.omp-plugin/plugin.json
CHANGED
package/AGENTS.md
CHANGED
|
@@ -134,7 +134,7 @@ Dispatch asks stay on Dispatch.
|
|
|
134
134
|
| Manual `/clear` smoke | `scripts/smoke-clear-rebind.sh` | Real `/clear` against the live listener with the build in `CLAUDE_PLUGIN_DIR` (default: a `--out` build of this tree in the smoke's scratch directory); checks the registry entry moves to the new id without the old direct subject. Sends no prompt to the model; excluded from CI. |
|
|
135
135
|
| Manual session-title smoke | `scripts/smoke-session-title.sh` | Real nats-server, a listener built from this tree, and the `dist/` of its own `--out` build of this tree for both the hook and the channel server: a chosen name registers, a rename replaces it, taking the name away restores the folder-and-short-id fallback, and the `dispatch` command's stamp carries the same name, each read back through the listener's `GET /v1/sessions`; the base revision's committed bundle is the negative control. Claude Code is not installed in an issue pod's image, though it runs there from `bunx --package @anthropic-ai/claude-code@<version> claude`, as `scripts/e2e/envoy-session-delivery.sh` runs it; this smoke writes the two hook payloads to their documented shape instead. Excluded from CI. |
|
|
136
136
|
| NATS stall test | `tests/envoy-channel-stall.test.ts`, `../envoy-client/test/stall-proxy.ts`, `../envoy-client/test/envoy-stack.ts`, `../envoy-client/test/stall-scenario.ts` | Runs only with `LEGION_E2E_ENVOY_STACK=1` (CI's `envoy-session-stall` job), and needs `go` on `PATH` to build natsd and the listener from `packages/envoy`: with the gate set, a missing `go` or a failed build fails it rather than skipping it. The real channel server process registers against that listener (its row shows `plugin` `@sjawhar/claude-envoy` and `plugin_version` `source`), which answers `consumer`, and the proxy freezes its NATS path. Within 60 s the connection nats.js dials in place of the frozen one subscribes the relay subject again (natsd's `/connz`), the session registers a new epoch (its `envoy_sessions` entry), and the message sent during the freeze and one sent after it are each handed over once, neither as a replay: the freeze and what it checks are `runFreezeScenario`, which pi-envoy's stall row runs too. |
|
|
137
|
-
| Legion phase worker on Claude Code | `src/legion-claim.ts`, `src/legion-tool.ts`, `src/legion-inbox.ts`, `src/legion-phase-hook.ts` | Active only when `legion claude-bridge` launched the pane (`LEGION_BOOT_TOKEN_FILE`, `LEGION_DAEMON_URL`, `CLAUDE_CONFIG_DIR` set). The claim waits for the session transcript, then boots through the claim boot `@sjawhar/pi-legion` shares (`bootLegionClaim`, `@legion/pi-shared/legion-claim-core`): registers with the daemon, claims the issue's Envoy role soft
|
|
137
|
+
| Legion phase worker on Claude Code | `src/legion-claim.ts`, `src/legion-tool.ts`, `src/legion-inbox.ts`, `src/legion-phase-hook.ts` | Active only when `legion claude-bridge` launched the pane (`LEGION_BOOT_TOKEN_FILE`, `LEGION_DAEMON_URL`, `CLAUDE_CONFIG_DIR` set). The claim waits for the session transcript, then boots through the claim boot `@sjawhar/pi-legion` shares (`bootLegionClaim`, `@legion/pi-shared/legion-claim-core`): registers with the daemon, calls ready, again on every `onRoleRegained`, and claims the issue's Envoy role soft last of all — at this session's first turn or at the bound (`claimFirstTurnBoundMs`, 30 s, `LEGION_CLAIM_FIRST_TURN_BOUND_MS`), whichever comes first, so a message the listener kept for the role arrives inside a turn that is already running rather than ahead of the daemon's task (INFRA-1573). The first turn is the phase hook's `UserPromptSubmit`, this process's only sight of one: the endpoint fires it before its phase gate, for every prompt and whatever claim exists, and the server holds the boot's first-turn signal in one slot (`reportFirstTurn` in `src/envoy-channel-server.ts`), filled the moment `claims/register` answers — so the bridge's seeding `/rename`, which runs before any claim exists, finds it empty and signals nothing, a prompt that arrives while the boot's `claims/ready` is still being retried is counted, and a later prompt runs a step that has already run. The `legion` MCP tool is the phase ops `@sjawhar/pi-legion`'s tool serves too (`@legion/pi-shared/legion-phase-ops`: one schema, one executor, and the shared description template with its `read_record` and `request_backward_move` sentences, naming `mcp__legion__envoy_publish`). `src/legion-phase-hook.ts` is the endless phase reminder's Claude Code host (the section below). With `LEGION_CLAUDE_INBOX` set, deliveries go to the bridge's socket instead of the mod's `$.session.append`. `package.json` `legion.daemonApiVersion` is pinned by `tests/daemon-api-version.test.ts`. |
|
|
138
138
|
| Generated Legion plugin | `legion/`, `scripts/build.ts` | Never edit by hand, and never committed (convention below): `scripts/build.ts` stages pi-legion's skills, converts `packages/pi-legion/agents` (tool names mapped to Claude Code's, `glob`/`grep`/`todo` dropped) and writes the phase reminder's five hook entries (`LEGION_HOOKS` → `legion/hooks/hooks.json`, the section below). `scripts/verify-build.sh` builds the tree twice and fails when the two builds differ, so the release publishes what the source builds to; `tests/dist-fresh.test.ts`, `tests/legion-plugin-fresh.test.ts` and `tests/build-out.test.ts` build fresh and read no file of the package. `tests/legion-pane-mcp.test.ts` runs a Legion pane's server end to end against stand-ins. |
|
|
139
139
|
| The phase reminder on the real Claude Code binary | `tests/legion-phase-hook-claude.test.ts` | The one check that Claude Code arms the generated `legion/hooks/hooks.json` entries at all: it runs the real binary under Legion's own agent command (`claudelaunch.Argv`, `--debug` added for the log it reads), with a fresh `scripts/build.ts --out` build of this tree — its generated `legion/` tree, and its `dist/envoy-channel.js` as the `legion` MCP server — against stand-ins for the Anthropic API, the daemon, the listener and NATS. `LEGION_TEST_CLAUDE` names the binary — in a worker pod, the one installed from `packages/daemon/docker/claude-code/package-lock.json`, at `node_modules/@anthropic-ai/claude-code-linux-x64/claude` (the `node_modules/.bin/claude` symlink is a `.exe` shim that does not exec on Linux): `cd packages/claude-envoy && LEGION_TEST_CLAUDE=<that path> bun test tests/legion-phase-hook-claude.test.ts`. A run without it skips the file, and nothing in CI installs the binary. |
|
|
140
140
|
|
|
@@ -432,9 +432,13 @@ above says how to run it).
|
|
|
432
432
|
more would cost a `--resume` or a channel-server restart inside the live window its role for
|
|
433
433
|
the life of the process. The Legion pane's claim waits the same refusal out rather than
|
|
434
434
|
stopping the pane, asking every `ROLE_CLAIM_RETRY_MS` (10 s) for the live window and one
|
|
435
|
-
attempt more
|
|
436
|
-
|
|
437
|
-
|
|
435
|
+
attempt more. That wait runs after the pane's `claims/ready`, since the role is claimed last,
|
|
436
|
+
at the session's first turn or at the bound, so the daemon's registration deadline
|
|
437
|
+
(`worker_boot_timeout_seconds` × `worker_boot_registration_deadline_intervals` from the
|
|
438
|
+
registration) is already met when the first attempt goes out and nothing outside the pane is
|
|
439
|
+
counting the wait; what bounds it is the listener's own live window, after which the standing
|
|
440
|
+
claim of the process this pane replaced is granted to nobody. It throws only on a refusal
|
|
441
|
+
naming a different session. The
|
|
438
442
|
lookup's rule and the record's are the client contract's own,
|
|
439
443
|
`roleHeldBy` and `mayActOnRoleRecord` in `@legion/envoy-client/transport`, which
|
|
440
444
|
`packages/pi-envoy` calls too and which read an empty instance id as none, the lookup leaving
|
package/dist/envoy-channel.js
CHANGED
|
@@ -55391,7 +55391,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
|
|
|
55391
55391
|
|
|
55392
55392
|
// package.json
|
|
55393
55393
|
var name = "@sjawhar/claude-envoy";
|
|
55394
|
-
var version2 = "1.28.
|
|
55394
|
+
var version2 = "1.28.1";
|
|
55395
55395
|
var legion = {
|
|
55396
55396
|
daemonApiVersion: 59
|
|
55397
55397
|
};
|
|
@@ -56588,9 +56588,59 @@ function installedPluginVersion(bundlePath) {
|
|
|
56588
56588
|
|
|
56589
56589
|
// src/legion-claim.ts
|
|
56590
56590
|
import { readdir as readdir2, stat as stat2 } from "fs/promises";
|
|
56591
|
-
import { join as
|
|
56591
|
+
import { join as join9 } from "path";
|
|
56592
56592
|
import { setTimeout as delay } from "timers/promises";
|
|
56593
56593
|
|
|
56594
|
+
// ../pi-shared/src/stall-limits.ts
|
|
56595
|
+
var DEFAULT_STALL_LIMITS = {
|
|
56596
|
+
reminderMs: 300000,
|
|
56597
|
+
waitingMs: 900000,
|
|
56598
|
+
resumeMs: 120000,
|
|
56599
|
+
architectAfter: 3,
|
|
56600
|
+
callGraceMs: 300000,
|
|
56601
|
+
callBoundMs: 3600000,
|
|
56602
|
+
stepMs: 120000
|
|
56603
|
+
};
|
|
56604
|
+
var LONG_CALL_BOUND_MS = 14400000;
|
|
56605
|
+
var LONG_CALL_BOUND_ROLES = [
|
|
56606
|
+
"implementer",
|
|
56607
|
+
"reviewer"
|
|
56608
|
+
];
|
|
56609
|
+
function defaultCallBoundMs(role) {
|
|
56610
|
+
return role !== undefined && LONG_CALL_BOUND_ROLES.includes(role) ? LONG_CALL_BOUND_MS : DEFAULT_STALL_LIMITS.callBoundMs;
|
|
56611
|
+
}
|
|
56612
|
+
function integerSetting(env, log, name, fallback, least) {
|
|
56613
|
+
const raw = env[name];
|
|
56614
|
+
if (raw === undefined)
|
|
56615
|
+
return fallback;
|
|
56616
|
+
const value = raw.trim() === "" ? Number.NaN : Number(raw);
|
|
56617
|
+
if (!Number.isInteger(value) || value < least) {
|
|
56618
|
+
log.warn(`legion: ${name} is not an integer of ${least} or more; using ${fallback}`, {
|
|
56619
|
+
value: raw
|
|
56620
|
+
});
|
|
56621
|
+
return fallback;
|
|
56622
|
+
}
|
|
56623
|
+
return value;
|
|
56624
|
+
}
|
|
56625
|
+
function stallLimits(env, log, role) {
|
|
56626
|
+
return {
|
|
56627
|
+
reminderMs: integerSetting(env, log, "LEGION_STALL_REMINDER_MS", DEFAULT_STALL_LIMITS.reminderMs, 0),
|
|
56628
|
+
waitingMs: integerSetting(env, log, "LEGION_STALL_WAITING_MS", DEFAULT_STALL_LIMITS.waitingMs, 0),
|
|
56629
|
+
resumeMs: integerSetting(env, log, "LEGION_STALL_RESUME_MS", DEFAULT_STALL_LIMITS.resumeMs, 0),
|
|
56630
|
+
architectAfter: integerSetting(env, log, "LEGION_STALL_ARCHITECT_AFTER", DEFAULT_STALL_LIMITS.architectAfter, 2),
|
|
56631
|
+
callGraceMs: integerSetting(env, log, "LEGION_STALL_CALL_GRACE_MS", DEFAULT_STALL_LIMITS.callGraceMs, 0),
|
|
56632
|
+
callBoundMs: integerSetting(env, log, "LEGION_STALL_CALL_BOUND_MS", defaultCallBoundMs(role), 0),
|
|
56633
|
+
stepMs: integerSetting(env, log, "LEGION_STALL_STEP_MS", DEFAULT_STALL_LIMITS.stepMs, 0)
|
|
56634
|
+
};
|
|
56635
|
+
}
|
|
56636
|
+
|
|
56637
|
+
// ../pi-shared/src/claim-first-turn-bound.ts
|
|
56638
|
+
var DEFAULT_CLAIM_FIRST_TURN_BOUND_MS = 30000;
|
|
56639
|
+
var BOUND_VARIABLE = "LEGION_CLAIM_FIRST_TURN_BOUND_MS";
|
|
56640
|
+
function claimFirstTurnBoundMs(env, log) {
|
|
56641
|
+
return integerSetting(env, log, BOUND_VARIABLE, DEFAULT_CLAIM_FIRST_TURN_BOUND_MS, 0);
|
|
56642
|
+
}
|
|
56643
|
+
|
|
56594
56644
|
// ../pi-shared/src/legion-claim-core.ts
|
|
56595
56645
|
async function bootLegionClaim(host) {
|
|
56596
56646
|
const { daemon } = host;
|
|
@@ -56604,8 +56654,9 @@ async function bootLegionClaim(host) {
|
|
|
56604
56654
|
if (error.status < 400 || error.status >= 500)
|
|
56605
56655
|
throw error;
|
|
56606
56656
|
host.stop();
|
|
56607
|
-
return;
|
|
56657
|
+
return { claimed: Promise.resolve() };
|
|
56608
56658
|
}
|
|
56659
|
+
const firstTurn = listenForFirstTurn(host);
|
|
56609
56660
|
try {
|
|
56610
56661
|
await host.afterRegister?.(claim);
|
|
56611
56662
|
host.setCapability({
|
|
@@ -56618,7 +56669,6 @@ async function bootLegionClaim(host) {
|
|
|
56618
56669
|
secret: claim.secret,
|
|
56619
56670
|
promptAgents: claim.promptAgents
|
|
56620
56671
|
});
|
|
56621
|
-
await host.claimRole(claim.claimToken);
|
|
56622
56672
|
const ready = {
|
|
56623
56673
|
claimToken: claim.claimToken,
|
|
56624
56674
|
sessionId: host.registration.sessionId,
|
|
@@ -56637,217 +56687,58 @@ async function bootLegionClaim(host) {
|
|
|
56637
56687
|
}
|
|
56638
56688
|
});
|
|
56639
56689
|
} catch (error) {
|
|
56640
|
-
host
|
|
56641
|
-
|
|
56642
|
-
}
|
|
56643
|
-
}
|
|
56644
|
-
|
|
56645
|
-
// src/legion-claim.ts
|
|
56646
|
-
function legionPane(env) {
|
|
56647
|
-
const pointer = env["LEGION_BOOT_TOKEN_FILE"];
|
|
56648
|
-
if (pointer === undefined && configuredValue(env["LEGION_BOOT_TOKEN"]) === undefined) {
|
|
56649
|
-
return;
|
|
56650
|
-
}
|
|
56651
|
-
const required = (key) => {
|
|
56652
|
-
const value = configuredValue(env[key]);
|
|
56653
|
-
if (value === undefined) {
|
|
56654
|
-
throw new Error(`${key} is required for Legion: the pane carries a boot token`);
|
|
56655
|
-
}
|
|
56656
|
-
return value;
|
|
56657
|
-
};
|
|
56658
|
-
return {
|
|
56659
|
-
daemonUrl: required("LEGION_DAEMON_URL"),
|
|
56660
|
-
configDir: required("CLAUDE_CONFIG_DIR"),
|
|
56661
|
-
bootToken: pointer === undefined ? required("LEGION_BOOT_TOKEN") : readSecretFile("LEGION_BOOT_TOKEN_FILE", pointer),
|
|
56662
|
-
launcherSaves: configuredValue(env["LEGION_CLAUDE_SESSION_ID"]) !== undefined
|
|
56663
|
-
};
|
|
56664
|
-
}
|
|
56665
|
-
function logLegion(line) {
|
|
56666
|
-
process.stderr.write(`[legion] ${line}
|
|
56667
|
-
`);
|
|
56668
|
-
}
|
|
56669
|
-
function endPane() {
|
|
56670
|
-
process.kill(process.ppid, "SIGTERM");
|
|
56671
|
-
}
|
|
56672
|
-
function stopPane(why) {
|
|
56673
|
-
logLegion(`${why}; stopping the pane so the daemon launches it again`);
|
|
56674
|
-
endPane();
|
|
56675
|
-
}
|
|
56676
|
-
async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
|
|
56677
|
-
const projects = join8(configDir, "projects");
|
|
56678
|
-
const name = `${sessionID}.jsonl`;
|
|
56679
|
-
for (;; ) {
|
|
56680
|
-
signal.throwIfAborted();
|
|
56681
|
-
for (const directory of await readdir2(projects).catch(() => [])) {
|
|
56682
|
-
const file = join8(projects, directory, name);
|
|
56683
|
-
if (await isFile(file))
|
|
56684
|
-
return file;
|
|
56685
|
-
}
|
|
56686
|
-
await delay(pollMs, undefined, { signal });
|
|
56690
|
+
stopAfterRegistration(host, claim.claimToken, error);
|
|
56691
|
+
return { claimed: Promise.resolve() };
|
|
56687
56692
|
}
|
|
56693
|
+
return { claimed: claimRoleAtFirstTurn(host, claim.claimToken, firstTurn) };
|
|
56688
56694
|
}
|
|
56689
|
-
|
|
56690
|
-
|
|
56691
|
-
|
|
56692
|
-
for (;; ) {
|
|
56693
|
-
signal.throwIfAborted();
|
|
56694
|
-
if (await isFile(marker))
|
|
56695
|
-
return;
|
|
56696
|
-
await delay(pollMs, undefined, { signal });
|
|
56697
|
-
}
|
|
56698
|
-
}
|
|
56699
|
-
function isFile(file) {
|
|
56700
|
-
return stat2(file).then((info) => info.isFile(), () => false);
|
|
56695
|
+
function stopAfterRegistration(host, role, error) {
|
|
56696
|
+
host.log(`claim boot failed after claims/register registered ${role}; ${host.stopping}: ${messageFor(error)}`);
|
|
56697
|
+
host.stop();
|
|
56701
56698
|
}
|
|
56702
|
-
|
|
56703
|
-
|
|
56704
|
-
|
|
56705
|
-
|
|
56706
|
-
|
|
56707
|
-
|
|
56708
|
-
const roleRetryMs = deps.roleRetryMs ?? ROLE_CLAIM_RETRY_MS;
|
|
56709
|
-
const boot = async () => {
|
|
56710
|
-
const transcript = await waitForTranscript(deps.pane.configDir, sessionID, deps.signal, deps.pollMs);
|
|
56711
|
-
if (deps.pane.launcherSaves) {
|
|
56712
|
-
await waitForSavedTranscript(transcript, deps.signal, deps.pollMs);
|
|
56713
|
-
}
|
|
56714
|
-
await bootLegionClaim({
|
|
56715
|
-
daemon: deps.daemon,
|
|
56716
|
-
registration: {
|
|
56717
|
-
bootToken: deps.pane.bootToken,
|
|
56718
|
-
sessionId: sessionID,
|
|
56719
|
-
ompSessionFile: transcript,
|
|
56720
|
-
agentId: sessionID,
|
|
56721
|
-
pluginContract: legion.daemonApiVersion
|
|
56722
|
-
},
|
|
56723
|
-
setCapability: (registered) => {
|
|
56724
|
-
capability = registered;
|
|
56725
|
-
},
|
|
56726
|
-
claimRole: async (role) => {
|
|
56727
|
-
const deadline = Date.now() + roleWaitMs;
|
|
56728
|
-
let waited = false;
|
|
56729
|
-
for (;; ) {
|
|
56730
|
-
const claimed = await deps.client.setRole({
|
|
56731
|
-
sessionID,
|
|
56732
|
-
role,
|
|
56733
|
-
soft: true,
|
|
56734
|
-
clientInstanceID: deps.clientInstanceID
|
|
56735
|
-
});
|
|
56736
|
-
if (claimed.claimed)
|
|
56737
|
-
break;
|
|
56738
|
-
if (claimed.holder !== sessionID) {
|
|
56739
|
-
throw new Error(`Envoy role ${role} is held by live session ${claimed.holder}`);
|
|
56740
|
-
}
|
|
56741
|
-
const left = deadline - Date.now();
|
|
56742
|
-
if (left <= 0) {
|
|
56743
|
-
throw new Error(`Envoy role ${role} is still claimed under this session by another process after ${roleWaitMs} ms of asking`);
|
|
56744
|
-
}
|
|
56745
|
-
if (!waited) {
|
|
56746
|
-
waited = true;
|
|
56747
|
-
deps.log(`Envoy role ${role} is claimed under this session by the process this pane replaced; asking again every ${roleRetryMs} ms for up to ${roleWaitMs} ms, until nobody has answered for that claim inside the listener's live window`);
|
|
56748
|
-
}
|
|
56749
|
-
await delay(Math.min(roleRetryMs, left), undefined, { signal: deps.signal });
|
|
56750
|
-
}
|
|
56751
|
-
await deps.session.rememberRole(role);
|
|
56752
|
-
},
|
|
56753
|
-
onRoleRegained: (listener) => deps.session.onRoleRegained(listener),
|
|
56754
|
-
log: deps.log,
|
|
56755
|
-
stopping: "stopping the pane so the daemon launches it again",
|
|
56756
|
-
stop: () => {
|
|
56757
|
-
if (!deps.signal.aborted)
|
|
56758
|
-
deps.stop();
|
|
56759
|
-
}
|
|
56760
|
-
});
|
|
56761
|
-
};
|
|
56762
|
-
const booted = boot().catch((error) => {
|
|
56763
|
-
if (deps.signal.aborted)
|
|
56764
|
-
return;
|
|
56765
|
-
deps.log(`claim boot failed before a registration; the daemon's registration deadline relaunches the pane: ${messageFor(error)}`);
|
|
56699
|
+
function listenForFirstTurn(host) {
|
|
56700
|
+
let started = false;
|
|
56701
|
+
let claim;
|
|
56702
|
+
host.onFirstTurn(() => {
|
|
56703
|
+
started = true;
|
|
56704
|
+
claim?.();
|
|
56766
56705
|
});
|
|
56767
|
-
return
|
|
56768
|
-
|
|
56769
|
-
|
|
56770
|
-
|
|
56771
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
56772
|
-
import { createConnection } from "net";
|
|
56773
|
-
var INBOX_VARIABLE = "LEGION_CLAUDE_INBOX";
|
|
56774
|
-
var INBOX_CAPABILITIES = [
|
|
56775
|
-
"aside",
|
|
56776
|
-
"steer"
|
|
56777
|
-
];
|
|
56778
|
-
function createInboxNotifier(socketPath) {
|
|
56779
|
-
let socket;
|
|
56780
|
-
let buffered = "";
|
|
56781
|
-
const waiting = [];
|
|
56782
|
-
const fail = (error) => {
|
|
56783
|
-
for (const pending of waiting.splice(0))
|
|
56784
|
-
pending.settle.reject(error);
|
|
56706
|
+
return (step) => {
|
|
56707
|
+
claim = step;
|
|
56708
|
+
if (started)
|
|
56709
|
+
step();
|
|
56785
56710
|
};
|
|
56786
|
-
|
|
56787
|
-
|
|
56788
|
-
|
|
56789
|
-
|
|
56790
|
-
|
|
56791
|
-
|
|
56792
|
-
parsed = JSON.parse(line);
|
|
56793
|
-
} catch {
|
|
56794
|
-
pending.settle.reject(new Error(`the Legion inbox answered ${JSON.stringify(line)}`));
|
|
56711
|
+
}
|
|
56712
|
+
function claimRoleAtFirstTurn(host, role, firstTurn) {
|
|
56713
|
+
const done = Promise.withResolvers();
|
|
56714
|
+
let ran = false;
|
|
56715
|
+
const claim = () => {
|
|
56716
|
+
if (ran)
|
|
56795
56717
|
return;
|
|
56796
|
-
|
|
56797
|
-
|
|
56798
|
-
|
|
56799
|
-
|
|
56800
|
-
|
|
56801
|
-
|
|
56802
|
-
|
|
56803
|
-
const connected = () => {
|
|
56804
|
-
if (socket !== undefined && !socket.destroyed)
|
|
56805
|
-
return socket;
|
|
56806
|
-
buffered = "";
|
|
56807
|
-
const opened = createConnection(socketPath);
|
|
56808
|
-
opened.setEncoding("utf8");
|
|
56809
|
-
opened.on("data", (chunk) => {
|
|
56810
|
-
buffered += chunk;
|
|
56811
|
-
for (let end = buffered.indexOf(`
|
|
56812
|
-
`);end >= 0; end = buffered.indexOf(`
|
|
56813
|
-
`)) {
|
|
56814
|
-
const line = buffered.slice(0, end);
|
|
56815
|
-
buffered = buffered.slice(end + 1);
|
|
56816
|
-
answer(line);
|
|
56718
|
+
ran = true;
|
|
56719
|
+
clearTimeout(bound);
|
|
56720
|
+
(async () => {
|
|
56721
|
+
try {
|
|
56722
|
+
await host.claimRole(role);
|
|
56723
|
+
} catch (error) {
|
|
56724
|
+
stopAfterRegistration(host, role, error);
|
|
56817
56725
|
}
|
|
56818
|
-
|
|
56819
|
-
|
|
56820
|
-
opened.on("close", () => {
|
|
56821
|
-
fail(new Error(`the Legion inbox ${socketPath} closed before it answered`));
|
|
56822
|
-
if (socket === opened)
|
|
56823
|
-
socket = undefined;
|
|
56824
|
-
});
|
|
56825
|
-
socket = opened;
|
|
56826
|
-
return opened;
|
|
56827
|
-
};
|
|
56828
|
-
return {
|
|
56829
|
-
notification(notification) {
|
|
56830
|
-
const id = notification.eventId ?? randomUUID2();
|
|
56831
|
-
const settle = Promise.withResolvers();
|
|
56832
|
-
waiting.push({ id, settle });
|
|
56833
|
-
connected().write(`${JSON.stringify({
|
|
56834
|
-
id,
|
|
56835
|
-
content: notification.content,
|
|
56836
|
-
...notification.blocks === undefined ? {} : { blocks: notification.blocks }
|
|
56837
|
-
})}
|
|
56838
|
-
`);
|
|
56839
|
-
return settle.promise;
|
|
56840
|
-
}
|
|
56726
|
+
done.resolve();
|
|
56727
|
+
})();
|
|
56841
56728
|
};
|
|
56729
|
+
const bound = setTimeout(claim, host.firstTurnBoundMs);
|
|
56730
|
+
bound.unref?.();
|
|
56731
|
+
firstTurn(claim);
|
|
56732
|
+
return done.promise;
|
|
56842
56733
|
}
|
|
56843
56734
|
|
|
56844
56735
|
// src/legion-phase-hook.ts
|
|
56845
|
-
import { randomUUID as
|
|
56736
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
56846
56737
|
import { readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
|
|
56847
|
-
import { dirname as dirname3, join as
|
|
56738
|
+
import { dirname as dirname3, join as join8 } from "path";
|
|
56848
56739
|
|
|
56849
56740
|
// ../pi-shared/src/phase-reminder.ts
|
|
56850
|
-
import { randomUUID as
|
|
56741
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
56851
56742
|
|
|
56852
56743
|
// ../pi-shared/src/phase-stall.ts
|
|
56853
56744
|
var WAITING_REPLY = /^\W*WAITING\b/m;
|
|
@@ -57036,7 +56927,7 @@ function createPhaseReminder(deps) {
|
|
|
57036
56927
|
});
|
|
57037
56928
|
return;
|
|
57038
56929
|
}
|
|
57039
|
-
reportKey ??=
|
|
56930
|
+
reportKey ??= randomUUID2();
|
|
57040
56931
|
const key = reportKey;
|
|
57041
56932
|
writeEntry();
|
|
57042
56933
|
const phase = record?.phase ?? "unknown";
|
|
@@ -57222,49 +57113,6 @@ function sessionActivityRequest(input) {
|
|
|
57222
57113
|
};
|
|
57223
57114
|
}
|
|
57224
57115
|
|
|
57225
|
-
// ../pi-shared/src/stall-limits.ts
|
|
57226
|
-
var DEFAULT_STALL_LIMITS = {
|
|
57227
|
-
reminderMs: 300000,
|
|
57228
|
-
waitingMs: 900000,
|
|
57229
|
-
resumeMs: 120000,
|
|
57230
|
-
architectAfter: 3,
|
|
57231
|
-
callGraceMs: 300000,
|
|
57232
|
-
callBoundMs: 3600000,
|
|
57233
|
-
stepMs: 120000
|
|
57234
|
-
};
|
|
57235
|
-
var LONG_CALL_BOUND_MS = 14400000;
|
|
57236
|
-
var LONG_CALL_BOUND_ROLES = [
|
|
57237
|
-
"implementer",
|
|
57238
|
-
"reviewer"
|
|
57239
|
-
];
|
|
57240
|
-
function defaultCallBoundMs(role) {
|
|
57241
|
-
return role !== undefined && LONG_CALL_BOUND_ROLES.includes(role) ? LONG_CALL_BOUND_MS : DEFAULT_STALL_LIMITS.callBoundMs;
|
|
57242
|
-
}
|
|
57243
|
-
function integerSetting(env, log, name, fallback, least) {
|
|
57244
|
-
const raw = env[name];
|
|
57245
|
-
if (raw === undefined)
|
|
57246
|
-
return fallback;
|
|
57247
|
-
const value = raw.trim() === "" ? Number.NaN : Number(raw);
|
|
57248
|
-
if (!Number.isInteger(value) || value < least) {
|
|
57249
|
-
log.warn(`legion: ${name} is not an integer of ${least} or more; using ${fallback}`, {
|
|
57250
|
-
value: raw
|
|
57251
|
-
});
|
|
57252
|
-
return fallback;
|
|
57253
|
-
}
|
|
57254
|
-
return value;
|
|
57255
|
-
}
|
|
57256
|
-
function stallLimits(env, log, role) {
|
|
57257
|
-
return {
|
|
57258
|
-
reminderMs: integerSetting(env, log, "LEGION_STALL_REMINDER_MS", DEFAULT_STALL_LIMITS.reminderMs, 0),
|
|
57259
|
-
waitingMs: integerSetting(env, log, "LEGION_STALL_WAITING_MS", DEFAULT_STALL_LIMITS.waitingMs, 0),
|
|
57260
|
-
resumeMs: integerSetting(env, log, "LEGION_STALL_RESUME_MS", DEFAULT_STALL_LIMITS.resumeMs, 0),
|
|
57261
|
-
architectAfter: integerSetting(env, log, "LEGION_STALL_ARCHITECT_AFTER", DEFAULT_STALL_LIMITS.architectAfter, 2),
|
|
57262
|
-
callGraceMs: integerSetting(env, log, "LEGION_STALL_CALL_GRACE_MS", DEFAULT_STALL_LIMITS.callGraceMs, 0),
|
|
57263
|
-
callBoundMs: integerSetting(env, log, "LEGION_STALL_CALL_BOUND_MS", defaultCallBoundMs(role), 0),
|
|
57264
|
-
stepMs: integerSetting(env, log, "LEGION_STALL_STEP_MS", DEFAULT_STALL_LIMITS.stepMs, 0)
|
|
57265
|
-
};
|
|
57266
|
-
}
|
|
57267
|
-
|
|
57268
57116
|
// ../pi-shared/src/workspace-recreated.ts
|
|
57269
57117
|
var WORKSPACE_RECREATED_VARIABLE = "LEGION_WORKSPACE_RECREATED";
|
|
57270
57118
|
var WORKSPACE_RESTORED_VARIABLE = "LEGION_WORKSPACE_RESTORED";
|
|
@@ -57327,7 +57175,7 @@ function phaseHookToolDefinition() {
|
|
|
57327
57175
|
};
|
|
57328
57176
|
}
|
|
57329
57177
|
function phaseStallFile(configDir, sessionID) {
|
|
57330
|
-
return
|
|
57178
|
+
return join8(configDir, `legion-phase-stall-${sessionID}.json`);
|
|
57331
57179
|
}
|
|
57332
57180
|
function paneReminderLog(write) {
|
|
57333
57181
|
const line = (level, message, context) => {
|
|
@@ -57380,7 +57228,7 @@ function readPhaseStallRecord(file, log) {
|
|
|
57380
57228
|
};
|
|
57381
57229
|
}
|
|
57382
57230
|
function writePhaseStallRecord(file, entry, recreatedNoticeSent, log) {
|
|
57383
|
-
const temporary =
|
|
57231
|
+
const temporary = join8(dirname3(file), `.legion-phase-stall-${randomUUID3()}`);
|
|
57384
57232
|
try {
|
|
57385
57233
|
writeFileSync4(temporary, JSON.stringify({ ...entry, ...recreatedNoticeSent ? { recreatedNoticeSent } : {} }), { mode: 384 });
|
|
57386
57234
|
renameSync3(temporary, file);
|
|
@@ -57505,6 +57353,8 @@ function createPhaseHookEndpoint(deps) {
|
|
|
57505
57353
|
if (!parsed.success)
|
|
57506
57354
|
return { error: PHASE_HOOK_REFUSAL };
|
|
57507
57355
|
const event = parsed.data;
|
|
57356
|
+
if (event.event === "UserPromptSubmit")
|
|
57357
|
+
deps.firstTurnStarted();
|
|
57508
57358
|
const claim = deps.claim();
|
|
57509
57359
|
if (claim === undefined || claim.role === "architect")
|
|
57510
57360
|
return {};
|
|
@@ -57549,6 +57399,214 @@ function createPhaseHookEndpoint(deps) {
|
|
|
57549
57399
|
};
|
|
57550
57400
|
}
|
|
57551
57401
|
|
|
57402
|
+
// src/legion-claim.ts
|
|
57403
|
+
function legionPane(env) {
|
|
57404
|
+
const pointer = env["LEGION_BOOT_TOKEN_FILE"];
|
|
57405
|
+
if (pointer === undefined && configuredValue(env["LEGION_BOOT_TOKEN"]) === undefined) {
|
|
57406
|
+
return;
|
|
57407
|
+
}
|
|
57408
|
+
const required = (key) => {
|
|
57409
|
+
const value = configuredValue(env[key]);
|
|
57410
|
+
if (value === undefined) {
|
|
57411
|
+
throw new Error(`${key} is required for Legion: the pane carries a boot token`);
|
|
57412
|
+
}
|
|
57413
|
+
return value;
|
|
57414
|
+
};
|
|
57415
|
+
return {
|
|
57416
|
+
daemonUrl: required("LEGION_DAEMON_URL"),
|
|
57417
|
+
configDir: required("CLAUDE_CONFIG_DIR"),
|
|
57418
|
+
bootToken: pointer === undefined ? required("LEGION_BOOT_TOKEN") : readSecretFile("LEGION_BOOT_TOKEN_FILE", pointer),
|
|
57419
|
+
launcherSaves: configuredValue(env["LEGION_CLAUDE_SESSION_ID"]) !== undefined
|
|
57420
|
+
};
|
|
57421
|
+
}
|
|
57422
|
+
function logLegion(line) {
|
|
57423
|
+
process.stderr.write(`[legion] ${line}
|
|
57424
|
+
`);
|
|
57425
|
+
}
|
|
57426
|
+
function endPane() {
|
|
57427
|
+
process.kill(process.ppid, "SIGTERM");
|
|
57428
|
+
}
|
|
57429
|
+
function stopPane(why) {
|
|
57430
|
+
logLegion(`${why}; stopping the pane so the daemon launches it again`);
|
|
57431
|
+
endPane();
|
|
57432
|
+
}
|
|
57433
|
+
async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
|
|
57434
|
+
const projects = join9(configDir, "projects");
|
|
57435
|
+
const name = `${sessionID}.jsonl`;
|
|
57436
|
+
for (;; ) {
|
|
57437
|
+
signal.throwIfAborted();
|
|
57438
|
+
for (const directory of await readdir2(projects).catch(() => [])) {
|
|
57439
|
+
const file = join9(projects, directory, name);
|
|
57440
|
+
if (await isFile(file))
|
|
57441
|
+
return file;
|
|
57442
|
+
}
|
|
57443
|
+
await delay(pollMs, undefined, { signal });
|
|
57444
|
+
}
|
|
57445
|
+
}
|
|
57446
|
+
var SAVED_MARKER_SUFFIX = ".legion-saved";
|
|
57447
|
+
async function waitForSavedTranscript(transcript, signal, pollMs = 100) {
|
|
57448
|
+
const marker = `${transcript}${SAVED_MARKER_SUFFIX}`;
|
|
57449
|
+
for (;; ) {
|
|
57450
|
+
signal.throwIfAborted();
|
|
57451
|
+
if (await isFile(marker))
|
|
57452
|
+
return;
|
|
57453
|
+
await delay(pollMs, undefined, { signal });
|
|
57454
|
+
}
|
|
57455
|
+
}
|
|
57456
|
+
function isFile(file) {
|
|
57457
|
+
return stat2(file).then((info) => info.isFile(), () => false);
|
|
57458
|
+
}
|
|
57459
|
+
var ROLE_CLAIM_RETRY_MS = 1e4;
|
|
57460
|
+
var ROLE_CLAIM_WAIT_MS = SESSION_LIVE_WINDOW_MS + ROLE_CLAIM_RETRY_MS;
|
|
57461
|
+
function startLegionClaim(deps) {
|
|
57462
|
+
let capability;
|
|
57463
|
+
const { sessionID } = deps;
|
|
57464
|
+
const roleWaitMs = deps.roleWaitMs ?? ROLE_CLAIM_WAIT_MS;
|
|
57465
|
+
const roleRetryMs = deps.roleRetryMs ?? ROLE_CLAIM_RETRY_MS;
|
|
57466
|
+
const boot = async () => {
|
|
57467
|
+
const transcript = await waitForTranscript(deps.pane.configDir, sessionID, deps.signal, deps.pollMs);
|
|
57468
|
+
if (deps.pane.launcherSaves) {
|
|
57469
|
+
await waitForSavedTranscript(transcript, deps.signal, deps.pollMs);
|
|
57470
|
+
}
|
|
57471
|
+
return await bootLegionClaim({
|
|
57472
|
+
daemon: deps.daemon,
|
|
57473
|
+
registration: {
|
|
57474
|
+
bootToken: deps.pane.bootToken,
|
|
57475
|
+
sessionId: sessionID,
|
|
57476
|
+
ompSessionFile: transcript,
|
|
57477
|
+
agentId: sessionID,
|
|
57478
|
+
pluginContract: legion.daemonApiVersion
|
|
57479
|
+
},
|
|
57480
|
+
setCapability: (registered) => {
|
|
57481
|
+
capability = registered;
|
|
57482
|
+
},
|
|
57483
|
+
claimRole: async (role) => {
|
|
57484
|
+
const deadline = Date.now() + roleWaitMs;
|
|
57485
|
+
let waited = false;
|
|
57486
|
+
for (;; ) {
|
|
57487
|
+
const claimed = await deps.client.setRole({
|
|
57488
|
+
sessionID,
|
|
57489
|
+
role,
|
|
57490
|
+
soft: true,
|
|
57491
|
+
clientInstanceID: deps.clientInstanceID
|
|
57492
|
+
});
|
|
57493
|
+
if (claimed.claimed)
|
|
57494
|
+
break;
|
|
57495
|
+
if (claimed.holder !== sessionID) {
|
|
57496
|
+
throw new Error(`Envoy role ${role} is held by live session ${claimed.holder}`);
|
|
57497
|
+
}
|
|
57498
|
+
const left = deadline - Date.now();
|
|
57499
|
+
if (left <= 0) {
|
|
57500
|
+
throw new Error(`Envoy role ${role} is still claimed under this session by another process after ${roleWaitMs} ms of asking`);
|
|
57501
|
+
}
|
|
57502
|
+
if (!waited) {
|
|
57503
|
+
waited = true;
|
|
57504
|
+
deps.log(`Envoy role ${role} is claimed under this session by the process this pane replaced; asking again every ${roleRetryMs} ms for up to ${roleWaitMs} ms, until nobody has answered for that claim inside the listener's live window`);
|
|
57505
|
+
}
|
|
57506
|
+
await delay(Math.min(roleRetryMs, left), undefined, { signal: deps.signal });
|
|
57507
|
+
}
|
|
57508
|
+
await deps.session.rememberRole(role);
|
|
57509
|
+
},
|
|
57510
|
+
onFirstTurn: deps.onFirstTurn,
|
|
57511
|
+
firstTurnBoundMs: claimFirstTurnBoundMs(deps.env ?? process.env, paneReminderLog(deps.log)),
|
|
57512
|
+
onRoleRegained: (listener) => deps.session.onRoleRegained(listener),
|
|
57513
|
+
log: deps.log,
|
|
57514
|
+
stopping: "stopping the pane so the daemon launches it again",
|
|
57515
|
+
stop: () => {
|
|
57516
|
+
if (!deps.signal.aborted)
|
|
57517
|
+
deps.stop();
|
|
57518
|
+
}
|
|
57519
|
+
});
|
|
57520
|
+
};
|
|
57521
|
+
const started = boot().catch((error) => {
|
|
57522
|
+
if (!deps.signal.aborted) {
|
|
57523
|
+
deps.log(`claim boot failed before a registration; the daemon's registration deadline relaunches the pane: ${messageFor(error)}`);
|
|
57524
|
+
}
|
|
57525
|
+
return { claimed: Promise.resolve() };
|
|
57526
|
+
});
|
|
57527
|
+
return {
|
|
57528
|
+
capability: () => capability,
|
|
57529
|
+
booted: started.then(() => {
|
|
57530
|
+
return;
|
|
57531
|
+
}),
|
|
57532
|
+
claimed: started.then((claimBoot) => claimBoot.claimed)
|
|
57533
|
+
};
|
|
57534
|
+
}
|
|
57535
|
+
|
|
57536
|
+
// src/legion-inbox.ts
|
|
57537
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
57538
|
+
import { createConnection } from "net";
|
|
57539
|
+
var INBOX_VARIABLE = "LEGION_CLAUDE_INBOX";
|
|
57540
|
+
var INBOX_CAPABILITIES = [
|
|
57541
|
+
"aside",
|
|
57542
|
+
"steer"
|
|
57543
|
+
];
|
|
57544
|
+
function createInboxNotifier(socketPath) {
|
|
57545
|
+
let socket;
|
|
57546
|
+
let buffered = "";
|
|
57547
|
+
const waiting = [];
|
|
57548
|
+
const fail = (error) => {
|
|
57549
|
+
for (const pending of waiting.splice(0))
|
|
57550
|
+
pending.settle.reject(error);
|
|
57551
|
+
};
|
|
57552
|
+
const answer = (line) => {
|
|
57553
|
+
const pending = waiting.shift();
|
|
57554
|
+
if (pending === undefined)
|
|
57555
|
+
return;
|
|
57556
|
+
let parsed;
|
|
57557
|
+
try {
|
|
57558
|
+
parsed = JSON.parse(line);
|
|
57559
|
+
} catch {
|
|
57560
|
+
pending.settle.reject(new Error(`the Legion inbox answered ${JSON.stringify(line)}`));
|
|
57561
|
+
return;
|
|
57562
|
+
}
|
|
57563
|
+
if (parsed.ok === true && parsed.id === pending.id)
|
|
57564
|
+
pending.settle.resolve();
|
|
57565
|
+
else {
|
|
57566
|
+
pending.settle.reject(new Error(`the Legion inbox refused delivery ${pending.id}: ${parsed.error ?? `answered ${line}`}`));
|
|
57567
|
+
}
|
|
57568
|
+
};
|
|
57569
|
+
const connected = () => {
|
|
57570
|
+
if (socket !== undefined && !socket.destroyed)
|
|
57571
|
+
return socket;
|
|
57572
|
+
buffered = "";
|
|
57573
|
+
const opened = createConnection(socketPath);
|
|
57574
|
+
opened.setEncoding("utf8");
|
|
57575
|
+
opened.on("data", (chunk) => {
|
|
57576
|
+
buffered += chunk;
|
|
57577
|
+
for (let end = buffered.indexOf(`
|
|
57578
|
+
`);end >= 0; end = buffered.indexOf(`
|
|
57579
|
+
`)) {
|
|
57580
|
+
const line = buffered.slice(0, end);
|
|
57581
|
+
buffered = buffered.slice(end + 1);
|
|
57582
|
+
answer(line);
|
|
57583
|
+
}
|
|
57584
|
+
});
|
|
57585
|
+
opened.on("error", (error) => fail(new Error(`the Legion inbox ${socketPath}: ${error.message}`)));
|
|
57586
|
+
opened.on("close", () => {
|
|
57587
|
+
fail(new Error(`the Legion inbox ${socketPath} closed before it answered`));
|
|
57588
|
+
if (socket === opened)
|
|
57589
|
+
socket = undefined;
|
|
57590
|
+
});
|
|
57591
|
+
socket = opened;
|
|
57592
|
+
return opened;
|
|
57593
|
+
};
|
|
57594
|
+
return {
|
|
57595
|
+
notification(notification) {
|
|
57596
|
+
const id = notification.eventId ?? randomUUID4();
|
|
57597
|
+
const settle = Promise.withResolvers();
|
|
57598
|
+
waiting.push({ id, settle });
|
|
57599
|
+
connected().write(`${JSON.stringify({
|
|
57600
|
+
id,
|
|
57601
|
+
content: notification.content,
|
|
57602
|
+
...notification.blocks === undefined ? {} : { blocks: notification.blocks }
|
|
57603
|
+
})}
|
|
57604
|
+
`);
|
|
57605
|
+
return settle.promise;
|
|
57606
|
+
}
|
|
57607
|
+
};
|
|
57608
|
+
}
|
|
57609
|
+
|
|
57552
57610
|
// ../pi-shared/src/legion-phase-ops.ts
|
|
57553
57611
|
var PHASE_OPS = [
|
|
57554
57612
|
"read_record",
|
|
@@ -60120,10 +60178,12 @@ async function runEnvoyChannelServer() {
|
|
|
60120
60178
|
const daemon = pane === undefined ? undefined : createLegionDaemonClient(pane.daemonUrl);
|
|
60121
60179
|
const phaseLog = paneReminderLog(logLegion);
|
|
60122
60180
|
const claimBooted = Promise.withResolvers();
|
|
60181
|
+
let reportFirstTurn;
|
|
60123
60182
|
const phaseHook = pane === undefined || daemon === undefined ? undefined : createPhaseHookEndpoint({
|
|
60124
60183
|
stateFile: phaseStallFile(pane.configDir, identity.id),
|
|
60125
60184
|
claim: () => claim?.capability(),
|
|
60126
60185
|
booted: claimBooted.promise,
|
|
60186
|
+
firstTurnStarted: () => reportFirstTurn?.(),
|
|
60127
60187
|
readState: (signal) => daemon.state({ signal }),
|
|
60128
60188
|
reportActivity: (input) => daemon.activity(input),
|
|
60129
60189
|
inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
|
|
@@ -60320,7 +60380,10 @@ async function runEnvoyChannelServer() {
|
|
|
60320
60380
|
session,
|
|
60321
60381
|
signal: booting.signal,
|
|
60322
60382
|
log: logLegion,
|
|
60323
|
-
stop: endPane
|
|
60383
|
+
stop: endPane,
|
|
60384
|
+
onFirstTurn: (started) => {
|
|
60385
|
+
reportFirstTurn = started;
|
|
60386
|
+
}
|
|
60324
60387
|
});
|
|
60325
60388
|
claim.booted.then(claimBooted.resolve);
|
|
60326
60389
|
}
|
package/package.json
CHANGED
package/skills/envoy/SKILL.md
CHANGED
|
@@ -80,4 +80,4 @@ Every topic starts with `notifications.`.
|
|
|
80
80
|
- A message that must reach more than 4 role topics is the project controller's to send, not yours. Each publish wakes a session, and a woken session reads its whole context again, which the provider charges as uncached input: a mean of 576,083 tokens a wake, a median of 493,636 and a ninetieth percentile of 1,327,888. The controller is also the one session that can read whether a wave of wakes is already running, and a fan-out sent into a daemon restart or a pod roll is what puts an Anthropic organization over its per-minute uncached-input cap. Send the controller the topics and the text, and it sends them at its own rate (`skill://legion-controller`).
|
|
81
81
|
- For a team, the group subscribes to `notifications.team.<name>.>`, and any member publishes to `notifications.team.<name>.all`. Envoy treats any other `notifications.` topic that no source in the table uses the same way. It reaches every session subscribed when it is published, yours too when you subscribe. The listener also asks each other session that holds its own NATS connection and registered the topic (every session that follows it with `envoy_subscribe`) to confirm the message; your own session is never asked. A publish returns an error naming each such session that did not confirm within about 4 seconds, and you see it after about 8 seconds, because the client tries once more. A session named with `receipt_timeout` still gets the message: the listener kept a copy in that session's inbox, which the session reads back once its connection returns. An `unresponsive` session is sent the message the same way, asked for no receipt and named under `unresponsive` in the answer, which is no failure. A session that stopped without unregistering stays in the registry until the reaper finds it `gone`, and is named until then; a named session is not a failed delivery to the others. A team topic is not kept for a session that subscribes later. A topic outside `notifications.` is refused.
|
|
82
82
|
- How a role claim survives a resume, a fork or a dead process: `skill://envoy/references/roles.md`.
|
|
83
|
-
- In a Legion pane, the plugin claims your role at session
|
|
83
|
+
- In a Legion pane, the plugin claims your role for you, at your session's first turn; read `skill://envoy/references/legion.md` before you claim, release or publish to a role, or answer a role delivery failure there.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Read this in a Legion pane before you touch a role claim, or when a Legion role message fails.
|
|
4
4
|
|
|
5
|
-
- The Legion plugin claims your assigned role
|
|
5
|
+
- The Legion plugin claims your assigned role for you, through a daemon-minted role token: it registers your session and reports it ready at session start, and takes the role at your first turn, or at a bound (30 s by default) when no turn comes first. Never call `envoy_role_set` and never subscribe to your role topic yourself, because the claim is already made (`packages/pi-shared/src/legion-claim-core.ts`).
|
|
6
6
|
- Never build a role token from an issue number or title: only the daemon maps tokens to issues.
|
|
7
7
|
- A Legion claim is last-claim-wins. It survives parking and worker re-creation, and stays through the issue's linger after close (the deployment's `linger_hours`).
|
|
8
8
|
- `no_holder`, `holder_lapsed`, `delivery_failed` and `receipt_timeout` on a Legion role are the daemon's liveness signals. Never add a second subscriber or retry by hand: the daemon revives or recreates the worker and re-delivers, or relaunches the root process, which gets a `catch-up` notice of its tree and reads each issue's handoffs on its Dispatch issue (`dispatch handoff-read`).
|
|
@@ -2171,6 +2171,26 @@ export async function runEnvoyChannelServer(): Promise<void> {
|
|
|
2171
2171
|
// The claim's boot, for the endpoint's resume reminder and its recreated-workspace notice: both
|
|
2172
2172
|
// need the claim, and the claim starts further down, once the channel session exists.
|
|
2173
2173
|
const claimBooted = Promise.withResolvers<void>()
|
|
2174
|
+
// The other way round: the hook endpoint is built here, before the claim, and the boot's
|
|
2175
|
+
// first-turn signal fills this slot. The endpoint calls it at every `UserPromptSubmit`, this
|
|
2176
|
+
// process's only sight of a turn starting; the call reports that turn and claims nothing, and
|
|
2177
|
+
// the boot's own claim step, which runs after `claims/ready`, is what takes the Envoy name —
|
|
2178
|
+
// inside a running turn rather than ahead of the daemon's task (INFRA-1573).
|
|
2179
|
+
//
|
|
2180
|
+
// A slot, rather than a promise that remembers every prompt this process ever saw, because on
|
|
2181
|
+
// this host the first prompt is always the bridge's seeding `/rename`
|
|
2182
|
+
// (`packages/daemon/internal/claudebridge`), which runs before the claim exists — it is what
|
|
2183
|
+
// writes the transcript the boot waits for, so no registration can precede it. A signal kept
|
|
2184
|
+
// from before the boot filled this slot would take the name the moment `claims/ready` answers,
|
|
2185
|
+
// ahead of the daemon's task, which is the ordering this defers.
|
|
2186
|
+
//
|
|
2187
|
+
// The boot fills the slot as soon as `claims/register` has answered, before the ready that
|
|
2188
|
+
// follows, so a prompt that arrives while that ready is still being retried — the daemon took
|
|
2189
|
+
// the first one and its answer was lost, and its task reaches Claude Code meanwhile — is this
|
|
2190
|
+
// session's first turn and the name is taken as soon as ready answers, rather than at the
|
|
2191
|
+
// bound. A pane given no task at all is the bound's to cover, and a later prompt costs
|
|
2192
|
+
// nothing — the step itself claims once however often it runs.
|
|
2193
|
+
let reportFirstTurn: (() => void) | undefined
|
|
2174
2194
|
const phaseHook =
|
|
2175
2195
|
pane === undefined || daemon === undefined
|
|
2176
2196
|
? undefined
|
|
@@ -2178,6 +2198,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
|
|
|
2178
2198
|
stateFile: phaseStallFile(pane.configDir, identity.id),
|
|
2179
2199
|
claim: () => claim?.capability(),
|
|
2180
2200
|
booted: claimBooted.promise,
|
|
2201
|
+
firstTurnStarted: () => reportFirstTurn?.(),
|
|
2181
2202
|
readState: (signal) => daemon.state({ signal }),
|
|
2182
2203
|
reportActivity: (input) => daemon.activity(input),
|
|
2183
2204
|
inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
|
|
@@ -2454,6 +2475,12 @@ export async function runEnvoyChannelServer(): Promise<void> {
|
|
|
2454
2475
|
signal: booting.signal,
|
|
2455
2476
|
log: logLegion,
|
|
2456
2477
|
stop: endPane,
|
|
2478
|
+
// The signal goes in the slot the phase hook's `UserPromptSubmit` calls. The boot fills
|
|
2479
|
+
// it when `claims/register` has answered, which is after the bridge's seed: that prompt
|
|
2480
|
+
// found the slot empty and reported nothing.
|
|
2481
|
+
onFirstTurn: (started) => {
|
|
2482
|
+
reportFirstTurn = started
|
|
2483
|
+
},
|
|
2457
2484
|
})
|
|
2458
2485
|
// What `claimSession.bootstrap` returning is to the Oh My Pi host: the point the phase
|
|
2459
2486
|
// endpoint may read the claim, arm its resume reminder and tell the worker its workspace
|
package/src/legion-claim.ts
CHANGED
|
@@ -5,12 +5,14 @@ import { SESSION_LIVE_WINDOW_MS } from "@legion/contracts"
|
|
|
5
5
|
import { messageFor } from "@legion/envoy-client/errors"
|
|
6
6
|
import { readSecretFile } from "@legion/envoy-client/secret-file"
|
|
7
7
|
import type { EnvoyClient } from "@legion/envoy-client/transport"
|
|
8
|
+
import { claimFirstTurnBoundMs } from "@legion/pi-shared/claim-first-turn-bound"
|
|
8
9
|
import type { LegionDaemonClient } from "@legion/pi-shared/daemon-client"
|
|
9
|
-
import { bootLegionClaim } from "@legion/pi-shared/legion-claim-core"
|
|
10
|
+
import { bootLegionClaim, type LegionClaimBoot } from "@legion/pi-shared/legion-claim-core"
|
|
10
11
|
import type { ClaimCapability } from "@legion/pi-shared/legion-phase-ops"
|
|
11
12
|
import { legion } from "../package.json" with { type: "json" }
|
|
12
13
|
import { configuredValue } from "./claude-session"
|
|
13
14
|
import type { ChannelSession } from "./envoy-channel-server"
|
|
15
|
+
import { paneReminderLog } from "./legion-phase-hook"
|
|
14
16
|
|
|
15
17
|
/**
|
|
16
18
|
* A Claude Code phase worker's claim on the Legion daemon, made by the MCP server Claude Code runs
|
|
@@ -137,18 +139,21 @@ function isFile(file: string): Promise<boolean> {
|
|
|
137
139
|
* How long apart the attempts of {@link startLegionClaim}'s wait on a claim the listener refused
|
|
138
140
|
* naming this very session are.
|
|
139
141
|
*
|
|
140
|
-
* The wait runs
|
|
141
|
-
*
|
|
142
|
-
* `
|
|
143
|
-
* s
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
142
|
+
* The wait runs after `claims/ready`, not before it: the role is claimed last, at the session's
|
|
143
|
+
* first turn or at the bound (INFRA-1573), so the daemon's registration deadline —
|
|
144
|
+
* `worker_boot_timeout_seconds` × `worker_boot_registration_deadline_intervals`, 120 s × 3 = 360
|
|
145
|
+
* s with the shipped defaults (`packages/daemon/internal/config/config.go`, armed by `register`
|
|
146
|
+
* through `armRegistration` in `packages/daemon/internal/supervise`) — is already met when the
|
|
147
|
+
* first attempt goes out, and no part of this wait is spent against it.
|
|
148
|
+
*
|
|
149
|
+
* What bounds the wait now is the listener's own live window: the standing claim of the process
|
|
150
|
+
* this pane replaced is granted to nobody until a whole `SESSION_LIVE_WINDOW_MS` has passed with
|
|
151
|
+
* no answer for it, so no interval can bring the grant forward, and every part of an interval
|
|
152
|
+
* past that point is dead waiting with the session already ready — the daemon may have handed it
|
|
153
|
+
* a task, and the lane the listener keeps for a role no session holds is handed over only when
|
|
154
|
+
* the claim lands. The interval is kept at 10 s for that: the grant falls at most 10 s after the
|
|
155
|
+
* window passes, where the session heartbeat's own cadence (`SESSION_HEARTBEAT_MS`, 90 s) would
|
|
156
|
+
* leave the pane unaddressable for up to 90 s more.
|
|
152
157
|
*
|
|
153
158
|
* What the shorter interval costs: one `POST /v1/roles/set` per interval, a conditional write the
|
|
154
159
|
* listener refuses without touching the claim, at most about 30 of them, and only in a pane the
|
|
@@ -161,11 +166,12 @@ export const ROLE_CLAIM_RETRY_MS = 10_000
|
|
|
161
166
|
* How long that same wait keeps asking before it gives up and the pane is stopped: the live
|
|
162
167
|
* window and one attempt more, so the last attempt falls after the window the process this pane
|
|
163
168
|
* replaced could still have been answering for its claim in, even when it answered for it at the
|
|
164
|
-
* very moment this pane
|
|
169
|
+
* very moment this pane first asked.
|
|
165
170
|
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
171
|
+
* That window is the whole of what can explain a refusal naming this session, and `claims/ready`
|
|
172
|
+
* is already answered, so nothing outside the pane is counting: past the wait, the claim is
|
|
173
|
+
* stopped on as every other failure after a registration is, and the pane writes why to its log
|
|
174
|
+
* and is launched again rather than sitting nameless for a lane it can never be handed.
|
|
169
175
|
*/
|
|
170
176
|
export const ROLE_CLAIM_WAIT_MS = SESSION_LIVE_WINDOW_MS + ROLE_CLAIM_RETRY_MS
|
|
171
177
|
|
|
@@ -174,17 +180,23 @@ export interface LegionClaim {
|
|
|
174
180
|
readonly capability: () => ClaimCapability | undefined
|
|
175
181
|
/** Settles once the boot has run: ready sent, or the failure reported. Never rejects. */
|
|
176
182
|
readonly booted: Promise<void>
|
|
183
|
+
/** Settles once the boot's last step has run — the Envoy role claimed at this session's first
|
|
184
|
+
* turn or at the bound, or the refusal logged and the pane stopped — and at once for a boot
|
|
185
|
+
* that never reached that step (`LegionClaimBoot.claimed`). Never rejects. */
|
|
186
|
+
readonly claimed: Promise<void>
|
|
177
187
|
}
|
|
178
188
|
|
|
179
189
|
/**
|
|
180
190
|
* Boots the pane's claim in the background of the server (`bootLegionClaim`): waits for the
|
|
181
191
|
* transcript, and in a pod whose launcher keeps it (`launcherSaves`) for the launcher's first save
|
|
182
192
|
* of it too, registers with it as the session file (`agentId` is the session id,
|
|
183
|
-
* `pluginContract` this package's `legion.daemonApiVersion`), claims
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
193
|
+
* `pluginContract` this package's `legion.daemonApiVersion`), sends `claims/ready` with no
|
|
194
|
+
* capability report, again each time the heartbeat regains the role, and claims the claim
|
|
195
|
+
* token's Envoy role soft last of all — at this session's first turn (`onFirstTurn`) or at the
|
|
196
|
+
* bound this pane's environment names, whichever comes first — recording it with the channel
|
|
197
|
+
* session, whose heartbeat re-asserts it. A failure the core stops on ends the pane through
|
|
198
|
+
* `stop`; a failure before a registration is logged and leaves the pane to the daemon's
|
|
199
|
+
* registration deadline.
|
|
188
200
|
*
|
|
189
201
|
* A claim the listener refuses naming this very session is waited out rather than stopped on:
|
|
190
202
|
* the pane the daemon relaunched with `--resume` meets the standing claim of the process it
|
|
@@ -193,8 +205,8 @@ export interface LegionClaim {
|
|
|
193
205
|
* meets the same claim, for a whole window of relaunches.
|
|
194
206
|
*
|
|
195
207
|
* The claim is asked again every {@link ROLE_CLAIM_RETRY_MS} for up to
|
|
196
|
-
* {@link ROLE_CLAIM_WAIT_MS},
|
|
197
|
-
*
|
|
208
|
+
* {@link ROLE_CLAIM_WAIT_MS}, the listener's live window and one attempt more, which is the
|
|
209
|
+
* whole of what can explain such a refusal.
|
|
198
210
|
*/
|
|
199
211
|
export function startLegionClaim(deps: {
|
|
200
212
|
readonly pane: LegionPane
|
|
@@ -210,6 +222,14 @@ export function startLegionClaim(deps: {
|
|
|
210
222
|
readonly log: (line: string) => void
|
|
211
223
|
/** Ends the pane's Claude Code, this server's parent, so the daemon launches the claim again. */
|
|
212
224
|
readonly stop: () => void
|
|
225
|
+
/** Registers the step that takes this session's Envoy name, to be run once a turn of this
|
|
226
|
+
* session has started: the channel server holds it in a slot the phase hook's
|
|
227
|
+
* `UserPromptSubmit` calls, the only sight this process has of a turn beginning
|
|
228
|
+
* (`./legion-phase-hook`). It is called once the boot has registered, and a prompt submitted
|
|
229
|
+
* before that — the bridge's seeding `/rename`, which runs before any claim exists — runs
|
|
230
|
+
* nothing, so the name is never taken ahead of the daemon's task
|
|
231
|
+
* (`src/envoy-channel-server.ts`). */
|
|
232
|
+
readonly onFirstTurn: (claim: () => void) => void
|
|
213
233
|
/**
|
|
214
234
|
* How long a claim refused by a standing claim under this very session id keeps asking before
|
|
215
235
|
* it gives up and the pane is stopped: {@link ROLE_CLAIM_WAIT_MS}.
|
|
@@ -217,6 +237,10 @@ export function startLegionClaim(deps: {
|
|
|
217
237
|
readonly roleWaitMs?: number
|
|
218
238
|
/** How long between those attempts: {@link ROLE_CLAIM_RETRY_MS}. */
|
|
219
239
|
readonly roleRetryMs?: number
|
|
240
|
+
/** The pane's own environment, which the first-turn bound is read from
|
|
241
|
+
* (`claimFirstTurnBoundMs`): `process.env` for the server, and a case's own map in a test that
|
|
242
|
+
* will not wait 30 seconds. */
|
|
243
|
+
readonly env?: NodeJS.ProcessEnv
|
|
220
244
|
readonly pollMs?: number
|
|
221
245
|
}): LegionClaim {
|
|
222
246
|
let capability: ClaimCapability | undefined
|
|
@@ -224,7 +248,7 @@ export function startLegionClaim(deps: {
|
|
|
224
248
|
const roleWaitMs = deps.roleWaitMs ?? ROLE_CLAIM_WAIT_MS
|
|
225
249
|
const roleRetryMs = deps.roleRetryMs ?? ROLE_CLAIM_RETRY_MS
|
|
226
250
|
|
|
227
|
-
const boot = async (): Promise<
|
|
251
|
+
const boot = async (): Promise<LegionClaimBoot> => {
|
|
228
252
|
const transcript = await waitForTranscript(
|
|
229
253
|
deps.pane.configDir,
|
|
230
254
|
sessionID,
|
|
@@ -234,7 +258,7 @@ export function startLegionClaim(deps: {
|
|
|
234
258
|
if (deps.pane.launcherSaves) {
|
|
235
259
|
await waitForSavedTranscript(transcript, deps.signal, deps.pollMs)
|
|
236
260
|
}
|
|
237
|
-
await bootLegionClaim({
|
|
261
|
+
return await bootLegionClaim({
|
|
238
262
|
daemon: deps.daemon,
|
|
239
263
|
registration: {
|
|
240
264
|
bootToken: deps.pane.bootToken,
|
|
@@ -289,6 +313,10 @@ export function startLegionClaim(deps: {
|
|
|
289
313
|
}
|
|
290
314
|
await deps.session.rememberRole(role)
|
|
291
315
|
},
|
|
316
|
+
onFirstTurn: deps.onFirstTurn,
|
|
317
|
+
// The pane's own bound, read from its environment as the reminder's four numbers are
|
|
318
|
+
// (`stallLimits` in `./legion-phase-hook`), and warned about on the pane's own log line.
|
|
319
|
+
firstTurnBoundMs: claimFirstTurnBoundMs(deps.env ?? process.env, paneReminderLog(deps.log)),
|
|
292
320
|
onRoleRegained: (listener) => deps.session.onRoleRegained(listener),
|
|
293
321
|
log: deps.log,
|
|
294
322
|
stopping: "stopping the pane so the daemon launches it again",
|
|
@@ -300,11 +328,20 @@ export function startLegionClaim(deps: {
|
|
|
300
328
|
})
|
|
301
329
|
}
|
|
302
330
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
)
|
|
331
|
+
// A boot that failed before a registration claims nothing, and says so with a `claimed` that
|
|
332
|
+
// is already settled: a caller waiting on the name is not left waiting for a step that is
|
|
333
|
+
// never coming.
|
|
334
|
+
const started = boot().catch((error: unknown): LegionClaimBoot => {
|
|
335
|
+
if (!deps.signal.aborted) {
|
|
336
|
+
deps.log(
|
|
337
|
+
`claim boot failed before a registration; the daemon's registration deadline relaunches the pane: ${messageFor(error)}`,
|
|
338
|
+
)
|
|
339
|
+
}
|
|
340
|
+
return { claimed: Promise.resolve() }
|
|
308
341
|
})
|
|
309
|
-
return {
|
|
342
|
+
return {
|
|
343
|
+
capability: () => capability,
|
|
344
|
+
booted: started.then(() => undefined),
|
|
345
|
+
claimed: started.then((claimBoot) => claimBoot.claimed),
|
|
346
|
+
}
|
|
310
347
|
}
|
package/src/legion-phase-hook.ts
CHANGED
|
@@ -165,6 +165,14 @@ export interface PhaseHookDeps {
|
|
|
165
165
|
* reminder and the recreated-workspace notice both need the claim, and neither is sent before
|
|
166
166
|
* one exists. Never rejects. */
|
|
167
167
|
readonly booted: Promise<void>
|
|
168
|
+
/** A turn of this session has started, whatever started it: the daemon's task, an Envoy
|
|
169
|
+
* delivery, a reminder, a person. The channel server answers it by firing the claim boot's
|
|
170
|
+
* deferred role claim (`startLegionClaim`'s `onFirstTurn`), so the session takes its Envoy
|
|
171
|
+
* name inside a turn that is already running (INFRA-1573). It is called for every
|
|
172
|
+
* `UserPromptSubmit`, and the server decides which of them counts: one before the boot
|
|
173
|
+
* registered its step — the bridge's seeding `/rename` — signals nothing, and one after the
|
|
174
|
+
* name is taken costs nothing. */
|
|
175
|
+
readonly firstTurnStarted: () => void
|
|
168
176
|
/** The daemon's whole state, for the reminder's record check, aborted with `signal` once the
|
|
169
177
|
* check's bound passes (`PhaseReminderDeps.readState`). */
|
|
170
178
|
readonly readState: (signal: AbortSignal) => Promise<LegionState>
|
|
@@ -481,6 +489,13 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
|
|
|
481
489
|
// itself: it is refused, and no state moves, so it cannot zero its own count.
|
|
482
490
|
if (!parsed.success) return { error: PHASE_HOOK_REFUSAL }
|
|
483
491
|
const event = parsed.data
|
|
492
|
+
// Before the gate below, and before anything else this endpoint does: the claim's own
|
|
493
|
+
// first-turn signal is not the reminder's business, and a turn is a turn whether or not a
|
|
494
|
+
// claim has registered yet (the bridge's seeding `/rename` turn runs before one has) and
|
|
495
|
+
// whatever role this pane holds, an architect's included. What a prompt before the boot
|
|
496
|
+
// registered its step comes to is the server's to decide, not this endpoint's: it holds
|
|
497
|
+
// the step the signal runs (`src/envoy-channel-server.ts`).
|
|
498
|
+
if (event.event === "UserPromptSubmit") deps.firstTurnStarted()
|
|
484
499
|
// The same gate as `phaseWorkerSession` in `packages/pi-legion/extensions/legion.ts`: the
|
|
485
500
|
// machine runs for a phase worker whose claim has booted, and for nobody else. The bridge's
|
|
486
501
|
// seeding `/rename` turn is what writes the transcript the claim boot waits for
|