@sjawhar/claude-envoy 6.17.2 → 6.17.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "6.17.2"
5
+ "version": "6.17.3"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "6.17.2",
3
+ "version": "6.17.3",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
@@ -13688,26 +13688,6 @@ var DISPATCH_KEY_PATTERN = /^([A-Z][A-Z0-9]*)-([0-9]+)$/;
13688
13688
  function isLegionRole(role) {
13689
13689
  return LEGION_ROLES.some((candidate) => candidate === role);
13690
13690
  }
13691
- function roleForPhase(phase) {
13692
- switch (phase) {
13693
- case "planning":
13694
- return "planner";
13695
- case "implementing":
13696
- case "retro":
13697
- return "implementer";
13698
- case "testing":
13699
- return "tester";
13700
- case "reviewing":
13701
- return "reviewer";
13702
- case "admitted":
13703
- case "accepting":
13704
- return "architect";
13705
- case "merging":
13706
- return "merger";
13707
- default:
13708
- return;
13709
- }
13710
- }
13711
13691
  function isLegionProjectToken(project) {
13712
13692
  return PROJECT_TOKEN.test(project);
13713
13693
  }
@@ -13724,6 +13704,9 @@ function roleToken(project, issue, role) {
13724
13704
  const [, dispatchProject, number] = dispatchMatch;
13725
13705
  return `legion-${project}-${dispatchProject?.toLowerCase()}-${number}-${role}`;
13726
13706
  }
13707
+ function roleTopic(token) {
13708
+ return `${ROLE_TOPIC_PREFIX}${token}`;
13709
+ }
13727
13710
 
13728
13711
  // ../contracts/src/dispatch-api-core.ts
13729
13712
  var DisplayTreeSchema = looseObject({ type: string2() });
package/dist/dispatch.js CHANGED
@@ -14288,26 +14288,6 @@ var DISPATCH_KEY_PATTERN = /^([A-Z][A-Z0-9]*)-([0-9]+)$/;
14288
14288
  function isLegionRole(role) {
14289
14289
  return LEGION_ROLES.some((candidate) => candidate === role);
14290
14290
  }
14291
- function roleForPhase(phase) {
14292
- switch (phase) {
14293
- case "planning":
14294
- return "planner";
14295
- case "implementing":
14296
- case "retro":
14297
- return "implementer";
14298
- case "testing":
14299
- return "tester";
14300
- case "reviewing":
14301
- return "reviewer";
14302
- case "admitted":
14303
- case "accepting":
14304
- return "architect";
14305
- case "merging":
14306
- return "merger";
14307
- default:
14308
- return;
14309
- }
14310
- }
14311
14291
  function isLegionProjectToken(project) {
14312
14292
  return PROJECT_TOKEN.test(project);
14313
14293
  }
@@ -14324,6 +14304,9 @@ function roleToken(project, issue, role) {
14324
14304
  const [, dispatchProject, number] = dispatchMatch;
14325
14305
  return `legion-${project}-${dispatchProject?.toLowerCase()}-${number}-${role}`;
14326
14306
  }
14307
+ function roleTopic(token) {
14308
+ return `${ROLE_TOPIC_PREFIX}${token}`;
14309
+ }
14327
14310
 
14328
14311
  // ../contracts/src/dispatch-api-core.ts
14329
14312
  var DisplayTreeSchema = looseObject({ type: string2() });
@@ -36488,26 +36488,6 @@ var DISPATCH_KEY_PATTERN = /^([A-Z][A-Z0-9]*)-([0-9]+)$/;
36488
36488
  function isLegionRole(role) {
36489
36489
  return LEGION_ROLES.some((candidate) => candidate === role);
36490
36490
  }
36491
- function roleForPhase(phase) {
36492
- switch (phase) {
36493
- case "planning":
36494
- return "planner";
36495
- case "implementing":
36496
- case "retro":
36497
- return "implementer";
36498
- case "testing":
36499
- return "tester";
36500
- case "reviewing":
36501
- return "reviewer";
36502
- case "admitted":
36503
- case "accepting":
36504
- return "architect";
36505
- case "merging":
36506
- return "merger";
36507
- default:
36508
- return;
36509
- }
36510
- }
36511
36491
  function isLegionProjectToken(project) {
36512
36492
  return PROJECT_TOKEN.test(project);
36513
36493
  }
@@ -36524,6 +36504,9 @@ function roleToken(project, issue, role) {
36524
36504
  const [, dispatchProject, number] = dispatchMatch;
36525
36505
  return `legion-${project}-${dispatchProject?.toLowerCase()}-${number}-${role}`;
36526
36506
  }
36507
+ function roleTopic(token) {
36508
+ return `${ROLE_TOPIC_PREFIX}${token}`;
36509
+ }
36527
36510
 
36528
36511
  // ../contracts/src/dispatch-api-core.ts
36529
36512
  var DisplayTreeSchema = looseObject({ type: string2() });
@@ -67086,7 +67069,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
67086
67069
 
67087
67070
  // package.json
67088
67071
  var name2 = "@sjawhar/claude-envoy";
67089
- var version2 = "6.17.2";
67072
+ var version2 = "6.17.3";
67090
67073
  var package_default = {
67091
67074
  name: name2,
67092
67075
  version: version2,
@@ -67097,7 +67080,7 @@ var package_default = {
67097
67080
  repository: { type: "git", url: "https://github.com/cybermonklabs/legion" },
67098
67081
  scripts: { channel: "bun bin/envoy-channel.ts", "verify-build": "bash scripts/verify-build.sh", prepack: "bash scripts/pack-skills.sh", postpack: "bash scripts/pack-skills.sh --restore", typecheck: "bun ../contracts/scripts/gen-api.ts && bunx tsc --noEmit", test: "bun test --timeout=60000", lint: "bunx biome check src/ hooks/ scripts/" },
67099
67082
  devDependencies: { "@biomejs/biome": "2.5.15", "@legion/cipher-client": "workspace:*", "@legion/contracts": "workspace:*", "@legion/envoy-client": "workspace:*", "@legion/pi-shared": "workspace:*", "@legion/test-fixtures": "workspace:*", "@modelcontextprotocol/sdk": "^1.30.0", "bun-types": "latest", nats: "^2.29.2", typescript: "^5.3.0", zod: "4.3.6" },
67100
- legion: { daemonApiVersion: 287 }
67083
+ legion: { daemonApiVersion: 288 }
67101
67084
  };
67102
67085
 
67103
67086
  // ../pi-shared/src/agent-stream.ts
@@ -69002,6 +68985,10 @@ var legionIssue = object({
69002
68985
  treeRuns: boolean2().optional(),
69003
68986
  repo: nonEmptyString2.optional(),
69004
68987
  defaultBranch: nonEmptyString2.optional(),
68988
+ repoBefore: nonEmptyString2.optional(),
68989
+ repoCorrectedAt: timestamp.optional(),
68990
+ repoChangePending: nonEmptyString2.optional(),
68991
+ repoChangeReason: nonEmptyString2.optional(),
69005
68992
  holdReason: _enum2(["escalated", "task-stopped", "children"]).optional(),
69006
68993
  heldFrom: _enum2(LEGION_WORKFLOW_PHASES).optional(),
69007
68994
  lingerUntil: timestamp.optional(),
@@ -69407,6 +69394,18 @@ var LegionActivityRequest = strictObject({
69407
69394
  secret: nonEmptyString2,
69408
69395
  activity: LegionSessionActivity
69409
69396
  });
69397
+ var LegionOwedRequest = strictObject({
69398
+ claimToken: nonEmptyString2,
69399
+ sessionId: nonEmptyString2,
69400
+ secret: nonEmptyString2
69401
+ });
69402
+ var LegionOwedResponse = object({
69403
+ owes: boolean2(),
69404
+ work: string2(),
69405
+ architect: nonEmptyString2.optional()
69406
+ }).refine((body) => body.owes === (body.work !== ""), {
69407
+ message: "work names the owed work exactly when owes is true"
69408
+ });
69410
69409
  var legionReleaseRecord = object({
69411
69410
  id: number2().int().positive(),
69412
69411
  issue: issueKey,
@@ -69911,7 +69910,8 @@ var LEGION_ANSWER_READS = {
69911
69910
  "pause.endedBy|1.kind",
69912
69911
  "pause.endedBy|0.session"
69913
69912
  ],
69914
- LegionTurnOutcomeResponse: ["refusedRun", "failed"]
69913
+ LegionTurnOutcomeResponse: ["refusedRun", "failed"],
69914
+ LegionOwedResponse: ["owes", "work", "architect"]
69915
69915
  };
69916
69916
 
69917
69917
  // ../pi-shared/src/daemon-client.ts
@@ -70139,7 +70139,7 @@ function createLegionDaemonClient(baseUrl, options) {
70139
70139
  }
70140
70140
  return parsed.value;
70141
70141
  };
70142
- const post = (path, request, response, body) => read("POST", path, response, request.parse(body));
70142
+ const post = (path, request, response, body, signal) => read("POST", path, response, request.parse(body), signal);
70143
70143
  const acknowledge = async (path, body, signal) => {
70144
70144
  const { status, text, daemonContract } = await call("POST", path, body, signal);
70145
70145
  if (status !== 204 || text !== "") {
@@ -70147,7 +70147,7 @@ function createLegionDaemonClient(baseUrl, options) {
70147
70147
  }
70148
70148
  };
70149
70149
  return {
70150
- state: (reading) => read("GET", "/legion/v1/state", LegionStateResponse, undefined, reading?.signal),
70150
+ state: () => read("GET", "/legion/v1/state", LegionStateResponse),
70151
70151
  record: async (issue, reading) => {
70152
70152
  try {
70153
70153
  return await read("GET", `/legion/v1/issues/${encodeURIComponent(issue)}/record`, LegionIssueRecordResponse, undefined, reading?.signal);
@@ -70167,6 +70167,7 @@ function createLegionDaemonClient(baseUrl, options) {
70167
70167
  exit: (input) => acknowledge("/legion/v1/claims/exit", input),
70168
70168
  turnOutcome: (input) => post("/legion/v1/claims/turn-outcome", LegionTurnOutcomeRequest, LegionTurnOutcomeResponse, input),
70169
70169
  activity: (input) => acknowledge("/legion/v1/claims/activity", input),
70170
+ owed: async (input, options) => post("/legion/v1/claims/owed", LegionOwedRequest, LegionOwedResponse, input, options?.signal),
70170
70171
  releaseRecords: (input) => post("/legion/v1/claims/release-records", LegionReleaseRecordsRequest, LegionReleaseRecordsResponse, input),
70171
70172
  grant: (input) => post("/legion/v1/grants", LegionGrantRequest, LegionGrantResponse, input),
70172
70173
  controllerGrant: (input) => post("/legion/v1/grants", LegionControllerGrantRequest, LegionGrantResponse, input),
@@ -70363,34 +70364,34 @@ import { randomUUID as randomUUID6 } from "crypto";
70363
70364
  // ../pi-shared/src/phase-stall.ts
70364
70365
  var WAITING_REPLY = /^\W*WAITING\b/m;
70365
70366
  var TOOL_CALL_SHAPED = /<(?:[\w-]+:)?(?:function_calls\b|invoke\s+name\s*=|parameter\s+name\s*=)/;
70366
- var REMINDER = "Your turn ended with your Legion phase still open: the `legion` tool's `handoff_complete` has " + "not succeeded since your assignment. If your phase's work is done, call the `legion` tool now " + "with op `handoff_complete` and the fields your role's instructions give. If you are waiting on " + "something (CI, a review, a person), reply with a line starting WAITING that names what you are " + "waiting on: that buys a quiet wait, and then this reminder comes again. This reminder repeats " + "at the end of every turn for as long as your phase is open.";
70367
+ function owedReminder(work) {
70368
+ return `Your turn ended with ${work} still owed: the Legion daemon's record holds it open for your ` + "role. If that work is done, call the `legion` tool now with op `handoff_complete` and the " + "fields your role's instructions give. If you are waiting on something (CI, a review, a " + "person), reply with a line starting WAITING that names what you are waiting on: that buys a " + "quiet wait, and then this reminder comes again. This reminder repeats at the end of every " + "turn for as long as the daemon's record holds that work open.";
70369
+ }
70370
+ var UNREAD_REMINDER = "Your turn ended, and this reminder could not read the Legion daemon's record of what your " + "role owes, so it cannot say whether any work is still yours. If your role's instructions " + "leave work of yours unfinished, finish it now with a real tool call. If you are waiting on " + "something (CI, a review, a person), reply with a line starting WAITING that names what you " + "are waiting on: that buys a quiet wait, and then this reminder comes again. This reminder " + "repeats at the end of every turn for as long as the record cannot be read.";
70367
70371
  var TEXT_TOOL_CALL = "Your last message holds a tool call written as text, so it did not run: make it a real tool call. ";
70368
- function reminderText(lastAssistantText) {
70369
- return TOOL_CALL_SHAPED.test(lastAssistantText) ? TEXT_TOOL_CALL + REMINDER : REMINDER;
70372
+ function reminderText(lastAssistantText, work) {
70373
+ const reminder = work === undefined ? UNREAD_REMINDER : owedReminder(work);
70374
+ return TOOL_CALL_SHAPED.test(lastAssistantText) ? TEXT_TOOL_CALL + reminder : reminder;
70370
70375
  }
70371
70376
  function stepPhaseStall(state, input) {
70372
70377
  switch (input.kind) {
70373
- case "assignment":
70374
- return { state: { state: "open", count: 0 } };
70375
- case "phase-closed":
70376
- return { state: { state: "closed", count: 0 } };
70378
+ case "inbound":
70379
+ return { state: { state: "active", count: 0 } };
70377
70380
  case "update-answered":
70378
- return state.state === "closed" ? { state } : { state: { state: "awaiting-update", count: 0 } };
70379
- case "inbound-event":
70380
- return state.state === "closed" ? { state } : { state: { state: "open", count: 0 } };
70381
+ return { state: { state: "awaiting-update", count: 0 } };
70381
70382
  case "tool-call":
70382
70383
  return { state: { state: state.state, count: 0 } };
70383
70384
  case "refused":
70384
70385
  return { state };
70385
70386
  case "reminded":
70386
- return state.state === "closed" ? { state } : { state: { state: "open", count: state.count + 1 } };
70387
+ return { state: { state: "active", count: state.count + 1 } };
70387
70388
  case "settle": {
70388
- if (state.state !== "open")
70389
+ if (state.state !== "active")
70389
70390
  return { state };
70390
70391
  if (input.backgroundWork === true || WAITING_REPLY.test(input.lastAssistantText)) {
70391
70392
  return { state: { state: "waiting", count: state.count } };
70392
70393
  }
70393
- return { state, reminder: reminderText(input.lastAssistantText) };
70394
+ return { state, remind: true };
70394
70395
  }
70395
70396
  }
70396
70397
  }
@@ -70403,13 +70404,15 @@ function phaseStallFrom(data) {
70403
70404
  const recorded = "count" in data ? data.count : undefined;
70404
70405
  const count = typeof recorded === "number" && Number.isInteger(recorded) && recorded >= 0 ? recorded : 0;
70405
70406
  switch (data.state) {
70406
- case "closed":
70407
- case "open":
70407
+ case "active":
70408
70408
  case "waiting":
70409
70409
  return { state: data.state, count };
70410
+ case "open":
70411
+ case "closed":
70412
+ return { state: "active", count };
70410
70413
  case "quiet":
70411
70414
  case "text-call":
70412
- return { state: "open", count: 0 };
70415
+ return { state: "active", count: 0 };
70413
70416
  default:
70414
70417
  return;
70415
70418
  }
@@ -70438,7 +70441,7 @@ function phaseStallEntryFrom(data) {
70438
70441
  }
70439
70442
 
70440
70443
  // ../pi-shared/src/phase-reminder.ts
70441
- var RECORD_READ_BOUND_MS = 5000;
70444
+ var OWED_READ_BOUND_MS = 3000;
70442
70445
  function roleUnheld(error) {
70443
70446
  if (!(error instanceof EnvoyApiError) || error.details.status !== 404)
70444
70447
  return false;
@@ -70466,13 +70469,13 @@ async function withBound(work, ms) {
70466
70469
  clearTimeout(timer);
70467
70470
  }
70468
70471
  }
70469
- function architectLive(record) {
70470
- const architect = record?.architect;
70471
- return architect !== undefined && architect.state !== "retired" && architect.state !== "failed";
70472
+ function readOwedWithin(readOwed, claim, ms) {
70473
+ return withBound((signal) => readOwed({ claimToken: claim.claimToken, sessionId: claim.sessionID, secret: claim.secret }, signal), ms);
70472
70474
  }
70475
+ var UNREAD_CHECK = { reminds: true, work: undefined };
70473
70476
  function createPhaseReminder(deps) {
70474
- const boundMs = deps.recordBoundMs ?? RECORD_READ_BOUND_MS;
70475
- let stall = { state: "closed", count: 0 };
70477
+ const boundMs = deps.owedBoundMs ?? OWED_READ_BOUND_MS;
70478
+ let stall = { state: "active", count: 0 };
70476
70479
  let reported = false;
70477
70480
  let reportKey;
70478
70481
  let generation = 0;
@@ -70481,6 +70484,7 @@ function createPhaseReminder(deps) {
70481
70484
  let lastMessage = "";
70482
70485
  let recorded = "";
70483
70486
  let armed;
70487
+ let owner;
70484
70488
  const entryOf = () => ({
70485
70489
  state: recordedPhaseStall(stall.state),
70486
70490
  count: stall.count,
@@ -70505,48 +70509,35 @@ function createPhaseReminder(deps) {
70505
70509
  reportKey = undefined;
70506
70510
  }
70507
70511
  writeEntry();
70508
- return step.reminder;
70512
+ return step.remind === true;
70509
70513
  };
70510
- const recordCheck = async () => {
70514
+ const owedCheck = async () => {
70511
70515
  const claim = deps.claim();
70512
70516
  if (claim === undefined)
70513
- return { reminds: true };
70514
- let record;
70517
+ return UNREAD_CHECK;
70518
+ let answer;
70515
70519
  try {
70516
- record = await withBound((signal) => deps.readRecord(claim.issue, signal), boundMs);
70520
+ answer = await readOwedWithin(deps.readOwed, claim, boundMs);
70517
70521
  } catch (error) {
70518
- deps.log.debug("legion: the daemon did not answer the phase reminder's record check", {
70522
+ deps.log.debug("legion: the daemon did not say what this claim owes", {
70519
70523
  issue: claim.issue,
70520
70524
  error: messageFor(error)
70521
70525
  });
70522
- return { reminds: true };
70523
- }
70524
- if (record === undefined) {
70525
- deps.log.debug("legion: the daemon holds no record for this phase reminder's issue", {
70526
- issue: claim.issue
70527
- });
70528
- return { reminds: true };
70529
- }
70530
- if (roleForPhase(record.phase) !== claim.role) {
70531
- deps.log.debug("legion: this role no longer works this phase; no reminder is sent", {
70532
- issue: claim.issue,
70533
- phase: record.phase,
70534
- role: claim.role
70535
- });
70536
- return { reminds: false, record };
70526
+ return UNREAD_CHECK;
70537
70527
  }
70538
- const state = record.workers?.[claim.role]?.claim?.state;
70539
- if (state === "failed") {
70540
- deps.log.debug("legion: the daemon has failed this claim; no reminder is sent", {
70528
+ if (answer.architect !== undefined)
70529
+ owner = answer.architect;
70530
+ if (!answer.owes) {
70531
+ deps.log.debug("legion: the daemon says this claim owes nothing; no reminder is sent", {
70541
70532
  issue: claim.issue,
70542
70533
  role: claim.role
70543
70534
  });
70544
- return { reminds: false, record };
70535
+ return { reminds: false };
70545
70536
  }
70546
- return { reminds: true, record };
70537
+ return { reminds: true, work: answer.work };
70547
70538
  };
70548
70539
  const architectDue = () => !reported && stall.count >= deps.limits.architectAfter;
70549
- const tellArchitect = async (record) => {
70540
+ const tellArchitect = async (work) => {
70550
70541
  if (deps.claim() === undefined)
70551
70542
  return;
70552
70543
  const publish = await deps.publisher();
@@ -70565,18 +70556,17 @@ function createPhaseReminder(deps) {
70565
70556
  reportKey ??= randomUUID6();
70566
70557
  const key = reportKey;
70567
70558
  writeEntry();
70568
- const phase = record?.phase ?? "unknown";
70569
70559
  const reminders = stall.count;
70560
+ const owed = work === undefined ? "its turns keep ending while the daemon's record of what it owes cannot be read" : `its turns keep ending with ${work} still owed`;
70570
70561
  try {
70571
- const live = architectLive(record);
70572
- const topic = ROLE_TOPIC_PREFIX + roleToken(deps.project ?? "", live ? claim.issue : claim.tree, "architect");
70562
+ const topic = roleTopic(owner ?? roleToken(deps.project ?? "", claim.tree, "architect"));
70573
70563
  const answer = await publish({
70574
70564
  topic,
70575
- message: `The ${claim.role} of ${claim.issue} has let ${reminders} phase reminders go unanswered: ` + `its turns keep ending with the phase ${phase} still open and no successful ` + `handoff_complete, and nothing it does clears the reminder. ` + `What it last said was: ${lastMessage}`,
70565
+ message: `The ${claim.role} of ${claim.issue} has let ${reminders} reminders go unanswered: ` + `${owed}, and nothing it does clears the reminder. ` + `What it last said was: ${lastMessage}`,
70576
70566
  payload: JSON.stringify({
70577
70567
  issue: claim.issue,
70578
70568
  role: claim.role,
70579
- phase,
70569
+ ...work === undefined ? {} : { work },
70580
70570
  reminders,
70581
70571
  lastMessage
70582
70572
  }),
@@ -70623,14 +70613,14 @@ function createPhaseReminder(deps) {
70623
70613
  });
70624
70614
  }
70625
70615
  };
70626
- const deliver = async (reminder, record) => {
70616
+ const deliver = async (lastText, work) => {
70627
70617
  const uncounted = stall;
70628
70618
  advance({ kind: "reminded" });
70629
70619
  const counted = stall;
70630
70620
  generation += 1;
70631
70621
  const sentAt = generation;
70632
70622
  try {
70633
- await deps.sendReminder(reminder);
70623
+ await deps.sendReminder(reminderText(lastText, work));
70634
70624
  } catch (error) {
70635
70625
  deps.log.warn("legion: a phase reminder did not reach this worker; it comes again later", {
70636
70626
  error: messageFor(error)
@@ -70640,47 +70630,43 @@ function createPhaseReminder(deps) {
70640
70630
  writeEntry();
70641
70631
  }
70642
70632
  if (generation === sentAt)
70643
- armReminder(reminder, deps.limits.reminderMs);
70633
+ armReminder(lastText, deps.limits.reminderMs);
70644
70634
  return;
70645
70635
  }
70646
70636
  if (!architectDue())
70647
70637
  return;
70648
- await tellArchitect(record);
70638
+ await tellArchitect(work);
70649
70639
  };
70650
- const armReminder = (reminder, delayMs) => {
70640
+ const armReminder = (lastText, delayMs) => {
70651
70641
  const armedAt = generation;
70652
70642
  armed = { at: Date.now() + delayMs, generation: armedAt };
70653
70643
  deps.armTimer(async () => {
70654
- if (generation !== armedAt || stall.state === "closed" || turnRunning)
70644
+ if (generation !== armedAt || turnRunning)
70655
70645
  return;
70656
- const check = await recordCheck();
70646
+ const check = await owedCheck();
70657
70647
  if (!check.reminds)
70658
70648
  return;
70659
70649
  if (generation !== armedAt || turnRunning)
70660
70650
  return;
70661
- await deliver(reminder, check.record);
70651
+ await deliver(lastText, check.work);
70662
70652
  }, delayMs);
70663
70653
  };
70664
70654
  return {
70665
70655
  restore: (entry) => {
70666
- stall = entry === undefined ? { state: "closed", count: 0 } : { state: entry.state, count: entry.count };
70656
+ stall = entry === undefined ? { state: "active", count: 0 } : { state: entry.state, count: entry.count };
70667
70657
  reported = entry?.reported ?? false;
70668
70658
  reportKey = entry?.reportKey;
70669
70659
  lastMessage = entry?.lastMessage ?? "";
70670
70660
  recorded = JSON.stringify(entryOf());
70671
70661
  },
70672
70662
  armResumeReminder: () => {
70673
- if (stall.state === "closed")
70674
- return;
70675
- armReminder(reminderText(""), deps.limits.resumeMs);
70663
+ armReminder("", deps.limits.resumeMs);
70676
70664
  },
70677
70665
  turnStarted: () => {
70678
70666
  generation += 1;
70679
70667
  turnRunning = true;
70680
70668
  },
70681
70669
  apply: (input) => {
70682
- if (input.kind === "phase-closed")
70683
- generation += 1;
70684
70670
  advance(input);
70685
70671
  },
70686
70672
  settle: async (turn) => {
@@ -70689,46 +70675,39 @@ function createPhaseReminder(deps) {
70689
70675
  if (turn.kind === "refused") {
70690
70676
  advance(turn);
70691
70677
  continued = false;
70692
- armReminder(reminderText(""), deps.limits.reminderMs);
70678
+ armReminder("", deps.limits.reminderMs);
70693
70679
  return;
70694
70680
  }
70695
70681
  const text = turn.lastAssistantText;
70696
- if (stall.state !== "closed")
70697
- lastMessage = text.slice(0, LAST_MESSAGE_LIMIT);
70682
+ lastMessage = text.slice(0, LAST_MESSAGE_LIMIT);
70698
70683
  const before = stall.count;
70699
- const reminder = advance(turn);
70700
- if (stall.state === "awaiting-update") {
70701
- continued = false;
70702
- return;
70703
- }
70704
- if (stall.state === "waiting") {
70705
- continued = false;
70706
- armReminder(reminderText(text), deps.limits.waitingMs);
70707
- return;
70708
- }
70709
- if (reminder === undefined) {
70684
+ const remind = advance(turn);
70685
+ if (!remind) {
70710
70686
  continued = false;
70687
+ if (stall.state === "waiting")
70688
+ armReminder(text, deps.limits.waitingMs);
70711
70689
  return;
70712
70690
  }
70713
70691
  if (before !== 0 || continued) {
70714
70692
  continued = false;
70715
- armReminder(reminder, deps.limits.reminderMs);
70693
+ armReminder(text, deps.limits.reminderMs);
70716
70694
  return;
70717
70695
  }
70718
- if (!(await recordCheck()).reminds) {
70696
+ const check = await owedCheck();
70697
+ if (!check.reminds) {
70719
70698
  continued = false;
70720
70699
  return;
70721
70700
  }
70722
70701
  advance({ kind: "reminded" });
70723
70702
  generation += 1;
70724
70703
  continued = true;
70725
- return reminder;
70704
+ return reminderText(text, check.work);
70726
70705
  },
70727
70706
  sessionChanged: () => {
70728
70707
  generation += 1;
70729
70708
  },
70730
70709
  phaseWake: () => {
70731
- if (stall.state === "closed" || armed === undefined || armed.generation !== generation) {
70710
+ if (armed === undefined || armed.generation !== generation) {
70732
70711
  return { nextReminderAt: null };
70733
70712
  }
70734
70713
  return { nextReminderAt: new Date(armed.at).toISOString() };
@@ -70789,7 +70768,6 @@ var HOOK_EVENTS = [
70789
70768
  "PostToolUseFailure",
70790
70769
  "UserPromptSubmit"
70791
70770
  ];
70792
- var WRITTEN_LINES_KEPT = 32;
70793
70771
  var hookArguments = object({
70794
70772
  event: _enum2(HOOK_EVENTS),
70795
70773
  lastAssistantMessage: string2().optional(),
@@ -70888,7 +70866,7 @@ function writePhaseStallRecord(file, entry, recreatedNoticeSent, log) {
70888
70866
  function createPhaseHookEndpoint(deps) {
70889
70867
  const limits = stallLimits(deps.env, deps.log, configuredValue(deps.env["LEGION_ROLE"]));
70890
70868
  const restored = readPhaseStallRecord(deps.stateFile, deps.log);
70891
- let entry = restored.entry ?? { state: "closed", count: 0, reported: false };
70869
+ let entry = restored.entry ?? { state: "active", count: 0, reported: false };
70892
70870
  let recreatedNoticeSent = restored.recreatedNoticeSent;
70893
70871
  const saveRecord = (next) => {
70894
70872
  entry = next;
@@ -70913,15 +70891,6 @@ function createPhaseHookEndpoint(deps) {
70913
70891
  }, delayMs);
70914
70892
  };
70915
70893
  let lastReminder;
70916
- const written = new Set;
70917
- const noteWritten = (content) => {
70918
- written.add(content);
70919
- for (const oldest of written) {
70920
- if (written.size <= WRITTEN_LINES_KEPT)
70921
- break;
70922
- written.delete(oldest);
70923
- }
70924
- };
70925
70894
  const writeToSession = async (text, what) => {
70926
70895
  const { inbox } = deps;
70927
70896
  if (inbox === undefined) {
@@ -70941,7 +70910,7 @@ function createPhaseHookEndpoint(deps) {
70941
70910
  armTimer,
70942
70911
  saveEntry: saveRecord,
70943
70912
  claim: deps.claim,
70944
- readRecord: deps.readRecord,
70913
+ readOwed: deps.readOwed,
70945
70914
  publisher: async () => deps.publish,
70946
70915
  project: configuredValue(deps.env["LEGION_PROJECT"]),
70947
70916
  limits,
@@ -70973,7 +70942,6 @@ function createPhaseHookEndpoint(deps) {
70973
70942
  return;
70974
70943
  recreatedNoticeSent = true;
70975
70944
  saveRecord(entry);
70976
- noteWritten(notice.content);
70977
70945
  writeToSession(notice.content, "the recreated-workspace notice").catch((error) => {
70978
70946
  deps.log.warn("legion: the recreated-workspace notice did not reach this worker", {
70979
70947
  error: messageFor(error)
@@ -70989,8 +70957,6 @@ function createPhaseHookEndpoint(deps) {
70989
70957
  reminder.armResumeReminder();
70990
70958
  });
70991
70959
  return {
70992
- deliveryWritten: noteWritten,
70993
- phaseClosed: () => reminder.apply({ kind: "phase-closed" }),
70994
70960
  updateAnswered: () => reminder.apply({ kind: "update-answered" }),
70995
70961
  stop: dropTimer,
70996
70962
  handle: async (input) => {
@@ -71037,8 +71003,7 @@ function createPhaseHookEndpoint(deps) {
71037
71003
  const prompt = event.prompt ?? "";
71038
71004
  if (prompt === lastReminder)
71039
71005
  return {};
71040
- const delivered = written.delete(prompt);
71041
- reminder.apply({ kind: delivered ? "inbound-event" : "assignment" });
71006
+ reminder.apply({ kind: "inbound" });
71042
71007
  return {};
71043
71008
  }
71044
71009
  }
@@ -71283,13 +71248,6 @@ var PHASE_OPS = [
71283
71248
  function namesCheck(args) {
71284
71249
  return args["check_opened_at"] !== undefined;
71285
71250
  }
71286
- function phaseInputAfter(op, args) {
71287
- if (op === "ready_for_update")
71288
- return "update-answered";
71289
- if (op === "request_backward_move" || op === "handoff_complete" && !namesCheck(args))
71290
- return "phase-closed";
71291
- return;
71292
- }
71293
71251
  var requiredString = (op, field) => {
71294
71252
  const message = `${op} requires ${field}`;
71295
71253
  return string2({ error: message }).refine((value) => value.trim() !== "", { error: message });
@@ -71683,10 +71641,7 @@ async function executeLegionTool(runtime, input, signal) {
71683
71641
  }
71684
71642
  async function answerLegionTool(runtime, args, hooks, signal) {
71685
71643
  const answer = await executeLegionTool(runtime, args, signal);
71686
- const effect = phaseInputAfter(String(args["op"]), args);
71687
- if (effect === "phase-closed")
71688
- await hooks.phaseClosed();
71689
- else if (effect === "update-answered")
71644
+ if (args["op"] === "ready_for_update")
71690
71645
  await hooks.updateAnswered();
71691
71646
  return answer;
71692
71647
  }
@@ -74329,7 +74284,7 @@ async function runEnvoyChannelServer() {
74329
74284
  claim: () => claim?.capability(),
74330
74285
  booted: claimBooted.promise,
74331
74286
  firstTurnStarted: () => reportFirstTurn?.(),
74332
- readRecord: (issue, signal) => daemon.record(issue, { signal }),
74287
+ readOwed: (input, signal) => daemon.owed(input, { signal }),
74333
74288
  reportActivity: (input) => daemon.activity(input),
74334
74289
  inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
74335
74290
  publish: client.publish,
@@ -74352,10 +74307,7 @@ async function runEnvoyChannelServer() {
74352
74307
  handoffReport: paneHandoffReport(configFile, process.env, directory, identity.id),
74353
74308
  branchHead: () => findPushedBranchHead({ env: process.env })
74354
74309
  };
74355
- const answer = await answerLegionTool(legionRuntime, request.params.arguments ?? {}, {
74356
- phaseClosed: () => phaseHook?.phaseClosed(),
74357
- updateAnswered: () => phaseHook?.updateAnswered()
74358
- }, extra.signal);
74310
+ const answer = await answerLegionTool(legionRuntime, request.params.arguments ?? {}, { updateAnswered: () => phaseHook?.updateAnswered() }, extra.signal);
74359
74311
  return mcpResult(answer);
74360
74312
  }
74361
74313
  if (runtime === undefined)
@@ -74385,7 +74337,7 @@ async function runEnvoyChannelServer() {
74385
74337
  warn: (text) => serverStderr(`envoy-channel: ${text}
74386
74338
  `)
74387
74339
  });
74388
- const writer = inbox ?? {
74340
+ const notifier = inbox ?? {
74389
74341
  notification: async ({ content, blocks, eventId }) => {
74390
74342
  await claude.show({
74391
74343
  content: blocks ?? [{ type: "text", text: content }],
@@ -74394,12 +74346,6 @@ async function runEnvoyChannelServer() {
74394
74346
  });
74395
74347
  }
74396
74348
  };
74397
- const notifier = phaseHook === undefined ? writer : {
74398
- notification: async (notification) => {
74399
- phaseHook.deliveryWritten(notification.content);
74400
- await writer.notification(notification);
74401
- }
74402
- };
74403
74349
  const capabilities = () => sessionCapabilities({ pane: inboxSocket !== undefined, mod: modLink?.connected() === true });
74404
74350
  const booting = new AbortController;
74405
74351
  const stopped = Promise.withResolvers();
@@ -17290,26 +17290,6 @@ var DISPATCH_KEY_PATTERN = /^([A-Z][A-Z0-9]*)-([0-9]+)$/;
17290
17290
  function isLegionRole(role) {
17291
17291
  return LEGION_ROLES.some((candidate) => candidate === role);
17292
17292
  }
17293
- function roleForPhase(phase) {
17294
- switch (phase) {
17295
- case "planning":
17296
- return "planner";
17297
- case "implementing":
17298
- case "retro":
17299
- return "implementer";
17300
- case "testing":
17301
- return "tester";
17302
- case "reviewing":
17303
- return "reviewer";
17304
- case "admitted":
17305
- case "accepting":
17306
- return "architect";
17307
- case "merging":
17308
- return "merger";
17309
- default:
17310
- return;
17311
- }
17312
- }
17313
17293
  function isLegionProjectToken(project) {
17314
17294
  return PROJECT_TOKEN.test(project);
17315
17295
  }
@@ -17326,6 +17306,9 @@ function roleToken(project, issue, role) {
17326
17306
  const [, dispatchProject, number] = dispatchMatch;
17327
17307
  return `legion-${project}-${dispatchProject?.toLowerCase()}-${number}-${role}`;
17328
17308
  }
17309
+ function roleTopic(token) {
17310
+ return `${ROLE_TOPIC_PREFIX}${token}`;
17311
+ }
17329
17312
 
17330
17313
  // ../contracts/src/dispatch-api-core.ts
17331
17314
  var DisplayTreeSchema = looseObject({ type: string2() });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "6.17.2",
3
+ "version": "6.17.3",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -45,6 +45,6 @@
45
45
  "zod": "4.3.6"
46
46
  },
47
47
  "legion": {
48
- "daemonApiVersion": 287
48
+ "daemonApiVersion": 288
49
49
  }
50
50
  }
package/scripts/build.ts CHANGED
@@ -164,8 +164,8 @@ const LEGION_HOOKS: readonly {
164
164
  // woken by it rather than a stalled one, and earns no reminder.
165
165
  backgroundTasks: "${background_tasks}",
166
166
  },
167
- // The `Stop` answer waits on the reminder's record check, which bounds its own daemon read at
168
- // 5 s (RECORD_READ_BOUND_MS, packages/pi-shared/src/phase-reminder.ts); the others answer from
167
+ // The `Stop` answer waits on the reminder's owed check, which bounds its own daemon read at
168
+ // 3 s (OWED_READ_BOUND_MS, packages/pi-shared/src/phase-reminder.ts); the others answer from
169
169
  // memory and the state file alone.
170
170
  timeout: 30,
171
171
  },
@@ -2836,7 +2836,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2836
2836
  claim: () => claim?.capability(),
2837
2837
  booted: claimBooted.promise,
2838
2838
  firstTurnStarted: () => reportFirstTurn?.(),
2839
- readRecord: (issue, signal) => daemon.record(issue, { signal }),
2839
+ readOwed: (input, signal) => daemon.owed(input, { signal }),
2840
2840
  reportActivity: (input) => daemon.activity(input),
2841
2841
  inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
2842
2842
  publish: client.publish,
@@ -2863,13 +2863,13 @@ export async function runEnvoyChannelServer(): Promise<void> {
2863
2863
  }
2864
2864
  // The request's signal aborts on the client's notifications/cancelled, which ends a wait
2865
2865
  // for a restarting daemon.
2866
+ // A `ready_for_update` that answered blocks no `Stop` of its turn (`answerLegionTool`), as
2867
+ // the Oh My Pi host's `onUpdateAnswered` does (`createLegionTool` in
2868
+ // `packages/pi-legion/src/tools.ts`).
2866
2869
  const answer = await answerLegionTool(
2867
2870
  legionRuntime,
2868
2871
  request.params.arguments ?? {},
2869
- {
2870
- phaseClosed: () => phaseHook?.phaseClosed(),
2871
- updateAnswered: () => phaseHook?.updateAnswered(),
2872
- },
2872
+ { updateAnswered: () => phaseHook?.updateAnswered() },
2873
2873
  extra.signal,
2874
2874
  )
2875
2875
  return mcpResult(answer)
@@ -2915,11 +2915,8 @@ export async function runEnvoyChannelServer(): Promise<void> {
2915
2915
  // Every line this server writes into the session: the bridge's inbox in a Legion pane, and the
2916
2916
  // mod's own write in a terminal session, which is a row of the turn running and the prompt of
2917
2917
  // a new turn while the session is idle (`ModSession.show`), since an appended row an idle
2918
- // session never reads would wait for the person to type. The endpoint is told every line
2919
- // written for a delivery: the `UserPromptSubmit` that carries one back is that delivery's
2920
- // turn, not a fresh assignment, and this server, which writes them all, is the only place
2921
- // that knows.
2922
- const writer: ChannelNotifier = inbox ?? {
2918
+ // session never reads would wait for the person to type.
2919
+ const notifier: ChannelNotifier = inbox ?? {
2923
2920
  notification: async ({ content, blocks, eventId }) => {
2924
2921
  await claude.show({
2925
2922
  content: blocks ?? [{ type: "text", text: content }],
@@ -2930,15 +2927,6 @@ export async function runEnvoyChannelServer(): Promise<void> {
2930
2927
  })
2931
2928
  },
2932
2929
  }
2933
- const notifier: ChannelNotifier =
2934
- phaseHook === undefined
2935
- ? writer
2936
- : {
2937
- notification: async (notification) => {
2938
- phaseHook.deliveryWritten(notification.content)
2939
- await writer.notification(notification)
2940
- },
2941
- }
2942
2930
  const capabilities = (): readonly DeliveryCapability[] =>
2943
2931
  sessionCapabilities({ pane: inboxSocket !== undefined, mod: modLink?.connected() === true })
2944
2932
  const booting = new AbortController()
@@ -3014,8 +3002,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
3014
3002
  sessionId: () => identity.id,
3015
3003
  state,
3016
3004
  warn: (text) => serverStderr(`envoy-channel: ${text}\n`),
3017
- // A pane's person message is a line of the bridge's inbox, which makes it a user turn;
3018
- // the phase endpoint is told of it as it is told of every line this server writes.
3005
+ // A pane's person message is a line of the bridge's inbox, which makes it a user turn.
3019
3006
  ...(inboxSocket === undefined ? {} : { inbox: (input) => notifier.notification(input) }),
3020
3007
  }
3021
3008
  return createUserTurnRouter(options)
@@ -1,9 +1,9 @@
1
1
  import { randomUUID } from "node:crypto"
2
2
  import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
3
3
  import { dirname, join } from "node:path"
4
- import type { LegionIssue } from "@legion/contracts/legion-api"
4
+ import type { LegionOwed } from "@legion/contracts/legion-api"
5
5
  import { messageFor } from "@legion/envoy-client/errors"
6
- import type { ActivityInput } from "@legion/pi-shared/daemon-client"
6
+ import type { ActivityInput, OwedInput } from "@legion/pi-shared/daemon-client"
7
7
  import type { ClaimCapability } from "@legion/pi-shared/legion-phase-ops"
8
8
  import {
9
9
  createPhaseReminder,
@@ -47,14 +47,14 @@ import { configuredValue } from "./claude-session"
47
47
  * another turn at once and the provider would refuse that one the same way. It does arm one
48
48
  * timer, because the task that refused turn carried ended with it and nothing else would wake
49
49
  * this worker, so a single transient refusal would otherwise leave the issue idle. What stops
50
- * the reminding for good is the runner's record check, which drops every reminder once the
51
- * daemon has failed this role's claim. The bridge reports each turn's outcome to the daemon, with
52
- * the status Claude Code named, and marks a turn no prompt of the daemon's ran — a reminder
53
- * written over the inbox — so the daemon judges that turn from the report (dispatch://INFRA-4508):
54
- * a refusal whose status cannot clear fails the claim at once and holds the issue, and a
55
- * refusal that can clear fails nothing, so the reminders keep their pace. At six such turns in
56
- * a row the daemon sends the `provider-errors` notice once (`providerErrorRunReached` in the
57
- * daemon's `workflow.go` says to whom).
50
+ * the reminding for good is the runner's owed check: once the daemon has failed this role's
51
+ * claim it answers that the claim owes nothing, and every reminder is dropped. The bridge reports
52
+ * each turn's outcome to the daemon, with the status Claude Code named, and marks a turn no prompt
53
+ * of the daemon's ran — a reminder written over the inbox — so the daemon judges that turn from
54
+ * the report (dispatch://INFRA-4508): a refusal whose status cannot clear fails the claim at once
55
+ * and holds the issue, and a refusal that can clear fails nothing, so the reminders keep their
56
+ * pace. At six such turns in a row the daemon sends the `provider-errors` notice once
57
+ * (`providerErrorRunReached` in the daemon's `workflow.go` says to whom).
58
58
  */
59
59
 
60
60
  /** The tool's name: Claude Code shows it as `mcp__legion__legion_phase_hook`, and a hook entry
@@ -78,17 +78,6 @@ const HOOK_EVENTS = [
78
78
  "UserPromptSubmit",
79
79
  ] as const
80
80
 
81
- /**
82
- * How many inbox lines this server wrote are kept waiting for the prompt that carries them back.
83
- * Each is dropped as its prompt arrives, so the set stays at the one or two lines in flight; the
84
- * cap is what bounds it when a line never comes back at all, because the bridge handed two of
85
- * them to one turn. A turn whose line was dropped by the cap counts as an assignment rather than
86
- * an inbound event: both put the count back to 0, but an assignment reopens a phase an inbound
87
- * event would leave closed, so the mistake is the unsafe direction and the record check is all
88
- * that bounds it. The cap is high enough that only a bridge that lost a line reaches it.
89
- */
90
- const WRITTEN_LINES_KEPT = 32
91
-
92
81
  /** One hook call's arguments: the event, and that event's own fields. Claude Code substitutes
93
82
  * `${…}` as strings, so every field is one — `stopHookActive` ("true"/"false") and
94
83
  * `backgroundTasks` (the JSON array, as text) included. */
@@ -151,19 +140,11 @@ export interface PhaseHookAnswer {
151
140
  export interface PhaseHookEndpoint {
152
141
  /** Answers one hook call, with the record written before the answer. */
153
142
  readonly handle: (input: unknown) => Promise<PhaseHookAnswer>
154
- /** One line this server has just written into the bridge's inbox for an Envoy delivery. The
155
- * prompt that carries it back is that delivery's turn, not a fresh assignment, and this is the
156
- * only way the endpoint can tell the two apart: the server writes every delivery itself. */
157
- readonly deliveryWritten: (content: string) => void
158
- /** The `legion` tool's `handoff_complete`, or its `request_backward_move`, returned without
159
- * throwing: this session's phase is no longer open. The CallTool handler of the same server
160
- * calls it (`./envoy-channel-server`), as `onPhaseCompleted` does on the Oh My Pi host. */
161
- readonly phaseClosed: () => void
162
143
  /** The `legion` tool's `ready_for_update` returned without throwing: the worker has pushed
163
- * what it wants kept and waits for the process its claim runs in to be replaced. Its phase
164
- * stays open, and the `Stop` of the turn it answered in must block nothing: the work a
165
- * continuation did would go with the pod, and the daemon would see no turn end. The same
166
- * CallTool handler calls it, as `onUpdateAnswered` does on the Oh My Pi host. */
144
+ * what it wants kept and waits for the process its claim runs in to be replaced, and the `Stop`
145
+ * of the turn it answered in must block nothing: the work a continuation did would go with the
146
+ * pod, and the daemon would see no turn end. The CallTool handler of the same server calls it
147
+ * (`./envoy-channel-server`), as `onUpdateAnswered` does on the Oh My Pi host. */
167
148
  readonly updateAnswered: () => void
168
149
  /** Drops the armed timer, so a 15-minute WAITING wait never holds a shutting-down server
169
150
  * open (the server's own `stop`). */
@@ -187,10 +168,11 @@ export interface PhaseHookDeps {
187
168
  * registered its step — the bridge's seeding `/rename` — signals nothing, and one after the
188
169
  * name is taken costs nothing. */
189
170
  readonly firstTurnStarted: () => void
190
- /** One issue's record, for the reminder's record check, aborted with `signal` once the
191
- * check's bound passes (`PhaseReminderDeps.readRecord`): the record, or `undefined` for an
192
- * issue the daemon records nothing of. */
193
- readonly readRecord: (issue: string, signal: AbortSignal) => Promise<LegionIssue | undefined>
171
+ /** What this session's claim owes now (`LegionDaemonClient.owed`), the one answer that decides
172
+ * whether a reminder goes out, aborted with `signal` once the check's bound passes
173
+ * (`PhaseReminderDeps.readOwed`). An answer that does not arrive is the shared reminder's to
174
+ * decide (`UNREAD_CHECK`, `@legion/pi-shared/phase-reminder`), as it is on Oh My Pi. */
175
+ readonly readOwed: (input: OwedInput, signal: AbortSignal) => Promise<LegionOwed>
194
176
  /** Sends this session's activity report to the daemon (`LegionDaemonClient.activity`), so the
195
177
  * idle rule can decide whether the pane's pod may be released (INFRA-945). */
196
178
  readonly reportActivity: (input: ActivityInput) => Promise<void>
@@ -237,7 +219,8 @@ export function paneReminderLog(write: (line: string) => void): PhaseReminderLog
237
219
  * left behind, which has no such key, still reads.
238
220
  */
239
221
  export interface PhaseStallRecord {
240
- /** The phase and count the file holds, or undefined when it holds none this build knows. */
222
+ /** The reminder's rhythm and count the file holds, or undefined when it holds none this build
223
+ * knows. */
241
224
  readonly entry: PhaseStallEntry | undefined
242
225
  /** Whether this launch's recreated-workspace notice has already been written into the session
243
226
  * (`recreatedNoticeSent` in the file); false for a record that names no such key. It outlives
@@ -253,10 +236,11 @@ const NO_RECORD: PhaseStallRecord = { entry: undefined, recreatedNoticeSent: fal
253
236
  /**
254
237
  * The record `file` holds: a missing file is no record at all, so a fresh session restores
255
238
  * nothing. The entry itself is assembled where the Oh My Pi host's is
256
- * (`phaseStallEntryFrom`), so a record written by the build now in the pods —
257
- * `{"state":"quiet"}` or `{"state":"text-call"}` — reads as an open phase with no reminders yet
258
- * here too, and a missing `count`, `reported` or `reportKey` reads as 0, false and absent. This
259
- * host adds the warning for a record it understands none of, and its own `recreatedNoticeSent`.
239
+ * (`phaseStallEntryFrom`), so a record an earlier build wrote — `{"state":"open"}` or
240
+ * `{"state":"closed"}` with its count, `{"state":"quiet"}` or `{"state":"text-call"}` — reads as
241
+ * the rhythm's `active` here too, and a missing `count`, `reported` or `reportKey` reads as 0,
242
+ * false and absent. This host adds the warning for a record it understands none of, and its own
243
+ * `recreatedNoticeSent`.
260
244
  */
261
245
  export function readPhaseStallRecord(file: string, log: PhaseReminderLog): PhaseStallRecord {
262
246
  let raw: string
@@ -338,7 +322,7 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
338
322
  const restored = readPhaseStallRecord(deps.stateFile, deps.log)
339
323
  // The machine's entry and this host's own key are one record, so the last entry written is kept
340
324
  // for the write the notice makes.
341
- let entry: PhaseStallEntry = restored.entry ?? { state: "closed", count: 0, reported: false }
325
+ let entry: PhaseStallEntry = restored.entry ?? { state: "active", count: 0, reported: false }
342
326
  let recreatedNoticeSent = restored.recreatedNoticeSent
343
327
  const saveRecord = (next: PhaseStallEntry): void => {
344
328
  entry = next
@@ -372,18 +356,6 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
372
356
  /** The reminder last written to the inbox: the prompt that carries it back is this endpoint's
373
357
  * own reminder, and a reminder must never reset the count it just moved. */
374
358
  let lastReminder: string | undefined
375
- /** The lines this server wrote into the inbox for something that is not a reminder — an Envoy
376
- * delivery, the recreated-workspace notice — whose prompt has not arrived yet. Each is dropped
377
- * as its prompt arrives (`WRITTEN_LINES_KEPT` bounds the rest). */
378
- const written = new Set<string>()
379
- const noteWritten = (content: string): void => {
380
- written.add(content)
381
- for (const oldest of written) {
382
- if (written.size <= WRITTEN_LINES_KEPT) break
383
- written.delete(oldest)
384
- }
385
- }
386
-
387
359
  /** Writes `text` into the session over the bridge's inbox, and settles as the inbox does: it
388
360
  * rejects when the bridge did not queue the line. A session with no inbox says so and writes
389
361
  * nothing, and that is no failure: no later attempt could reach the worker either. */
@@ -416,7 +388,7 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
416
388
  // count was never recorded is what the count exists to catch.
417
389
  saveEntry: saveRecord,
418
390
  claim: deps.claim,
419
- readRecord: deps.readRecord,
391
+ readOwed: deps.readOwed,
420
392
  // The server's own listener client, so the notice reaches the one this session already talks
421
393
  // to; Envoy off for the session leaves it undefined, the runner says so once at debug, and
422
394
  // the reminder keeps coming without a notice.
@@ -460,11 +432,11 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
460
432
  /**
461
433
  * D29: a worker whose launcher recreated its workspace is told so, as an Oh My Pi one is, over
462
434
  * the same inbox the reminders use. Once per launch: the record it is written in is the one the
463
- * phase and count live in, so a server Claude Code restarts inside the same `claude` process
464
- * does not repeat it, and a launch that recreated nothing clears it again. The record lands
465
- * before the line does — a notice a broken socket loses is one notice lost, while one written
466
- * twice is the thing it must not be — and the line is noted as written, so the turn it starts
467
- * counts as an inbound event and leaves a closed phase closed.
435
+ * reminder's rhythm and count live in, so a server Claude Code restarts inside the same
436
+ * `claude` process does not repeat it, and a launch that recreated nothing clears it again. The
437
+ * record lands before the line does — a notice a broken socket loses is one notice lost, while
438
+ * one written twice is the thing it must not be — and the turn it starts is an inbound message
439
+ * like any other, which says nothing of what the claim owes.
468
440
  */
469
441
  const sendRecreatedNotice = (issue: string): void => {
470
442
  if (recreatedNoticeSent) return
@@ -472,7 +444,6 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
472
444
  if (notice === undefined) return
473
445
  recreatedNoticeSent = true
474
446
  saveRecord(entry)
475
- noteWritten(notice.content)
476
447
  void writeToSession(notice.content, "the recreated-workspace notice").catch(
477
448
  (error: unknown) => {
478
449
  deps.log.warn("legion: the recreated-workspace notice did not reach this worker", {
@@ -486,16 +457,14 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
486
457
  const claim = deps.claim()
487
458
  if (claim === undefined) return
488
459
  sendRecreatedNotice(claim.issue)
489
- // D10: a worker the daemon relaunched into an open phase is reminded from a timer, since
490
- // nothing else would wake it. The guard drops that timer when a turn started meanwhile, which
491
- // is exactly the case to drop — the daemon re-sending an interrupted task arrives as a
492
- // `UserPromptSubmit`.
460
+ // D10: a worker the daemon relaunched is reminded from a timer, since nothing else would wake
461
+ // it, and the daemon's answer when it is due says whether anything is owed. The guard drops
462
+ // that timer when a turn started meanwhile, which is exactly the case to drop — the daemon
463
+ // re-sending an interrupted task arrives as a `UserPromptSubmit`.
493
464
  if (claim.role !== "architect") reminder.armResumeReminder()
494
465
  })
495
466
 
496
467
  return {
497
- deliveryWritten: noteWritten,
498
- phaseClosed: () => reminder.apply({ kind: "phase-closed" }),
499
468
  updateAnswered: () => reminder.apply({ kind: "update-answered" }),
500
469
  stop: dropTimer,
501
470
  handle: async (input) => {
@@ -549,11 +518,12 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
549
518
  // refusing the turn, and the machine takes it as one: it earns no continuation, because
550
519
  // the next turn would be refused the same way, and one timer, because nothing else would
551
520
  // wake this worker once the task that turn carried ended with it. What ends the reminding
552
- // is the daemon failing the claim, which the timer's own record check reads: it does at
553
- // once for a refusal whose status cannot clear, the status the bridge reports beside the
554
- // turn's outcome, a reminder's own turn included, and never for a refusal that can clear,
555
- // of which the daemon sends the `provider-errors` notice at six in a row
556
- // (dispatch://INFRA-4508; `providerErrorRunReached` in the daemon says to whom).
521
+ // is the daemon failing the claim, after which the timer's own owed check is answered
522
+ // that the claim owes nothing: it fails one at once for a refusal whose status cannot
523
+ // clear, the status the bridge reports beside the turn's outcome, a reminder's own turn
524
+ // included, and never for a refusal that can clear, of which the daemon sends the
525
+ // `provider-errors` notice at six in a row (dispatch://INFRA-4508;
526
+ // `providerErrorRunReached` in the daemon says to whom).
557
527
  // Claude Code ignores whatever this hook returns, which costs nothing now that there
558
528
  // is nothing to return.
559
529
  await reminder.settle({ kind: "refused", message: event.lastAssistantMessage ?? "" })
@@ -571,19 +541,17 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
571
541
  }
572
542
  case "UserPromptSubmit": {
573
543
  // D7: the only sight this server has of an inbound turn. The daemon's task reaches
574
- // Claude Code's stdin from the bridge and never this process, so what a turn means is
575
- // read from the prompt itself. The turn is declared first, which makes every armed
576
- // timer stale, and the pending one is dropped outright: the runner's generation guard
577
- // answers the same for the timers it armed, and dropping the one timer this server
578
- // holds is the plainest way to say the same thing.
544
+ // Claude Code's stdin from the bridge and never this process, so a turn is read from the
545
+ // prompt itself: this endpoint's own reminder, or an inbound message, which starts the
546
+ // count again and says nothing of what the claim owes. The turn is declared first,
547
+ // which makes every armed timer stale, and the pending one is dropped outright: the
548
+ // runner's generation guard answers the same for the timers it armed, and dropping the
549
+ // one timer this server holds is the plainest way to say the same thing.
579
550
  reminder.turnStarted()
580
551
  dropTimer()
581
552
  const prompt = event.prompt ?? ""
582
553
  if (prompt === lastReminder) return {}
583
- // A line this server wrote is dropped as its prompt arrives, so a later turn carrying
584
- // the same text is an assignment, which is what a repeat of it would be.
585
- const delivered = written.delete(prompt)
586
- reminder.apply({ kind: delivered ? "inbound-event" : "assignment" })
554
+ reminder.apply({ kind: "inbound" })
587
555
  return {}
588
556
  }
589
557
  }
@@ -8,7 +8,6 @@ import {
8
8
  legionToolDescription,
9
9
  PHASE_OP_SENTENCES,
10
10
  PHASE_OPS,
11
- phaseInputAfter,
12
11
  phaseOpParameters,
13
12
  pluginBuildOf,
14
13
  } from "@legion/pi-shared/legion-phase-ops"
@@ -84,19 +83,18 @@ export async function executeLegionTool(
84
83
  )
85
84
  }
86
85
 
87
- /** Runs a successful call through the host's input hooks; a refusal changes no input gate. */
86
+ /** Runs one call of the `legion` tool, as executeLegionTool does, and tells the host once a
87
+ * `ready_for_update` it ran answered the pod's update message: the worker then waits for its
88
+ * process to be replaced, so the `Stop` of the turn it answered in blocks nothing
89
+ * (`updateAnswered`, `./legion-phase-hook`). A completion and a look's report tell the host
90
+ * nothing: the reminder asks the daemon what the claim owes. A refusal throws before any hook. */
88
91
  export async function answerLegionTool(
89
92
  runtime: LegionToolRuntime,
90
93
  args: Record<string, unknown>,
91
- hooks: {
92
- readonly phaseClosed: () => void | Promise<void>
93
- readonly updateAnswered: () => void | Promise<void>
94
- },
94
+ hooks: { readonly updateAnswered: () => void | Promise<void> },
95
95
  signal?: AbortSignal,
96
96
  ): Promise<unknown> {
97
97
  const answer = await executeLegionTool(runtime, args, signal)
98
- const effect = phaseInputAfter(String(args["op"]), args)
99
- if (effect === "phase-closed") await hooks.phaseClosed()
100
- else if (effect === "update-answered") await hooks.updateAnswered()
98
+ if (args["op"] === "ready_for_update") await hooks.updateAnswered()
101
99
  return answer
102
100
  }