@sjawhar/claude-envoy 1.27.2 → 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/dispatch.js +44 -1
- package/dist/envoy-channel.js +355 -249
- package/dist/session-hook.js +44 -1
- 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/dispatch.js
CHANGED
|
@@ -15492,6 +15492,22 @@ var dispatchToolSpecs = [
|
|
|
15492
15492
|
}),
|
|
15493
15493
|
validation: messageValidation
|
|
15494
15494
|
},
|
|
15495
|
+
{
|
|
15496
|
+
name: "dispatch_send_to_agent",
|
|
15497
|
+
example: {
|
|
15498
|
+
session: "01234567-0000-4000-8000-000000000001",
|
|
15499
|
+
body: "DSP-1: the rota is nowhere written down. Please write it up.",
|
|
15500
|
+
delivery: "aside"
|
|
15501
|
+
},
|
|
15502
|
+
description: "Hand a piece of work to one agent session, in that session's own conversation, which belongs to no " + "issue: the way to reach the agent already on the work - the session holding an issue's claim, or one " + "you are working with. Name the issue in the body, because this message carries none. It is not how " + "you reach a person (dispatch message, or dispatch ask for something only a person can do), and not a " + "note on an issue (dispatch message --issue), which everyone reading that issue sees; this reaches that " + "one session. It spends that session a turn, so send once and read the reply with " + "dispatch read --message <id> rather than sending again. The call is answered once its first delivery " + "attempt has settled. It needs a credential holding the person scope, and one without it is refused " + `403 OAUTH_SCOPE_REQUIRED, naming the scope. ${BODY_BLOCK_RULE}`,
|
|
15503
|
+
arguments: (z) => ({
|
|
15504
|
+
session: z.string({ min: 1 }).describe("The session to send to, by its bare session id. An issue's claim names the session holding it, " + "and dispatch whoami names this session's own."),
|
|
15505
|
+
body: z.string({ min: 1 }).describe(`The words the session reads. Name the issue they are about: this message carries none. ${BODY_BLOCK_RULE}`),
|
|
15506
|
+
delivery: z.enum(["btw", "aside", "steer"]).describe("How the words reach the session: btw waits for its next turn, aside reaches it while a turn " + "runs, and steer goes in as a keystroke at its terminal. A session advertises the modes it " + "takes, and Dispatch sends the mode you name rather than another."),
|
|
15507
|
+
in_reply_to: z.string().describe("Optional id of a message in this same session-to-session conversation, threading this message " + "under it; without it the message starts a conversation of its own.").optional()
|
|
15508
|
+
}),
|
|
15509
|
+
strict: true
|
|
15510
|
+
},
|
|
15495
15511
|
{
|
|
15496
15512
|
name: "dispatch_doc_edit",
|
|
15497
15513
|
example: {
|
|
@@ -18257,6 +18273,9 @@ class DispatchClient {
|
|
|
18257
18273
|
async message(issue, input) {
|
|
18258
18274
|
return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
|
|
18259
18275
|
}
|
|
18276
|
+
async agentMessage(sessionId, input) {
|
|
18277
|
+
return this.#json("POST", ["api", "v1", "agents", sessionId, "messages"], input);
|
|
18278
|
+
}
|
|
18260
18279
|
async messageReply(id, input, options = {}) {
|
|
18261
18280
|
return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
|
|
18262
18281
|
}
|
|
@@ -21470,6 +21489,9 @@ function itemBlockOf(value) {
|
|
|
21470
21489
|
function article(kind) {
|
|
21471
21490
|
return kind === "ask" ? "an ask" : `a ${kind}`;
|
|
21472
21491
|
}
|
|
21492
|
+
function conversationReadBack(messageId) {
|
|
21493
|
+
return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
|
|
21494
|
+
}
|
|
21473
21495
|
function replyBlockProblem(field, kind, value) {
|
|
21474
21496
|
if (!/^dispatch:\/\/[^#]*#b-/.test(value))
|
|
21475
21497
|
return;
|
|
@@ -23889,7 +23911,7 @@ async function executeDispatchTool(input) {
|
|
|
23889
23911
|
details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
|
|
23890
23912
|
};
|
|
23891
23913
|
}
|
|
23892
|
-
const readBack =
|
|
23914
|
+
const readBack = conversationReadBack(inReplyTo);
|
|
23893
23915
|
const parent = reply.in_reply_to ?? undefined;
|
|
23894
23916
|
const follows = parent === inReplyTo ? undefined : parent;
|
|
23895
23917
|
return {
|
|
@@ -23925,6 +23947,27 @@ async function executeDispatchTool(input) {
|
|
|
23925
23947
|
}
|
|
23926
23948
|
};
|
|
23927
23949
|
}
|
|
23950
|
+
case "dispatch_send_to_agent": {
|
|
23951
|
+
const session = stringArg(args, "session");
|
|
23952
|
+
const inReplyTo = optionalString(args, "in_reply_to");
|
|
23953
|
+
const message = await client.agentMessage(session, {
|
|
23954
|
+
body: stringArg(args, "body"),
|
|
23955
|
+
delivery: stringArg(args, "delivery"),
|
|
23956
|
+
...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
|
|
23957
|
+
});
|
|
23958
|
+
const attempt = message.deliveries?.at(-1);
|
|
23959
|
+
const readBack = conversationReadBack(message.id);
|
|
23960
|
+
const arrival = attempt === undefined ? "Dispatch recorded no delivery attempt for it" : attempt.state === "failed" ? `its delivery failed: ${attempt.error ?? "the listener gave no reason"}` : attempt.state === "pending" ? "its delivery is still on its way" : `it reached that session as ${attempt.delivery}`;
|
|
23961
|
+
return {
|
|
23962
|
+
text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
|
|
23963
|
+
details: {
|
|
23964
|
+
session,
|
|
23965
|
+
message: message.id,
|
|
23966
|
+
...attempt === undefined ? {} : { delivery: attempt.state },
|
|
23967
|
+
...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
|
|
23968
|
+
}
|
|
23969
|
+
};
|
|
23970
|
+
}
|
|
23928
23971
|
case "dispatch_doc_edit": {
|
|
23929
23972
|
const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
|
|
23930
23973
|
const ops = args.ops;
|
package/dist/envoy-channel.js
CHANGED
|
@@ -37141,6 +37141,22 @@ var dispatchToolSpecs = [
|
|
|
37141
37141
|
}),
|
|
37142
37142
|
validation: messageValidation
|
|
37143
37143
|
},
|
|
37144
|
+
{
|
|
37145
|
+
name: "dispatch_send_to_agent",
|
|
37146
|
+
example: {
|
|
37147
|
+
session: "01234567-0000-4000-8000-000000000001",
|
|
37148
|
+
body: "DSP-1: the rota is nowhere written down. Please write it up.",
|
|
37149
|
+
delivery: "aside"
|
|
37150
|
+
},
|
|
37151
|
+
description: "Hand a piece of work to one agent session, in that session's own conversation, which belongs to no " + "issue: the way to reach the agent already on the work - the session holding an issue's claim, or one " + "you are working with. Name the issue in the body, because this message carries none. It is not how " + "you reach a person (dispatch message, or dispatch ask for something only a person can do), and not a " + "note on an issue (dispatch message --issue), which everyone reading that issue sees; this reaches that " + "one session. It spends that session a turn, so send once and read the reply with " + "dispatch read --message <id> rather than sending again. The call is answered once its first delivery " + "attempt has settled. It needs a credential holding the person scope, and one without it is refused " + `403 OAUTH_SCOPE_REQUIRED, naming the scope. ${BODY_BLOCK_RULE}`,
|
|
37152
|
+
arguments: (z) => ({
|
|
37153
|
+
session: z.string({ min: 1 }).describe("The session to send to, by its bare session id. An issue's claim names the session holding it, " + "and dispatch whoami names this session's own."),
|
|
37154
|
+
body: z.string({ min: 1 }).describe(`The words the session reads. Name the issue they are about: this message carries none. ${BODY_BLOCK_RULE}`),
|
|
37155
|
+
delivery: z.enum(["btw", "aside", "steer"]).describe("How the words reach the session: btw waits for its next turn, aside reaches it while a turn " + "runs, and steer goes in as a keystroke at its terminal. A session advertises the modes it " + "takes, and Dispatch sends the mode you name rather than another."),
|
|
37156
|
+
in_reply_to: z.string().describe("Optional id of a message in this same session-to-session conversation, threading this message " + "under it; without it the message starts a conversation of its own.").optional()
|
|
37157
|
+
}),
|
|
37158
|
+
strict: true
|
|
37159
|
+
},
|
|
37144
37160
|
{
|
|
37145
37161
|
name: "dispatch_doc_edit",
|
|
37146
37162
|
example: {
|
|
@@ -42742,6 +42758,9 @@ class DispatchClient {
|
|
|
42742
42758
|
async message(issue, input) {
|
|
42743
42759
|
return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
|
|
42744
42760
|
}
|
|
42761
|
+
async agentMessage(sessionId, input) {
|
|
42762
|
+
return this.#json("POST", ["api", "v1", "agents", sessionId, "messages"], input);
|
|
42763
|
+
}
|
|
42745
42764
|
async messageReply(id, input, options = {}) {
|
|
42746
42765
|
return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
|
|
42747
42766
|
}
|
|
@@ -48390,6 +48409,9 @@ function itemBlockOf(value) {
|
|
|
48390
48409
|
function article(kind) {
|
|
48391
48410
|
return kind === "ask" ? "an ask" : `a ${kind}`;
|
|
48392
48411
|
}
|
|
48412
|
+
function conversationReadBack(messageId) {
|
|
48413
|
+
return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
|
|
48414
|
+
}
|
|
48393
48415
|
function replyBlockProblem(field, kind, value) {
|
|
48394
48416
|
if (!/^dispatch:\/\/[^#]*#b-/.test(value))
|
|
48395
48417
|
return;
|
|
@@ -50809,7 +50831,7 @@ async function executeDispatchTool(input) {
|
|
|
50809
50831
|
details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
|
|
50810
50832
|
};
|
|
50811
50833
|
}
|
|
50812
|
-
const readBack =
|
|
50834
|
+
const readBack = conversationReadBack(inReplyTo);
|
|
50813
50835
|
const parent = reply.in_reply_to ?? undefined;
|
|
50814
50836
|
const follows = parent === inReplyTo ? undefined : parent;
|
|
50815
50837
|
return {
|
|
@@ -50845,6 +50867,27 @@ async function executeDispatchTool(input) {
|
|
|
50845
50867
|
}
|
|
50846
50868
|
};
|
|
50847
50869
|
}
|
|
50870
|
+
case "dispatch_send_to_agent": {
|
|
50871
|
+
const session = stringArg(args, "session");
|
|
50872
|
+
const inReplyTo = optionalString(args, "in_reply_to");
|
|
50873
|
+
const message = await client.agentMessage(session, {
|
|
50874
|
+
body: stringArg(args, "body"),
|
|
50875
|
+
delivery: stringArg(args, "delivery"),
|
|
50876
|
+
...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
|
|
50877
|
+
});
|
|
50878
|
+
const attempt = message.deliveries?.at(-1);
|
|
50879
|
+
const readBack = conversationReadBack(message.id);
|
|
50880
|
+
const arrival = attempt === undefined ? "Dispatch recorded no delivery attempt for it" : attempt.state === "failed" ? `its delivery failed: ${attempt.error ?? "the listener gave no reason"}` : attempt.state === "pending" ? "its delivery is still on its way" : `it reached that session as ${attempt.delivery}`;
|
|
50881
|
+
return {
|
|
50882
|
+
text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
|
|
50883
|
+
details: {
|
|
50884
|
+
session,
|
|
50885
|
+
message: message.id,
|
|
50886
|
+
...attempt === undefined ? {} : { delivery: attempt.state },
|
|
50887
|
+
...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
|
|
50888
|
+
}
|
|
50889
|
+
};
|
|
50890
|
+
}
|
|
50848
50891
|
case "dispatch_doc_edit": {
|
|
50849
50892
|
const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
|
|
50850
50893
|
const ops = args.ops;
|
|
@@ -55348,7 +55391,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
|
|
|
55348
55391
|
|
|
55349
55392
|
// package.json
|
|
55350
55393
|
var name = "@sjawhar/claude-envoy";
|
|
55351
|
-
var version2 = "1.
|
|
55394
|
+
var version2 = "1.28.1";
|
|
55352
55395
|
var legion = {
|
|
55353
55396
|
daemonApiVersion: 59
|
|
55354
55397
|
};
|
|
@@ -56545,9 +56588,59 @@ function installedPluginVersion(bundlePath) {
|
|
|
56545
56588
|
|
|
56546
56589
|
// src/legion-claim.ts
|
|
56547
56590
|
import { readdir as readdir2, stat as stat2 } from "fs/promises";
|
|
56548
|
-
import { join as
|
|
56591
|
+
import { join as join9 } from "path";
|
|
56549
56592
|
import { setTimeout as delay } from "timers/promises";
|
|
56550
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
|
+
|
|
56551
56644
|
// ../pi-shared/src/legion-claim-core.ts
|
|
56552
56645
|
async function bootLegionClaim(host) {
|
|
56553
56646
|
const { daemon } = host;
|
|
@@ -56561,8 +56654,9 @@ async function bootLegionClaim(host) {
|
|
|
56561
56654
|
if (error.status < 400 || error.status >= 500)
|
|
56562
56655
|
throw error;
|
|
56563
56656
|
host.stop();
|
|
56564
|
-
return;
|
|
56657
|
+
return { claimed: Promise.resolve() };
|
|
56565
56658
|
}
|
|
56659
|
+
const firstTurn = listenForFirstTurn(host);
|
|
56566
56660
|
try {
|
|
56567
56661
|
await host.afterRegister?.(claim);
|
|
56568
56662
|
host.setCapability({
|
|
@@ -56575,7 +56669,6 @@ async function bootLegionClaim(host) {
|
|
|
56575
56669
|
secret: claim.secret,
|
|
56576
56670
|
promptAgents: claim.promptAgents
|
|
56577
56671
|
});
|
|
56578
|
-
await host.claimRole(claim.claimToken);
|
|
56579
56672
|
const ready = {
|
|
56580
56673
|
claimToken: claim.claimToken,
|
|
56581
56674
|
sessionId: host.registration.sessionId,
|
|
@@ -56594,217 +56687,58 @@ async function bootLegionClaim(host) {
|
|
|
56594
56687
|
}
|
|
56595
56688
|
});
|
|
56596
56689
|
} catch (error) {
|
|
56597
|
-
host
|
|
56598
|
-
|
|
56599
|
-
}
|
|
56600
|
-
}
|
|
56601
|
-
|
|
56602
|
-
// src/legion-claim.ts
|
|
56603
|
-
function legionPane(env) {
|
|
56604
|
-
const pointer = env["LEGION_BOOT_TOKEN_FILE"];
|
|
56605
|
-
if (pointer === undefined && configuredValue(env["LEGION_BOOT_TOKEN"]) === undefined) {
|
|
56606
|
-
return;
|
|
56607
|
-
}
|
|
56608
|
-
const required = (key) => {
|
|
56609
|
-
const value = configuredValue(env[key]);
|
|
56610
|
-
if (value === undefined) {
|
|
56611
|
-
throw new Error(`${key} is required for Legion: the pane carries a boot token`);
|
|
56612
|
-
}
|
|
56613
|
-
return value;
|
|
56614
|
-
};
|
|
56615
|
-
return {
|
|
56616
|
-
daemonUrl: required("LEGION_DAEMON_URL"),
|
|
56617
|
-
configDir: required("CLAUDE_CONFIG_DIR"),
|
|
56618
|
-
bootToken: pointer === undefined ? required("LEGION_BOOT_TOKEN") : readSecretFile("LEGION_BOOT_TOKEN_FILE", pointer),
|
|
56619
|
-
launcherSaves: configuredValue(env["LEGION_CLAUDE_SESSION_ID"]) !== undefined
|
|
56620
|
-
};
|
|
56621
|
-
}
|
|
56622
|
-
function logLegion(line) {
|
|
56623
|
-
process.stderr.write(`[legion] ${line}
|
|
56624
|
-
`);
|
|
56625
|
-
}
|
|
56626
|
-
function endPane() {
|
|
56627
|
-
process.kill(process.ppid, "SIGTERM");
|
|
56628
|
-
}
|
|
56629
|
-
function stopPane(why) {
|
|
56630
|
-
logLegion(`${why}; stopping the pane so the daemon launches it again`);
|
|
56631
|
-
endPane();
|
|
56632
|
-
}
|
|
56633
|
-
async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
|
|
56634
|
-
const projects = join8(configDir, "projects");
|
|
56635
|
-
const name = `${sessionID}.jsonl`;
|
|
56636
|
-
for (;; ) {
|
|
56637
|
-
signal.throwIfAborted();
|
|
56638
|
-
for (const directory of await readdir2(projects).catch(() => [])) {
|
|
56639
|
-
const file = join8(projects, directory, name);
|
|
56640
|
-
if (await isFile(file))
|
|
56641
|
-
return file;
|
|
56642
|
-
}
|
|
56643
|
-
await delay(pollMs, undefined, { signal });
|
|
56690
|
+
stopAfterRegistration(host, claim.claimToken, error);
|
|
56691
|
+
return { claimed: Promise.resolve() };
|
|
56644
56692
|
}
|
|
56693
|
+
return { claimed: claimRoleAtFirstTurn(host, claim.claimToken, firstTurn) };
|
|
56645
56694
|
}
|
|
56646
|
-
|
|
56647
|
-
|
|
56648
|
-
|
|
56649
|
-
for (;; ) {
|
|
56650
|
-
signal.throwIfAborted();
|
|
56651
|
-
if (await isFile(marker))
|
|
56652
|
-
return;
|
|
56653
|
-
await delay(pollMs, undefined, { signal });
|
|
56654
|
-
}
|
|
56695
|
+
function stopAfterRegistration(host, role, error) {
|
|
56696
|
+
host.log(`claim boot failed after claims/register registered ${role}; ${host.stopping}: ${messageFor(error)}`);
|
|
56697
|
+
host.stop();
|
|
56655
56698
|
}
|
|
56656
|
-
function
|
|
56657
|
-
|
|
56658
|
-
|
|
56659
|
-
|
|
56660
|
-
|
|
56661
|
-
|
|
56662
|
-
let capability;
|
|
56663
|
-
const { sessionID } = deps;
|
|
56664
|
-
const roleWaitMs = deps.roleWaitMs ?? ROLE_CLAIM_WAIT_MS;
|
|
56665
|
-
const roleRetryMs = deps.roleRetryMs ?? ROLE_CLAIM_RETRY_MS;
|
|
56666
|
-
const boot = async () => {
|
|
56667
|
-
const transcript = await waitForTranscript(deps.pane.configDir, sessionID, deps.signal, deps.pollMs);
|
|
56668
|
-
if (deps.pane.launcherSaves) {
|
|
56669
|
-
await waitForSavedTranscript(transcript, deps.signal, deps.pollMs);
|
|
56670
|
-
}
|
|
56671
|
-
await bootLegionClaim({
|
|
56672
|
-
daemon: deps.daemon,
|
|
56673
|
-
registration: {
|
|
56674
|
-
bootToken: deps.pane.bootToken,
|
|
56675
|
-
sessionId: sessionID,
|
|
56676
|
-
ompSessionFile: transcript,
|
|
56677
|
-
agentId: sessionID,
|
|
56678
|
-
pluginContract: legion.daemonApiVersion
|
|
56679
|
-
},
|
|
56680
|
-
setCapability: (registered) => {
|
|
56681
|
-
capability = registered;
|
|
56682
|
-
},
|
|
56683
|
-
claimRole: async (role) => {
|
|
56684
|
-
const deadline = Date.now() + roleWaitMs;
|
|
56685
|
-
let waited = false;
|
|
56686
|
-
for (;; ) {
|
|
56687
|
-
const claimed = await deps.client.setRole({
|
|
56688
|
-
sessionID,
|
|
56689
|
-
role,
|
|
56690
|
-
soft: true,
|
|
56691
|
-
clientInstanceID: deps.clientInstanceID
|
|
56692
|
-
});
|
|
56693
|
-
if (claimed.claimed)
|
|
56694
|
-
break;
|
|
56695
|
-
if (claimed.holder !== sessionID) {
|
|
56696
|
-
throw new Error(`Envoy role ${role} is held by live session ${claimed.holder}`);
|
|
56697
|
-
}
|
|
56698
|
-
const left = deadline - Date.now();
|
|
56699
|
-
if (left <= 0) {
|
|
56700
|
-
throw new Error(`Envoy role ${role} is still claimed under this session by another process after ${roleWaitMs} ms of asking`);
|
|
56701
|
-
}
|
|
56702
|
-
if (!waited) {
|
|
56703
|
-
waited = true;
|
|
56704
|
-
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`);
|
|
56705
|
-
}
|
|
56706
|
-
await delay(Math.min(roleRetryMs, left), undefined, { signal: deps.signal });
|
|
56707
|
-
}
|
|
56708
|
-
await deps.session.rememberRole(role);
|
|
56709
|
-
},
|
|
56710
|
-
onRoleRegained: (listener) => deps.session.onRoleRegained(listener),
|
|
56711
|
-
log: deps.log,
|
|
56712
|
-
stopping: "stopping the pane so the daemon launches it again",
|
|
56713
|
-
stop: () => {
|
|
56714
|
-
if (!deps.signal.aborted)
|
|
56715
|
-
deps.stop();
|
|
56716
|
-
}
|
|
56717
|
-
});
|
|
56718
|
-
};
|
|
56719
|
-
const booted = boot().catch((error) => {
|
|
56720
|
-
if (deps.signal.aborted)
|
|
56721
|
-
return;
|
|
56722
|
-
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?.();
|
|
56723
56705
|
});
|
|
56724
|
-
return
|
|
56725
|
-
|
|
56726
|
-
|
|
56727
|
-
|
|
56728
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
56729
|
-
import { createConnection } from "net";
|
|
56730
|
-
var INBOX_VARIABLE = "LEGION_CLAUDE_INBOX";
|
|
56731
|
-
var INBOX_CAPABILITIES = [
|
|
56732
|
-
"aside",
|
|
56733
|
-
"steer"
|
|
56734
|
-
];
|
|
56735
|
-
function createInboxNotifier(socketPath) {
|
|
56736
|
-
let socket;
|
|
56737
|
-
let buffered = "";
|
|
56738
|
-
const waiting = [];
|
|
56739
|
-
const fail = (error) => {
|
|
56740
|
-
for (const pending of waiting.splice(0))
|
|
56741
|
-
pending.settle.reject(error);
|
|
56706
|
+
return (step) => {
|
|
56707
|
+
claim = step;
|
|
56708
|
+
if (started)
|
|
56709
|
+
step();
|
|
56742
56710
|
};
|
|
56743
|
-
|
|
56744
|
-
|
|
56745
|
-
|
|
56746
|
-
|
|
56747
|
-
|
|
56748
|
-
|
|
56749
|
-
parsed = JSON.parse(line);
|
|
56750
|
-
} catch {
|
|
56751
|
-
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)
|
|
56752
56717
|
return;
|
|
56753
|
-
|
|
56754
|
-
|
|
56755
|
-
|
|
56756
|
-
|
|
56757
|
-
|
|
56758
|
-
|
|
56759
|
-
|
|
56760
|
-
const connected = () => {
|
|
56761
|
-
if (socket !== undefined && !socket.destroyed)
|
|
56762
|
-
return socket;
|
|
56763
|
-
buffered = "";
|
|
56764
|
-
const opened = createConnection(socketPath);
|
|
56765
|
-
opened.setEncoding("utf8");
|
|
56766
|
-
opened.on("data", (chunk) => {
|
|
56767
|
-
buffered += chunk;
|
|
56768
|
-
for (let end = buffered.indexOf(`
|
|
56769
|
-
`);end >= 0; end = buffered.indexOf(`
|
|
56770
|
-
`)) {
|
|
56771
|
-
const line = buffered.slice(0, end);
|
|
56772
|
-
buffered = buffered.slice(end + 1);
|
|
56773
|
-
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);
|
|
56774
56725
|
}
|
|
56775
|
-
|
|
56776
|
-
|
|
56777
|
-
opened.on("close", () => {
|
|
56778
|
-
fail(new Error(`the Legion inbox ${socketPath} closed before it answered`));
|
|
56779
|
-
if (socket === opened)
|
|
56780
|
-
socket = undefined;
|
|
56781
|
-
});
|
|
56782
|
-
socket = opened;
|
|
56783
|
-
return opened;
|
|
56784
|
-
};
|
|
56785
|
-
return {
|
|
56786
|
-
notification(notification) {
|
|
56787
|
-
const id = notification.eventId ?? randomUUID2();
|
|
56788
|
-
const settle = Promise.withResolvers();
|
|
56789
|
-
waiting.push({ id, settle });
|
|
56790
|
-
connected().write(`${JSON.stringify({
|
|
56791
|
-
id,
|
|
56792
|
-
content: notification.content,
|
|
56793
|
-
...notification.blocks === undefined ? {} : { blocks: notification.blocks }
|
|
56794
|
-
})}
|
|
56795
|
-
`);
|
|
56796
|
-
return settle.promise;
|
|
56797
|
-
}
|
|
56726
|
+
done.resolve();
|
|
56727
|
+
})();
|
|
56798
56728
|
};
|
|
56729
|
+
const bound = setTimeout(claim, host.firstTurnBoundMs);
|
|
56730
|
+
bound.unref?.();
|
|
56731
|
+
firstTurn(claim);
|
|
56732
|
+
return done.promise;
|
|
56799
56733
|
}
|
|
56800
56734
|
|
|
56801
56735
|
// src/legion-phase-hook.ts
|
|
56802
|
-
import { randomUUID as
|
|
56736
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
56803
56737
|
import { readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
|
|
56804
|
-
import { dirname as dirname3, join as
|
|
56738
|
+
import { dirname as dirname3, join as join8 } from "path";
|
|
56805
56739
|
|
|
56806
56740
|
// ../pi-shared/src/phase-reminder.ts
|
|
56807
|
-
import { randomUUID as
|
|
56741
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
56808
56742
|
|
|
56809
56743
|
// ../pi-shared/src/phase-stall.ts
|
|
56810
56744
|
var WAITING_REPLY = /^\W*WAITING\b/m;
|
|
@@ -56993,7 +56927,7 @@ function createPhaseReminder(deps) {
|
|
|
56993
56927
|
});
|
|
56994
56928
|
return;
|
|
56995
56929
|
}
|
|
56996
|
-
reportKey ??=
|
|
56930
|
+
reportKey ??= randomUUID2();
|
|
56997
56931
|
const key = reportKey;
|
|
56998
56932
|
writeEntry();
|
|
56999
56933
|
const phase = record?.phase ?? "unknown";
|
|
@@ -57179,49 +57113,6 @@ function sessionActivityRequest(input) {
|
|
|
57179
57113
|
};
|
|
57180
57114
|
}
|
|
57181
57115
|
|
|
57182
|
-
// ../pi-shared/src/stall-limits.ts
|
|
57183
|
-
var DEFAULT_STALL_LIMITS = {
|
|
57184
|
-
reminderMs: 300000,
|
|
57185
|
-
waitingMs: 900000,
|
|
57186
|
-
resumeMs: 120000,
|
|
57187
|
-
architectAfter: 3,
|
|
57188
|
-
callGraceMs: 300000,
|
|
57189
|
-
callBoundMs: 3600000,
|
|
57190
|
-
stepMs: 120000
|
|
57191
|
-
};
|
|
57192
|
-
var LONG_CALL_BOUND_MS = 14400000;
|
|
57193
|
-
var LONG_CALL_BOUND_ROLES = [
|
|
57194
|
-
"implementer",
|
|
57195
|
-
"reviewer"
|
|
57196
|
-
];
|
|
57197
|
-
function defaultCallBoundMs(role) {
|
|
57198
|
-
return role !== undefined && LONG_CALL_BOUND_ROLES.includes(role) ? LONG_CALL_BOUND_MS : DEFAULT_STALL_LIMITS.callBoundMs;
|
|
57199
|
-
}
|
|
57200
|
-
function integerSetting(env, log, name, fallback, least) {
|
|
57201
|
-
const raw = env[name];
|
|
57202
|
-
if (raw === undefined)
|
|
57203
|
-
return fallback;
|
|
57204
|
-
const value = raw.trim() === "" ? Number.NaN : Number(raw);
|
|
57205
|
-
if (!Number.isInteger(value) || value < least) {
|
|
57206
|
-
log.warn(`legion: ${name} is not an integer of ${least} or more; using ${fallback}`, {
|
|
57207
|
-
value: raw
|
|
57208
|
-
});
|
|
57209
|
-
return fallback;
|
|
57210
|
-
}
|
|
57211
|
-
return value;
|
|
57212
|
-
}
|
|
57213
|
-
function stallLimits(env, log, role) {
|
|
57214
|
-
return {
|
|
57215
|
-
reminderMs: integerSetting(env, log, "LEGION_STALL_REMINDER_MS", DEFAULT_STALL_LIMITS.reminderMs, 0),
|
|
57216
|
-
waitingMs: integerSetting(env, log, "LEGION_STALL_WAITING_MS", DEFAULT_STALL_LIMITS.waitingMs, 0),
|
|
57217
|
-
resumeMs: integerSetting(env, log, "LEGION_STALL_RESUME_MS", DEFAULT_STALL_LIMITS.resumeMs, 0),
|
|
57218
|
-
architectAfter: integerSetting(env, log, "LEGION_STALL_ARCHITECT_AFTER", DEFAULT_STALL_LIMITS.architectAfter, 2),
|
|
57219
|
-
callGraceMs: integerSetting(env, log, "LEGION_STALL_CALL_GRACE_MS", DEFAULT_STALL_LIMITS.callGraceMs, 0),
|
|
57220
|
-
callBoundMs: integerSetting(env, log, "LEGION_STALL_CALL_BOUND_MS", defaultCallBoundMs(role), 0),
|
|
57221
|
-
stepMs: integerSetting(env, log, "LEGION_STALL_STEP_MS", DEFAULT_STALL_LIMITS.stepMs, 0)
|
|
57222
|
-
};
|
|
57223
|
-
}
|
|
57224
|
-
|
|
57225
57116
|
// ../pi-shared/src/workspace-recreated.ts
|
|
57226
57117
|
var WORKSPACE_RECREATED_VARIABLE = "LEGION_WORKSPACE_RECREATED";
|
|
57227
57118
|
var WORKSPACE_RESTORED_VARIABLE = "LEGION_WORKSPACE_RESTORED";
|
|
@@ -57284,7 +57175,7 @@ function phaseHookToolDefinition() {
|
|
|
57284
57175
|
};
|
|
57285
57176
|
}
|
|
57286
57177
|
function phaseStallFile(configDir, sessionID) {
|
|
57287
|
-
return
|
|
57178
|
+
return join8(configDir, `legion-phase-stall-${sessionID}.json`);
|
|
57288
57179
|
}
|
|
57289
57180
|
function paneReminderLog(write) {
|
|
57290
57181
|
const line = (level, message, context) => {
|
|
@@ -57337,7 +57228,7 @@ function readPhaseStallRecord(file, log) {
|
|
|
57337
57228
|
};
|
|
57338
57229
|
}
|
|
57339
57230
|
function writePhaseStallRecord(file, entry, recreatedNoticeSent, log) {
|
|
57340
|
-
const temporary =
|
|
57231
|
+
const temporary = join8(dirname3(file), `.legion-phase-stall-${randomUUID3()}`);
|
|
57341
57232
|
try {
|
|
57342
57233
|
writeFileSync4(temporary, JSON.stringify({ ...entry, ...recreatedNoticeSent ? { recreatedNoticeSent } : {} }), { mode: 384 });
|
|
57343
57234
|
renameSync3(temporary, file);
|
|
@@ -57462,6 +57353,8 @@ function createPhaseHookEndpoint(deps) {
|
|
|
57462
57353
|
if (!parsed.success)
|
|
57463
57354
|
return { error: PHASE_HOOK_REFUSAL };
|
|
57464
57355
|
const event = parsed.data;
|
|
57356
|
+
if (event.event === "UserPromptSubmit")
|
|
57357
|
+
deps.firstTurnStarted();
|
|
57465
57358
|
const claim = deps.claim();
|
|
57466
57359
|
if (claim === undefined || claim.role === "architect")
|
|
57467
57360
|
return {};
|
|
@@ -57506,6 +57399,214 @@ function createPhaseHookEndpoint(deps) {
|
|
|
57506
57399
|
};
|
|
57507
57400
|
}
|
|
57508
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
|
+
|
|
57509
57610
|
// ../pi-shared/src/legion-phase-ops.ts
|
|
57510
57611
|
var PHASE_OPS = [
|
|
57511
57612
|
"read_record",
|
|
@@ -60077,10 +60178,12 @@ async function runEnvoyChannelServer() {
|
|
|
60077
60178
|
const daemon = pane === undefined ? undefined : createLegionDaemonClient(pane.daemonUrl);
|
|
60078
60179
|
const phaseLog = paneReminderLog(logLegion);
|
|
60079
60180
|
const claimBooted = Promise.withResolvers();
|
|
60181
|
+
let reportFirstTurn;
|
|
60080
60182
|
const phaseHook = pane === undefined || daemon === undefined ? undefined : createPhaseHookEndpoint({
|
|
60081
60183
|
stateFile: phaseStallFile(pane.configDir, identity.id),
|
|
60082
60184
|
claim: () => claim?.capability(),
|
|
60083
60185
|
booted: claimBooted.promise,
|
|
60186
|
+
firstTurnStarted: () => reportFirstTurn?.(),
|
|
60084
60187
|
readState: (signal) => daemon.state({ signal }),
|
|
60085
60188
|
reportActivity: (input) => daemon.activity(input),
|
|
60086
60189
|
inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
|
|
@@ -60277,7 +60380,10 @@ async function runEnvoyChannelServer() {
|
|
|
60277
60380
|
session,
|
|
60278
60381
|
signal: booting.signal,
|
|
60279
60382
|
log: logLegion,
|
|
60280
|
-
stop: endPane
|
|
60383
|
+
stop: endPane,
|
|
60384
|
+
onFirstTurn: (started) => {
|
|
60385
|
+
reportFirstTurn = started;
|
|
60386
|
+
}
|
|
60281
60387
|
});
|
|
60282
60388
|
claim.booted.then(claimBooted.resolve);
|
|
60283
60389
|
}
|
package/dist/session-hook.js
CHANGED
|
@@ -14491,6 +14491,22 @@ var dispatchToolSpecs = [
|
|
|
14491
14491
|
}),
|
|
14492
14492
|
validation: messageValidation
|
|
14493
14493
|
},
|
|
14494
|
+
{
|
|
14495
|
+
name: "dispatch_send_to_agent",
|
|
14496
|
+
example: {
|
|
14497
|
+
session: "01234567-0000-4000-8000-000000000001",
|
|
14498
|
+
body: "DSP-1: the rota is nowhere written down. Please write it up.",
|
|
14499
|
+
delivery: "aside"
|
|
14500
|
+
},
|
|
14501
|
+
description: "Hand a piece of work to one agent session, in that session's own conversation, which belongs to no " + "issue: the way to reach the agent already on the work - the session holding an issue's claim, or one " + "you are working with. Name the issue in the body, because this message carries none. It is not how " + "you reach a person (dispatch message, or dispatch ask for something only a person can do), and not a " + "note on an issue (dispatch message --issue), which everyone reading that issue sees; this reaches that " + "one session. It spends that session a turn, so send once and read the reply with " + "dispatch read --message <id> rather than sending again. The call is answered once its first delivery " + "attempt has settled. It needs a credential holding the person scope, and one without it is refused " + `403 OAUTH_SCOPE_REQUIRED, naming the scope. ${BODY_BLOCK_RULE}`,
|
|
14502
|
+
arguments: (z) => ({
|
|
14503
|
+
session: z.string({ min: 1 }).describe("The session to send to, by its bare session id. An issue's claim names the session holding it, " + "and dispatch whoami names this session's own."),
|
|
14504
|
+
body: z.string({ min: 1 }).describe(`The words the session reads. Name the issue they are about: this message carries none. ${BODY_BLOCK_RULE}`),
|
|
14505
|
+
delivery: z.enum(["btw", "aside", "steer"]).describe("How the words reach the session: btw waits for its next turn, aside reaches it while a turn " + "runs, and steer goes in as a keystroke at its terminal. A session advertises the modes it " + "takes, and Dispatch sends the mode you name rather than another."),
|
|
14506
|
+
in_reply_to: z.string().describe("Optional id of a message in this same session-to-session conversation, threading this message " + "under it; without it the message starts a conversation of its own.").optional()
|
|
14507
|
+
}),
|
|
14508
|
+
strict: true
|
|
14509
|
+
},
|
|
14494
14510
|
{
|
|
14495
14511
|
name: "dispatch_doc_edit",
|
|
14496
14512
|
example: {
|
|
@@ -17261,6 +17277,9 @@ class DispatchClient {
|
|
|
17261
17277
|
async message(issue, input) {
|
|
17262
17278
|
return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
|
|
17263
17279
|
}
|
|
17280
|
+
async agentMessage(sessionId, input) {
|
|
17281
|
+
return this.#json("POST", ["api", "v1", "agents", sessionId, "messages"], input);
|
|
17282
|
+
}
|
|
17264
17283
|
async messageReply(id, input, options = {}) {
|
|
17265
17284
|
return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
|
|
17266
17285
|
}
|
|
@@ -20474,6 +20493,9 @@ function itemBlockOf(value) {
|
|
|
20474
20493
|
function article(kind) {
|
|
20475
20494
|
return kind === "ask" ? "an ask" : `a ${kind}`;
|
|
20476
20495
|
}
|
|
20496
|
+
function conversationReadBack(messageId) {
|
|
20497
|
+
return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
|
|
20498
|
+
}
|
|
20477
20499
|
function replyBlockProblem(field, kind, value) {
|
|
20478
20500
|
if (!/^dispatch:\/\/[^#]*#b-/.test(value))
|
|
20479
20501
|
return;
|
|
@@ -22893,7 +22915,7 @@ async function executeDispatchTool(input) {
|
|
|
22893
22915
|
details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
|
|
22894
22916
|
};
|
|
22895
22917
|
}
|
|
22896
|
-
const readBack =
|
|
22918
|
+
const readBack = conversationReadBack(inReplyTo);
|
|
22897
22919
|
const parent = reply.in_reply_to ?? undefined;
|
|
22898
22920
|
const follows = parent === inReplyTo ? undefined : parent;
|
|
22899
22921
|
return {
|
|
@@ -22929,6 +22951,27 @@ async function executeDispatchTool(input) {
|
|
|
22929
22951
|
}
|
|
22930
22952
|
};
|
|
22931
22953
|
}
|
|
22954
|
+
case "dispatch_send_to_agent": {
|
|
22955
|
+
const session = stringArg(args, "session");
|
|
22956
|
+
const inReplyTo = optionalString(args, "in_reply_to");
|
|
22957
|
+
const message = await client.agentMessage(session, {
|
|
22958
|
+
body: stringArg(args, "body"),
|
|
22959
|
+
delivery: stringArg(args, "delivery"),
|
|
22960
|
+
...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
|
|
22961
|
+
});
|
|
22962
|
+
const attempt = message.deliveries?.at(-1);
|
|
22963
|
+
const readBack = conversationReadBack(message.id);
|
|
22964
|
+
const arrival = attempt === undefined ? "Dispatch recorded no delivery attempt for it" : attempt.state === "failed" ? `its delivery failed: ${attempt.error ?? "the listener gave no reason"}` : attempt.state === "pending" ? "its delivery is still on its way" : `it reached that session as ${attempt.delivery}`;
|
|
22965
|
+
return {
|
|
22966
|
+
text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
|
|
22967
|
+
details: {
|
|
22968
|
+
session,
|
|
22969
|
+
message: message.id,
|
|
22970
|
+
...attempt === undefined ? {} : { delivery: attempt.state },
|
|
22971
|
+
...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
|
|
22972
|
+
}
|
|
22973
|
+
};
|
|
22974
|
+
}
|
|
22932
22975
|
case "dispatch_doc_edit": {
|
|
22933
22976
|
const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
|
|
22934
22977
|
const ops = args.ops;
|
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
|