@sjawhar/claude-envoy 4.15.4 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -57643,1309 +57643,350 @@ function sessionsOnMachine(sessions, machine) {
57643
57643
  }
57644
57644
  var envoyToolSchemas = new Map;
57645
57645
 
57646
- // ../contracts/src/legion-claim-recovery.ts
57647
- var nonEmptyString = string2().min(1);
57648
- var LegionClaimRequest = strictObject({
57649
- grantId: nonEmptyString,
57650
- issue: nonEmptyString,
57651
- role: _enum2(LEGION_ROLES)
57652
- });
57653
- var LegionFreshSessionResponse = object({
57654
- phaseNotRestarted: nonEmptyString.optional()
57655
- });
57656
- var LegionCompactResponse = object({
57657
- compacted: boolean2(),
57658
- reason: string2().optional()
57659
- });
57646
+ // ../pi-shared/src/handoff-record.ts
57647
+ import { execFile as execFile2 } from "child_process";
57648
+ import { promisify as promisify2 } from "util";
57660
57649
 
57661
- // ../contracts/src/legion-api.ts
57662
- var nonEmptyString2 = string2().min(1);
57663
- var issueKey = string2().regex(DISPATCH_KEY_PATTERN);
57664
- var timestamp = exports_iso.datetime({ offset: true });
57665
- var LegionInstant = timestamp.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/, { error: "an RFC 3339 time with seconds, as 2026-11-02T09:00:00Z is" });
57666
- var LEGION_WORKFLOW_PHASES = [
57667
- "admitted",
57668
- "awaiting_person",
57669
- "planning",
57670
- "implementing",
57671
- "testing",
57672
- "reviewing",
57673
- "accepting",
57674
- "retro",
57675
- "merging",
57676
- "integrating",
57677
- "done",
57678
- "held"
57679
- ];
57680
- var LEGION_PHASE_BACKWARD_TARGETS = [
57681
- "admitted",
57682
- "planning",
57683
- "implementing",
57684
- "testing",
57685
- "reviewing",
57686
- "accepting",
57687
- "retro",
57688
- "merging",
57689
- "done",
57690
- "held"
57691
- ];
57692
- var LEGION_PHASES = [...LEGION_WORKFLOW_PHASES, "unrecorded"];
57693
- var LEGION_CLAIM_STATES = [
57694
- "queued",
57695
- "launch_uncertain",
57696
- "launching",
57697
- "shim_connected",
57698
- "registered",
57699
- "ready",
57700
- "working",
57701
- "idle",
57702
- "suspended",
57703
- "failed",
57704
- "retired"
57705
- ];
57706
- var legionLocator = discriminatedUnion("runtime", [
57707
- object({
57708
- runtime: literal("tmux"),
57709
- claim: nonEmptyString2,
57710
- incarnation: nonEmptyString2,
57711
- tmux: object({ window: nonEmptyString2, pane: nonEmptyString2 })
57712
- }),
57713
- object({
57714
- runtime: literal("sandbox"),
57715
- claim: nonEmptyString2,
57716
- incarnation: nonEmptyString2,
57717
- sandbox: object({
57718
- namespace: nonEmptyString2,
57719
- name: nonEmptyString2,
57720
- podUid: nonEmptyString2,
57721
- container: nonEmptyString2,
57722
- generation: number2().int().positive()
57723
- })
57724
- })
57725
- ]);
57726
- var legionCapabilityReportView = object({
57727
- measuredAt: timestamp,
57728
- incarnation: string2(),
57729
- ok: array(nonEmptyString2),
57730
- open: array(object({ name: nonEmptyString2, detail: nonEmptyString2 }))
57731
- });
57732
- var legionStepView = object({
57733
- at: timestamp.optional(),
57734
- turnStartedAt: timestamp.optional(),
57735
- tool: nonEmptyString2.optional(),
57736
- callId: nonEmptyString2.optional(),
57737
- argsBytes: number2().int().positive().optional(),
57738
- argsHash: nonEmptyString2.optional(),
57739
- startedAt: timestamp.optional(),
57740
- endedAt: timestamp.optional()
57741
- });
57742
- var LEGION_FAILURE_CAUSES = [
57743
- "launch_refused",
57744
- "died",
57745
- "never_registered",
57746
- "stale_plugin",
57747
- "prompt_retires_exhausted",
57748
- "provider_error",
57749
- "unrecorded"
57750
- ];
57751
- var legionFailureCause = _enum2(LEGION_FAILURE_CAUSES);
57752
- var legionClaimFailureView = object({
57753
- cause: legionFailureCause,
57754
- detail: string2(),
57755
- at: timestamp.optional(),
57756
- attempts: object({
57757
- launchFailures: number2().int().nonnegative(),
57758
- deaths: number2().int().nonnegative(),
57759
- promptFailures: number2().int().nonnegative(),
57760
- promptRetires: number2().int().nonnegative()
57761
- })
57762
- });
57763
- var legionPendingTaskView = object({
57764
- phase: _enum2(LEGION_WORKFLOW_PHASES).optional(),
57765
- queuedAt: timestamp,
57766
- sendFailures: number2().int().positive().optional(),
57767
- lastSendError: nonEmptyString2.optional()
57768
- });
57769
- var legionClaimView = object({
57770
- session: string2(),
57771
- state: _enum2(LEGION_CLAIM_STATES),
57772
- locator: legionLocator.optional(),
57773
- capabilities: legionCapabilityReportView.optional(),
57774
- servingGeneration: number2().int().positive().optional(),
57775
- pluginContract: number2().int().nonnegative(),
57776
- updateRound: nonEmptyString2.optional(),
57777
- updateHead: nonEmptyString2.optional(),
57778
- updateReasons: nonEmptyString2.optional(),
57779
- providerErrorRun: number2().int().positive().optional(),
57780
- pendingTask: legionPendingTaskView.optional(),
57781
- lastTurnStart: timestamp.optional(),
57782
- lastTurnEnd: timestamp.optional(),
57783
- lastDeathCause: nonEmptyString2.optional(),
57784
- lastStartFailure: nonEmptyString2.optional(),
57785
- lastReady: timestamp.optional(),
57786
- step: legionStepView.optional(),
57787
- failure: legionClaimFailureView.optional(),
57788
- pendingCause: legionFailureCause.optional(),
57789
- leakCheckCause: nonEmptyString2.optional()
57790
- });
57791
- var legionHandoffRecordView = object({
57792
- id: nonEmptyString2,
57793
- version: number2().int().positive()
57794
- });
57795
- var legionPhaseView = object({
57796
- claim: legionClaimView,
57797
- handoffCommit: nonEmptyString2.optional(),
57798
- handoffRecord: legionHandoffRecordView.optional(),
57799
- pass: number2().int().nonnegative(),
57800
- rounds: number2().int().nonnegative(),
57801
- backwardMoves: record(string2(), number2().int().positive()).optional()
57802
- });
57803
- var legionMergeState = _enum2([
57804
- "clean",
57805
- "unstable",
57806
- "has_hooks",
57807
- "blocked",
57808
- "dirty",
57809
- "behind",
57810
- "draft",
57811
- "unknown"
57812
- ]);
57813
- var legionPullRequestView = object({
57814
- repo: nonEmptyString2,
57815
- number: number2().int().positive(),
57816
- head: nonEmptyString2,
57817
- state: _enum2(["open", "merged", "closed"]),
57818
- mergeState: legionMergeState.optional(),
57819
- reviewDecision: nonEmptyString2.optional()
57820
- });
57821
- var legionMergeWaitView = object({
57822
- waitsOn: nonEmptyString2,
57823
- mergeState: legionMergeState.optional(),
57824
- stateReadAt: timestamp.optional(),
57825
- headUpdatedAt: timestamp.optional(),
57826
- checkRuns: number2().int().nonnegative(),
57827
- toldHead: nonEmptyString2.optional(),
57828
- toldState: legionMergeState.optional()
57829
- });
57830
- var legionGateView = object({
57831
- artifactId: nonEmptyString2,
57832
- currentVersion: number2().int().positive(),
57833
- approvedVersion: number2().int().positive().nullable()
57834
- });
57835
- var legionDesignStep = _enum2(GATED_STEPS);
57836
- var legionGatedStepView = object({
57837
- step: legionDesignStep,
57838
- artifactId: nonEmptyString2.optional(),
57839
- currentVersion: number2().int().positive().optional(),
57840
- approvedVersion: number2().int().positive().nullable(),
57841
- status: _enum2(["unregistered", "waiting", "approved", "changes_requested"]),
57842
- changesReason: nonEmptyString2.optional()
57843
- });
57844
- var legionSlotView = object({
57845
- index: number2().int().nonnegative(),
57846
- admittedAt: timestamp,
57847
- lentTo: issueKey.optional()
57848
- });
57849
- var legionWaitingLineView = object({
57850
- place: number2().int().positive(),
57851
- length: number2().int().positive(),
57852
- part: _enum2(["returned", "starting"]).optional(),
57853
- kind: _enum2(["returning", "answered", "queued_root", "first_phase", "waiting_on_issue"]).optional(),
57854
- partPlace: number2().int().positive().optional(),
57855
- partLength: number2().int().positive().optional(),
57856
- holdsSlot: boolean2().optional(),
57857
- since: timestamp.optional(),
57858
- rootRank: nonEmptyString2.optional(),
57859
- ownRank: nonEmptyString2.optional(),
57860
- rootKey: issueKey.optional(),
57861
- reason: nonEmptyString2.optional()
57862
- });
57863
- var legionWhyView = object({
57864
- state: _enum2(["claim_stopped", "waiting", "blocked", "unlisted"]),
57865
- reason: nonEmptyString2
57866
- });
57867
- var legionCheckWakeView = object({
57868
- kind: nonEmptyString2,
57869
- detail: string2(),
57870
- at: timestamp
57871
- });
57872
- var legionCheckView = object({
57873
- repo: nonEmptyString2,
57874
- pullRequest: number2().int().positive(),
57875
- mergeCommit: string2(),
57876
- openedAt: timestamp,
57877
- role: nonEmptyString2,
57878
- looks: number2().int().nonnegative(),
57879
- lookOpen: boolean2(),
57880
- lastWake: legionCheckWakeView.optional(),
57881
- nextWakeAt: timestamp,
57882
- last: boolean2()
57883
- });
57884
- var LEGION_WAIT_ANSWERS = [
57885
- "ask",
57886
- "retracted",
57887
- "closed",
57888
- "reply",
57889
- "declined",
57890
- "turn",
57891
- "approved",
57892
- "changes_requested",
57893
- "version"
57650
+ // ../pi-shared/src/git-lock.ts
57651
+ import { lstat } from "fs/promises";
57652
+ var GIT_LOCK_REPORTS = [
57653
+ /The lockfile at '([^']+)' might need manual deletion/g,
57654
+ /Unable to create '([^']+)': File exists/g
57894
57655
  ];
57895
- var legionWaitTimes = {
57896
- since: timestamp.optional(),
57897
- answeredAt: timestamp.optional(),
57898
- answeredBy: _enum2(LEGION_WAIT_ANSWERS).optional()
57656
+ function age(ms) {
57657
+ const total = Math.round(Math.abs(ms) / 1000);
57658
+ const sign = ms < 0 && total > 0 ? "-" : "";
57659
+ const hours = Math.floor(total / 3600);
57660
+ const minutes = Math.floor(total % 3600 / 60);
57661
+ const seconds = total % 60;
57662
+ if (hours > 0)
57663
+ return `${sign}${hours}h${minutes}m${seconds}s`;
57664
+ if (minutes > 0)
57665
+ return `${sign}${minutes}m${seconds}s`;
57666
+ return `${sign}${seconds}s`;
57667
+ }
57668
+ async function staleGitLockNote(output, now = Date.now()) {
57669
+ const locks = new Set;
57670
+ for (const report of GIT_LOCK_REPORTS) {
57671
+ for (const match of output.matchAll(report))
57672
+ locks.add(match[1]);
57673
+ }
57674
+ const notes = [];
57675
+ for (const lock of locks) {
57676
+ const written = await lstat(lock).then((info) => info.mtimeMs, () => {
57677
+ return;
57678
+ });
57679
+ if (written === undefined)
57680
+ continue;
57681
+ notes.push(`git lock ${lock} was last written ${age(now - written)} ago and blocks this command. The launcher of the issue's pod removes a git lock that no process of the pod holds open and that is more than 15 minutes old, and it looks again every minute. Under the tmux runtime nothing removes it: remove it by hand only once no git or jj process on the host is using the repository. Run the command again in about 16 minutes. If the lock is still there after that time, tell the issue's architect.`);
57682
+ }
57683
+ return notes.join(`
57684
+ `);
57685
+ }
57686
+
57687
+ // ../pi-shared/src/handoff-record.ts
57688
+ var FILE_BACKED = {
57689
+ planning: { word: "plan", role: "planner" },
57690
+ implementing: { word: "implement", role: "implementer" },
57691
+ testing: { word: "test", role: "tester" },
57692
+ reviewing: { word: "review", role: "reviewer" }
57899
57693
  };
57900
- var legionWaitingOn = discriminatedUnion("kind", [
57901
- object({ kind: literal("ask"), ask: nonEmptyString2, ...legionWaitTimes }),
57902
- object({
57903
- kind: literal("gate"),
57904
- gateVersion: number2().int().positive(),
57905
- artifactId: nonEmptyString2,
57906
- ...legionWaitTimes
57907
- })
57908
- ]).refine((wait) => wait.answeredAt === undefined === (wait.answeredBy === undefined), {
57909
- message: "answeredAt and answeredBy appear together"
57910
- });
57911
- var legionPendingStatusWrite = object({
57912
- issue: nonEmptyString2,
57913
- payload: record(string2(), unknown()),
57914
- attempts: number2().int().nonnegative(),
57915
- nextAt: timestamp,
57916
- lastError: string2().optional()
57917
- });
57918
- var legionStrandedClaim = object({
57919
- issue: issueKey,
57920
- role: _enum2(LEGION_ROLES),
57921
- state: _enum2(["suspended", "failed", "retired"])
57922
- });
57923
- var legionHeldOutboxRow = object({
57924
- id: number2().int().positive(),
57925
- kind: nonEmptyString2,
57926
- issue: nonEmptyString2,
57927
- waitedSeconds: number2().int().nonnegative(),
57928
- waitsOn: number2().int().positive()
57929
- });
57930
- var legionWakeWaiting = object({
57931
- claim: nonEmptyString2,
57932
- issue: issueKey,
57933
- role: _enum2(LEGION_ROLES),
57934
- kind: nonEmptyString2,
57935
- dueAt: timestamp
57936
- });
57937
- var legionAssignment = object({
57938
- experiment: nonEmptyString2,
57939
- variant: string2(),
57940
- mode: string2(),
57941
- drawnAt: timestamp.optional()
57942
- });
57943
- var legionIssue = object({
57944
- key: nonEmptyString2,
57945
- generation: number2().int().nonnegative(),
57946
- phase: _enum2(LEGION_PHASES),
57947
- status: nonEmptyString2,
57948
- tree: issueKey.optional(),
57949
- repo: nonEmptyString2.optional(),
57950
- defaultBranch: nonEmptyString2.optional(),
57951
- holdReason: literal("escalated").optional(),
57952
- heldFrom: _enum2(LEGION_WORKFLOW_PHASES).optional(),
57953
- lingerUntil: timestamp.optional(),
57954
- ancestry: array(issueKey).optional(),
57955
- architect: legionClaimView.optional(),
57956
- workers: partialRecord(string2(), legionPhaseView),
57957
- pullRequest: legionPullRequestView.optional(),
57958
- designGate: legionGateView.optional(),
57959
- gatedSteps: array(legionGatedStepView).optional(),
57960
- slot: legionSlotView.optional(),
57961
- waitingLine: legionWaitingLineView.optional(),
57962
- why: legionWhyView.optional(),
57963
- waitingOn: legionWaitingOn.optional(),
57964
- check: legionCheckView.optional(),
57965
- mergeWait: legionMergeWaitView.optional(),
57966
- memoryGroup: _enum2(["memory", "none"]).optional(),
57967
- memoryDrawMode: _enum2(["off", "on", "random"]).optional(),
57968
- memoryDrawnAt: timestamp.optional(),
57969
- phaseEntry: number2().int().nonnegative().optional(),
57970
- givenEntry: number2().int().nonnegative().optional(),
57971
- entryQueuedAt: timestamp.optional(),
57972
- entryConfirmedAt: timestamp.optional(),
57973
- architectStalls: array(_enum2(["took-nothing", "claim-unreachable", "slow-before-gate"])).optional(),
57974
- treeMovedAt: timestamp.optional(),
57975
- quietHours: number2().nonnegative().optional(),
57976
- assignments: array(legionAssignment).optional()
57977
- });
57978
- var daemonInfo = object({
57979
- project: nonEmptyString2,
57980
- schemaVersion: number2().int().nonnegative(),
57981
- boots: number2().int().nonnegative(),
57982
- firstBootAt: timestamp,
57983
- startedAt: timestamp
57984
- });
57985
- var legionContract = object({
57986
- daemon: number2().int().positive(),
57987
- caller: number2().int().positive().optional()
57988
- });
57989
- var legionBlockedIssue = object({
57990
- issue: issueKey,
57991
- blockedBy: array(issueKey)
57992
- });
57993
- var LEGION_HELD_REASONS = [
57994
- "tree_closed",
57995
- "tree_parked",
57996
- "label_off",
57997
- "ancestry",
57998
- "root_awaiting_person",
57999
- "design_gate",
58000
- "dispatch_blocker",
58001
- "children_first",
58002
- "accepted_ancestor",
58003
- "at_work",
58004
- "unclassified"
58005
- ];
58006
- var legionHeldIssue = object({
58007
- issue: issueKey,
58008
- reason: _enum2(LEGION_HELD_REASONS),
58009
- heldBy: array(issueKey).optional()
58010
- });
58011
- var legionAdmission = object({
58012
- cap: number2().int().nonnegative(),
58013
- active: array(nonEmptyString2),
58014
- waiting: array(nonEmptyString2),
58015
- trees: array(issueKey).optional(),
58016
- blocked: array(legionBlockedIssue),
58017
- held: array(legionHeldIssue).optional(),
58018
- free: number2().int().nonnegative().optional()
58019
- });
58020
- var legionControllerLocator = object({
58021
- runtime: _enum2(["tmux", "kubernetes"]),
58022
- external: literal(true),
58023
- sessionId: nonEmptyString2,
58024
- registeredAt: timestamp,
58025
- pluginContract: number2().int().nonnegative()
58026
- });
58027
- var legionAgentSecretsLoginView = object({
58028
- state: string2()
58029
- });
58030
- var legionCapabilityState = object({
58031
- name: nonEmptyString2,
58032
- status: _enum2(["present", "unchecked", "withheld", "decided", "open"]),
58033
- detail: nonEmptyString2,
58034
- decision: nonEmptyString2.optional(),
58035
- configLine: nonEmptyString2.optional(),
58036
- source: _enum2(["configuration", "boot"]).optional()
58037
- });
58038
- var legionSettings = looseObject({
58039
- review_round_cap: number2().int().positive(),
58040
- worker_boot_timeout_seconds: number2().int().positive()
58041
- });
58042
- var legionCacheView = object({
58043
- repo: nonEmptyString2,
58044
- sandbox: nonEmptyString2,
58045
- state: _enum2(["starting", "cloning", "ready", "failing", "refused"]),
58046
- reason: nonEmptyString2.optional(),
58047
- ready: boolean2(),
58048
- address: nonEmptyString2.optional(),
58049
- head: nonEmptyString2.optional(),
58050
- lastFetchAt: timestamp.optional(),
58051
- bytes: number2().int().positive().optional(),
58052
- healthError: nonEmptyString2.optional(),
58053
- retainedUntil: timestamp.optional()
58054
- });
58055
- var legionAppInstallations = object({ implement: boolean2(), review: boolean2() });
58056
- var legionRepositories = object({
58057
- owners: array(nonEmptyString2),
58058
- mapped: array(object({
58059
- repo: nonEmptyString2,
58060
- default: boolean2(),
58061
- apps: legionAppInstallations.optional(),
58062
- cache: legionCacheView.optional()
58063
- })),
58064
- refused: array(object({
58065
- repo: nonEmptyString2,
58066
- reason: nonEmptyString2,
58067
- apps: legionAppInstallations.optional()
58068
- })),
58069
- withoutWebhookApp: array(object({ repo: nonEmptyString2, reason: nonEmptyString2 })),
58070
- caches: array(legionCacheView)
58071
- });
58072
- var legionConsumerLag = object({
58073
- name: nonEmptyString2,
58074
- waiting: number2().int().nonnegative(),
58075
- oldestAt: timestamp.nullable(),
58076
- oldestAgeSeconds: number2().int().nullable(),
58077
- lastHandledAt: timestamp.nullable(),
58078
- stalled: boolean2(),
58079
- unavailable: nonEmptyString2.optional()
58080
- });
58081
- var legionPauseActor = discriminatedUnion("kind", [
58082
- object({ kind: literal("controller"), session: nonEmptyString2 }),
58083
- object({ kind: literal("operator") })
58084
- ]);
58085
- var pauseFields = {
58086
- id: number2().int().positive(),
58087
- since: timestamp,
58088
- by: legionPauseActor,
58089
- reason: nonEmptyString2
58090
- };
58091
- var legionPause = object({
58092
- ...pauseFields,
58093
- endedAt: timestamp.optional(),
58094
- endedBy: legionPauseActor.optional()
58095
- });
58096
- var legionEndedPause = object({
58097
- ...pauseFields,
58098
- endedAt: timestamp,
58099
- endedBy: legionPauseActor
58100
- });
58101
- var legionPauseStop = object({
58102
- claim: nonEmptyString2,
58103
- issue: issueKey,
58104
- role: _enum2(LEGION_ROLES),
58105
- askedAt: timestamp
58106
- });
58107
- var legionPauseHeldRow = object({
58108
- id: number2().int().positive(),
58109
- kind: nonEmptyString2,
58110
- issue: nonEmptyString2,
58111
- claim: nonEmptyString2.optional(),
58112
- waitedSeconds: number2().int().nonnegative()
58113
- });
58114
- var legionPaused = object({
58115
- ...pauseFields,
58116
- waitsOn: array(legionPauseStop),
58117
- held: array(legionPauseHeldRow)
58118
- });
58119
- var LegionStateResponse = object({
58120
- daemon: daemonInfo,
58121
- contract: legionContract.optional(),
58122
- admission: legionAdmission,
58123
- issues: record(string2(), legionIssue),
58124
- pendingStatusWrites: array(legionPendingStatusWrite),
58125
- heldOutboxRows: array(legionHeldOutboxRow),
58126
- strandedClaims: array(legionStrandedClaim),
58127
- wakesWaiting: array(legionWakeWaiting).optional(),
58128
- claimsToRefresh: number2().int().nonnegative().optional(),
58129
- paused: legionPaused.optional(),
58130
- lastPause: legionEndedPause.optional(),
58131
- controllerLocator: legionControllerLocator.optional(),
58132
- agentSecretsLogin: legionAgentSecretsLoginView.optional(),
58133
- capabilities: array(legionCapabilityState),
58134
- repositories: legionRepositories,
58135
- settings: legionSettings,
58136
- consumers: array(legionConsumerLag)
58137
- });
58138
- var LegionRegisterResponse = object({
58139
- claimToken: nonEmptyString2,
58140
- tree: nonEmptyString2,
58141
- issue: nonEmptyString2,
58142
- role: _enum2(LEGION_ROLES),
58143
- generation: number2().int().positive(),
58144
- secret: nonEmptyString2,
58145
- promptAgents: array(nonEmptyString2)
58146
- });
58147
- var LegionCapabilityReport = strictObject({
58148
- measuredAt: timestamp,
58149
- elapsedMs: number2().int().nonnegative(),
58150
- rows: array(strictObject({ name: nonEmptyString2, ok: boolean2(), detail: string2() }))
58151
- });
58152
- var LegionReadyRequest = strictObject({
58153
- claimToken: nonEmptyString2,
58154
- sessionId: nonEmptyString2,
58155
- secret: nonEmptyString2,
58156
- generation: number2().int().positive(),
58157
- capabilities: LegionCapabilityReport.optional()
58158
- });
58159
- var turnOutcomeFields = {
58160
- generation: number2().int().positive(),
58161
- sequence: number2().int().positive(),
58162
- outcome: _enum2(["clean", "refused"]),
58163
- message: string2().optional()
57694
+ var execFileAsync2 = promisify2(execFile2);
57695
+ var pathJj = async (args, cwd) => {
57696
+ try {
57697
+ const { stdout } = await execFileAsync2("jj", ["-R", cwd, ...args], {
57698
+ cwd,
57699
+ maxBuffer: 16 * 1024 * 1024
57700
+ });
57701
+ return stdout.trim();
57702
+ } catch (error) {
57703
+ const detail = error !== null && typeof error === "object" && "stderr" in error ? String(error.stderr).trim() : error instanceof Error ? error.message : String(error);
57704
+ const note = await staleGitLockNote(detail);
57705
+ throw new Error(`jj ${args.join(" ")} failed: ${detail}${note === "" ? "" : `
57706
+ ${note}`}`);
57707
+ }
58164
57708
  };
58165
- var LegionTurnOutcomeAgentRequest = strictObject({
58166
- claimToken: nonEmptyString2,
58167
- sessionId: nonEmptyString2,
58168
- secret: nonEmptyString2,
58169
- ...turnOutcomeFields
58170
- });
58171
- var LegionTurnOutcomeBootRequest = strictObject({
58172
- bootToken: nonEmptyString2,
58173
- ...turnOutcomeFields
58174
- });
58175
- var LegionTurnOutcomeRequest = union([
58176
- LegionTurnOutcomeAgentRequest,
58177
- LegionTurnOutcomeBootRequest
58178
- ]);
58179
- var LegionTurnOutcomeResponse = object({
58180
- refusedRun: number2().int().nonnegative(),
58181
- failed: boolean2()
58182
- });
58183
- var LegionReadyForUpdateRequest = strictObject({
58184
- claimToken: nonEmptyString2,
58185
- sessionId: nonEmptyString2,
58186
- secret: nonEmptyString2,
58187
- generation: number2().int().positive(),
58188
- round: nonEmptyString2,
58189
- head: string2().optional()
58190
- });
58191
- var LegionSessionActivity = strictObject({
58192
- at: timestamp,
58193
- backgroundWork: strictObject({ running: boolean2(), kinds: array(nonEmptyString2) }),
58194
- phase: strictObject({ nextReminderAt: timestamp.nullable() })
58195
- });
58196
- var LegionActivityRequest = strictObject({
58197
- claimToken: nonEmptyString2,
58198
- sessionId: nonEmptyString2,
58199
- secret: nonEmptyString2,
58200
- activity: LegionSessionActivity
58201
- });
58202
- var legionReleaseRecord = object({
58203
- id: number2().int().positive(),
58204
- issue: issueKey,
58205
- generation: number2().int().nonnegative(),
58206
- roles: array(nonEmptyString2),
58207
- at: timestamp,
58208
- bundleBytes: number2().int().nonnegative()
58209
- });
58210
- var legionResumeRecord = object({
58211
- id: number2().int().positive(),
58212
- release: number2().int().nonnegative(),
58213
- issue: issueKey,
58214
- role: nonEmptyString2,
58215
- kind: nonEmptyString2,
58216
- at: timestamp,
58217
- podReadyAt: timestamp.optional(),
58218
- firstTurnAt: timestamp.optional(),
58219
- stuck: boolean2(),
58220
- pause: number2().int().positive().optional()
58221
- });
58222
- var legionHoldRecord = object({
58223
- id: number2().int().positive(),
58224
- issue: issueKey,
58225
- reason: nonEmptyString2,
58226
- detail: nonEmptyString2.optional(),
58227
- firstAt: timestamp,
58228
- at: timestamp,
58229
- passes: number2().int().positive()
58230
- });
58231
- var LegionReleaseRecordsRequest = strictObject({
58232
- claimToken: nonEmptyString2,
58233
- secret: nonEmptyString2,
58234
- since: LegionInstant
58235
- });
58236
- var LegionReleaseRecordsResponse = object({
58237
- releases: array(legionReleaseRecord),
58238
- resumes: array(legionResumeRecord),
58239
- holds: array(legionHoldRecord)
58240
- });
58241
- var LegionControllerRegisterResponse = object({
58242
- claimToken: nonEmptyString2,
58243
- role: literal("controller"),
58244
- generation: number2().int().positive(),
58245
- secret: nonEmptyString2
58246
- });
58247
- var LegionControllerSecretResponse = object({
58248
- secret: nonEmptyString2,
58249
- designGateSteps: array(legionDesignStep)
58250
- });
58251
- var LegionControllerCredentialResponse = object({
58252
- owners: record(nonEmptyString2, object({
58253
- hosts: nonEmptyString2,
58254
- config: nonEmptyString2
58255
- })),
58256
- default: nonEmptyString2,
58257
- app: _enum2(["implement", "review"]),
58258
- expiresAt: timestamp,
58259
- renames: array(object({ from: nonEmptyString2, to: nonEmptyString2 })).optional(),
58260
- installed: array(nonEmptyString2)
58261
- });
58262
- var LegionErrorResponse = object({
58263
- error: nonEmptyString2,
58264
- code: nonEmptyString2.optional()
58265
- });
58266
- var legionDeliveryView = object({
58267
- id: nonEmptyString2,
58268
- task: nonEmptyString2,
58269
- phase: _enum2(LEGION_WORKFLOW_PHASES).optional(),
58270
- queuedAt: timestamp,
58271
- deliveredAt: timestamp.optional(),
58272
- confirmedAt: timestamp.optional(),
58273
- interrupted: literal(true).optional(),
58274
- sendFailures: number2().int().nonnegative().optional(),
58275
- lastSendFailureAt: timestamp.optional(),
58276
- lastSendError: nonEmptyString2.optional()
58277
- });
58278
- var legionSuspendedBy = _enum2(["unknown", "operator", "daemon", "exit", "released"]);
58279
- var LegionOperatorClaimResponse = object({
58280
- token: nonEmptyString2,
58281
- tree: nonEmptyString2,
58282
- issue: nonEmptyString2,
58283
- role: _enum2(LEGION_ROLES),
58284
- generation: number2().int().nonnegative(),
58285
- state: _enum2(LEGION_CLAIM_STATES),
58286
- session: string2(),
58287
- sessionFile: string2(),
58288
- forgottenSession: nonEmptyString2.optional(),
58289
- forgottenSessionFile: nonEmptyString2.optional(),
58290
- phaseNotRestarted: nonEmptyString2.optional(),
58291
- locator: legionLocator.optional(),
58292
- budgets: object({
58293
- launchFailures: number2().int().nonnegative(),
58294
- deaths: number2().int().nonnegative(),
58295
- promptFailures: number2().int().nonnegative(),
58296
- promptRetires: number2().int().nonnegative()
58297
- }),
58298
- uncertainStreak: number2().int().nonnegative(),
58299
- pending: legionDeliveryView.optional(),
58300
- suspendedBy: legionSuspendedBy.optional(),
58301
- suspensionHeld: literal(true).optional(),
58302
- suspensionHeldBy: legionSuspendedBy.optional(),
58303
- compacting: literal(true).optional(),
58304
- processGone: literal(true).optional(),
58305
- pluginContract: number2().int().nonnegative(),
58306
- updateRound: nonEmptyString2.optional(),
58307
- updateHead: nonEmptyString2.optional(),
58308
- lastTurnStart: timestamp.optional(),
58309
- lastTurnEnd: timestamp.optional(),
58310
- lastDeathCause: nonEmptyString2.optional(),
58311
- lastStartFailure: nonEmptyString2.optional(),
58312
- lastReady: timestamp.optional(),
58313
- step: legionStepView.optional(),
58314
- failure: legionClaimFailureView.optional(),
58315
- leakCheckCause: nonEmptyString2.optional()
58316
- });
58317
- var legionPodUpdateRounds = object({
58318
- swept: boolean2(),
58319
- max_open_rounds: number2().int().nullable(),
58320
- rounds_per_minute: number2().int().nullable(),
58321
- in_round: array(nonEmptyString2),
58322
- waiting_on_max_open_rounds: array(nonEmptyString2),
58323
- waiting_on_rounds_per_minute: array(nonEmptyString2)
58324
- });
58325
- var LegionOperatorClaimsResponse = object({
58326
- claims: array(LegionOperatorClaimResponse),
58327
- pod_update_rounds: legionPodUpdateRounds
58328
- });
58329
- var LegionGrantResponse = object({
58330
- grantId: nonEmptyString2,
58331
- expiresAt: timestamp
58332
- });
58333
- var LegionEmptyResponse = object({});
58334
- var LegionHandoffCompleteResponse = object({});
58335
- var LegionWaveReleaseResponse = object({
58336
- released: array(nonEmptyString2),
58337
- started: array(issueKey),
58338
- held: array(legionBlockedIssue)
58339
- });
58340
- var LegionProjectPauseResponse = object({
58341
- pause: legionPause
58342
- });
58343
- var LegionProjectResumeResponse = object({
58344
- pause: legionEndedPause,
58345
- released: number2().int().nonnegative()
58346
- });
58347
- var LegionPauseFailureResponse = object({
58348
- code: nonEmptyString2,
58349
- error: nonEmptyString2,
58350
- setting: nonEmptyString2.optional(),
58351
- pause: legionPause.optional(),
58352
- lastPause: legionEndedPause.optional()
58353
- });
58354
- var LegionGrantRequest = strictObject({
58355
- sessionId: nonEmptyString2,
58356
- secret: nonEmptyString2,
58357
- tree: nonEmptyString2,
58358
- issue: nonEmptyString2
58359
- });
58360
- var LegionControllerGrantRequest = strictObject({
58361
- sessionId: nonEmptyString2,
58362
- secret: nonEmptyString2
58363
- });
58364
- function legionPlanRatingScale(rating, refusal) {
58365
- const error = refusal === undefined ? undefined : { error: refusal };
58366
- return rating.int(error).min(LEGION_PLAN_RATING_LEAST, error).max(LEGION_PLAN_RATING_MOST, error);
57709
+ function paneLatestHandoff(file, env, cwd, session, fetchImpl = fetch) {
57710
+ return async (issue, word) => {
57711
+ const { dispatch } = sessionDispatchSettings(file, env, { cwd, session });
57712
+ if (!dispatch.enabled) {
57713
+ throw new Error(`Dispatch is off for this pane: ${dispatch.error ?? dispatch.notice}`);
57714
+ }
57715
+ return new DispatchClient(dispatch.url, dispatch.credential, fetchImpl).latestHandoff(issue, word);
57716
+ };
58367
57717
  }
58368
- function legionPlanReasonRules(reason, refusals) {
58369
- return reason.refine((text) => !goBlankPattern.test(text), { error: refusals.blank, abort: true }).refine((text) => [...text].length <= LEGION_PLAN_REASON_MAX, { error: refusals.long });
57718
+ function paneHandoffReport(file, env, cwd, session) {
57719
+ return (phase, role) => findHandoffReport({
57720
+ phase,
57721
+ role,
57722
+ env,
57723
+ latestHandoff: paneLatestHandoff(file, env, cwd, session)
57724
+ });
58370
57725
  }
58371
- var legionPlanReason = legionPlanReasonRules(string2(), {
58372
- blank: "planReason says why",
58373
- long: `planReason holds at most ${LEGION_PLAN_REASON_MAX} characters`
58374
- });
58375
- function legionPlanRatingLoneField(rating, reason) {
58376
- if (rating !== undefined && reason === undefined)
58377
- return "rating";
58378
- if (reason !== undefined && rating === undefined)
58379
- return "reason";
58380
- return;
57726
+ function requiredVariable(env, name, purpose) {
57727
+ const value = env[name];
57728
+ if (value === undefined || value === "") {
57729
+ throw new Error(`${name} is not set, so ${purpose}`);
57730
+ }
57731
+ return value;
58381
57732
  }
58382
- var LegionHandoffCompleteRequest = strictObject({
58383
- grantId: nonEmptyString2,
58384
- summary: nonEmptyString2,
58385
- verdict: string2(),
58386
- commit: nonEmptyString2.optional(),
58387
- handoffId: nonEmptyString2.optional(),
58388
- handoffVersion: number2().int().positive().optional(),
58389
- wakeAt: LegionInstant.optional(),
58390
- planRating: legionPlanRatingScale(number2()).optional(),
58391
- planReason: legionPlanReason.optional()
58392
- }).refine((request) => legionPlanRatingLoneField(request.planRating, request.planReason) === undefined, { message: "planRating and planReason appear together" });
58393
- var LegionIssueStatusRequest = strictObject({
58394
- grantId: nonEmptyString2,
58395
- issue: nonEmptyString2,
58396
- status: _enum2(["todo", "backlog", "icebox"])
58397
- });
58398
- var LegionProjectPauseRequest = strictObject({
58399
- grantId: nonEmptyString2,
58400
- reason: nonEmptyString2
58401
- });
58402
- var LegionProjectResumeRequest = strictObject({
58403
- grantId: nonEmptyString2
58404
- });
58405
- var LegionOperatorProjectPauseRequest = strictObject({
58406
- reason: nonEmptyString2
58407
- });
58408
- var LegionGateRegisterRequest = strictObject({
58409
- grantId: nonEmptyString2,
58410
- issue: nonEmptyString2,
58411
- artifactId: uuid2(),
58412
- version: number2().int().positive(),
58413
- step: legionDesignStep.optional()
58414
- });
58415
- var LegionWaveReleaseRequest = strictObject({
58416
- grantId: nonEmptyString2,
58417
- issues: array(nonEmptyString2)
58418
- });
58419
- var LegionPhaseBackwardRequest = strictObject({
58420
- grantId: nonEmptyString2,
58421
- to: _enum2(LEGION_PHASE_BACKWARD_TARGETS),
58422
- reason: nonEmptyString2,
58423
- issue: nonEmptyString2.optional()
58424
- });
58425
- var LegionPhaseRetryRequest = strictObject({
58426
- grantId: nonEmptyString2,
58427
- issue: nonEmptyString2,
58428
- decision: _enum2(["retry", "escalate"]),
58429
- reason: nonEmptyString2.optional()
58430
- });
58431
- var LegionEscalateRequest = strictObject({
58432
- grantId: nonEmptyString2,
58433
- issue: nonEmptyString2,
58434
- reason: nonEmptyString2
58435
- });
58436
- var LegionSignOffRequest = strictObject({
58437
- grantId: nonEmptyString2,
58438
- issue: nonEmptyString2
58439
- });
58440
- var LegionRootCloseRequest = strictObject({
58441
- grantId: nonEmptyString2,
58442
- issue: nonEmptyString2,
58443
- reason: nonEmptyString2
58444
- });
58445
- var LegionChildRequest = strictObject({
58446
- grantId: nonEmptyString2,
58447
- issue: nonEmptyString2
58448
- });
58449
-
58450
- // ../pi-shared/src/daemon-client.ts
58451
- class LegionDaemonApiError extends Error {
58452
- method;
58453
- path;
58454
- status;
58455
- code;
58456
- detail;
58457
- constructor(method, path, status, code, detail) {
58458
- super(`${method} ${path} failed with ${status}${code === undefined ? "" : ` ${code}`}: ${detail}`);
58459
- this.method = method;
58460
- this.path = path;
58461
- this.status = status;
58462
- this.code = code;
58463
- this.detail = detail;
58464
- this.name = "LegionDaemonApiError";
57733
+ var FOR_HANDOFF = "handoff_complete cannot find what to report";
57734
+ function issueBranch(env, purpose) {
57735
+ const issue = requiredVariable(env, "LEGION_ISSUE", purpose);
57736
+ if (!DISPATCH_KEY_PATTERN.test(issue)) {
57737
+ throw new Error(`LEGION_ISSUE ${JSON.stringify(issue)} is not a Dispatch issue key like LEGION-1`);
58465
57738
  }
57739
+ return { issue, bookmark: `legion/${issue}` };
58466
57740
  }
58467
-
58468
- class LegionDaemonContractError extends Error {
58469
- method;
58470
- path;
58471
- status;
58472
- constructor(method, path, status, problem) {
58473
- super(`${method} ${path} answered ${status} with a body the daemon API contract does not describe: ${problem}`);
58474
- this.method = method;
58475
- this.path = path;
58476
- this.status = status;
58477
- this.name = "LegionDaemonContractError";
57741
+ function pushedBranch(bookmark) {
57742
+ return `remote_bookmarks(exact:${JSON.stringify(bookmark)}, exact:"origin")`;
57743
+ }
57744
+ var STANDING = ["log", "-r", "@-", "--no-graph", "-T", "commit_id"];
57745
+ var RECORD_HEAD = /^[0-9a-f]{40}$/;
57746
+ function recordHead(body) {
57747
+ let parsed;
57748
+ try {
57749
+ parsed = JSON.parse(body);
57750
+ } catch {
57751
+ return;
58478
57752
  }
57753
+ if (parsed === null || typeof parsed !== "object" || !("head" in parsed))
57754
+ return;
57755
+ const head = parsed.head;
57756
+ return typeof head === "string" && RECORD_HEAD.test(head) ? head : undefined;
58479
57757
  }
58480
- var READY_RETRY_ATTEMPTS = 3;
58481
- var READY_RETRY_DELAY_MS = 1000;
58482
- function isNetworkOrTimeoutError(error) {
58483
- if (!(error instanceof Error))
58484
- return false;
58485
- if (error.name === "NetworkError" || error.name === "TimeoutError")
58486
- return true;
58487
- const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
58488
- return code === "ConnectionRefused" || code === "ConnectionTimeout" || code === "EAI_AGAIN" || code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EHOSTUNREACH" || code === "ENETUNREACH" || code === "ENOTFOUND" || code === "ETIMEDOUT" || error instanceof TypeError && (error.message === "Failed to fetch" || error.message === "fetch failed");
57758
+ async function findPushedBranchHead(input) {
57759
+ const { env } = input;
57760
+ const jj = input.jj ?? pathJj;
57761
+ const purpose = "ready_for_update cannot find the branch head to report";
57762
+ const workspace = requiredVariable(env, "LEGION_WORKSPACE", purpose);
57763
+ const { bookmark } = issueBranch(env, purpose);
57764
+ return jj(["log", "-r", pushedBranch(bookmark), "--no-graph", "-T", "commit_id"], workspace);
58489
57765
  }
58490
- async function callReadyWithRetry(label, call) {
58491
- for (let attempt = 1;; attempt++) {
58492
- try {
58493
- await call();
58494
- return;
58495
- } catch (error) {
58496
- const retryable = error instanceof LegionDaemonApiError ? error.status >= 500 && error.status < 600 : isNetworkOrTimeoutError(error);
58497
- if (!retryable)
58498
- throw error;
58499
- if (attempt === READY_RETRY_ATTEMPTS) {
58500
- console.error(`[legion] ${label} failed after ${attempt} attempts: ${messageFor(error)}`);
58501
- throw error;
58502
- }
58503
- console.error(`[legion] ${label} failed (attempt ${attempt}/${READY_RETRY_ATTEMPTS}), retrying: ${messageFor(error)}`);
58504
- const retryDelay = Promise.withResolvers();
58505
- setTimeout(retryDelay.resolve, READY_RETRY_DELAY_MS);
58506
- await retryDelay.promise;
58507
- }
57766
+ function completedPhase(role, at) {
57767
+ switch (role) {
57768
+ case "planner":
57769
+ return "planning";
57770
+ case "tester":
57771
+ return "testing";
57772
+ case "reviewer":
57773
+ return "reviewing";
57774
+ case "merger":
57775
+ return "merging";
57776
+ case "implementer":
57777
+ if (at === "implementing" || at === "retro")
57778
+ return at;
57779
+ return at === "merging" ? "retro" : "implementing";
57780
+ case "architect":
57781
+ return at;
58508
57782
  }
58509
57783
  }
58510
- var DAEMON_RESTART_BUDGET_MS = 10 * 60000;
58511
- var DAEMON_RESTART_FIRST_DELAY_MS = 500;
58512
- var DAEMON_RESTART_MAX_DELAY_MS = 30000;
58513
- function daemonUnreachable(error) {
58514
- if (error instanceof LegionDaemonApiError) {
58515
- return (error.status === 502 || error.status === 503) && error.code === undefined ? "dropped" : undefined;
58516
- }
58517
- if (!(error instanceof Error))
58518
- return;
58519
- const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
58520
- if (code === "ConnectionRefused" || code === "ECONNREFUSED")
58521
- return "refused";
58522
- if (code === "ConnectionClosed" || code === "ECONNRESET" || code === "EPIPE")
58523
- return "dropped";
58524
- return error instanceof TypeError && (error.message === "Failed to fetch" || error.message === "fetch failed") ? "dropped" : undefined;
57784
+ async function standingReport(env, jj) {
57785
+ return { commit: await jj(STANDING, requiredVariable(env, "LEGION_WORKSPACE", FOR_HANDOFF)) };
58525
57786
  }
58526
- async function retryWhileDaemonRestarts(label, call, options = {}) {
58527
- const { signal } = options;
58528
- const now = options.now ?? Date.now;
58529
- const sleep = options.sleep ?? ((ms, abort) => {
58530
- const wait = Promise.withResolvers();
58531
- const timer = setTimeout(wait.resolve, ms);
58532
- abort?.addEventListener("abort", () => {
58533
- clearTimeout(timer);
58534
- wait.resolve();
58535
- }, { once: true });
58536
- return wait.promise;
58537
- });
58538
- const deadline = now() + DAEMON_RESTART_BUDGET_MS;
58539
- let delay = DAEMON_RESTART_FIRST_DELAY_MS;
58540
- let told = false;
58541
- let dropped = false;
58542
- let lastFailure;
58543
- for (;; ) {
58544
- if (signal?.aborted && lastFailure !== undefined) {
58545
- throw new Error(`${label}: the Legion daemon was unreachable (${messageFor(lastFailure)}) and the call was aborted${dropped ? "; an attempt lost its connection before the daemon answered and may have been applied, so read the record before calling again" : "; call it again once the daemon is back"}`);
58546
- }
58547
- try {
58548
- return await call();
58549
- } catch (error) {
58550
- const unreachable = daemonUnreachable(error);
58551
- if (unreachable === undefined) {
58552
- if (dropped && error instanceof LegionDaemonApiError) {
58553
- error.message += ` (an earlier attempt of ${label} lost its connection before the daemon answered, and may have been applied: read the record before calling again)`;
58554
- }
58555
- throw error;
58556
- }
58557
- lastFailure = error;
58558
- dropped ||= unreachable === "dropped";
58559
- const remaining = deadline - now();
58560
- if (remaining <= 0) {
58561
- throw new Error(`${label}: the Legion daemon was unreachable (${messageFor(error)}) and stayed so for ${DAEMON_RESTART_BUDGET_MS / 60000} minutes${dropped ? "; an attempt lost its connection before the daemon answered and may have been applied, so read the record before calling again" : "; call it again once the daemon is back"}`);
58562
- }
58563
- if (!told && !signal?.aborted) {
58564
- told = true;
58565
- const message = `The Legion daemon is unreachable, most likely restarting (${messageFor(error)}); ${label} is being retried for up to ${DAEMON_RESTART_BUDGET_MS / 60000} minutes.`;
58566
- console.error(`[legion] ${message}`);
58567
- options.onRetrying?.(message);
58568
- }
58569
- if (!signal?.aborted)
58570
- await sleep(Math.min(delay, remaining), signal);
58571
- delay = Math.min(delay * 2, DAEMON_RESTART_MAX_DELAY_MS);
57787
+ async function findHandoffReport(input) {
57788
+ const { role, env } = input;
57789
+ const jj = input.jj ?? pathJj;
57790
+ const of = completedPhase(role, input.phase);
57791
+ const handoff = FILE_BACKED[of];
57792
+ if (handoff === undefined || handoff.role !== role)
57793
+ return standingReport(env, jj);
57794
+ const works = of === input.phase;
57795
+ const { issue, bookmark } = issueBranch(env, FOR_HANDOFF);
57796
+ let record;
57797
+ try {
57798
+ record = await input.latestHandoff(issue, handoff.word);
57799
+ } catch (error) {
57800
+ if (error instanceof DispatchServiceError && error.fromDispatch && error.code === "HANDOFF_NOT_FOUND") {
57801
+ if (!works)
57802
+ return standingReport(env, jj);
57803
+ throw new Error(`${issue} has no ${handoff.word} handoff in Dispatch: write it with \`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`, then complete again`);
58572
57804
  }
57805
+ const answer = error instanceof DispatchServiceError && error.fromDispatch ? `${error.status} ${error.code}: ${error.message}` : messageFor(error);
57806
+ throw new Error(`handoff_complete could not read ${issue}'s newest ${handoff.word} handoff from Dispatch: ${answer}; complete again once Dispatch answers`);
57807
+ }
57808
+ const report = { handoffId: record.id, handoffVersion: record.version };
57809
+ const head = recordHead(record.body);
57810
+ if (role !== "implementer" || !works) {
57811
+ if (head !== undefined)
57812
+ return { commit: head, ...report };
57813
+ if (role !== "implementer")
57814
+ return report;
57815
+ return standingReport(env, jj);
57816
+ }
57817
+ if (head === undefined) {
57818
+ throw new Error(`the newest ${handoff.word} handoff of ${issue} (version ${record.version}) names no head: write the handoff again with \`head\` set to the 40-character lower-case commit you pushed as \`@-\`, as \`jj -R "$LEGION_WORKSPACE" log -r @- --no-graph -T commit_id\` prints it once the push succeeded (\`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`), then complete again`);
57819
+ }
57820
+ const workspace = requiredVariable(env, "LEGION_WORKSPACE", FOR_HANDOFF);
57821
+ const stands = await jj(STANDING, workspace);
57822
+ const tip = await jj(["log", "-r", `${pushedBranch(bookmark)} & ${stands}::`, "--no-graph", "-T", "commit_id"], workspace);
57823
+ if (tip === "") {
57824
+ throw new Error(`the commit this workspace stands on, ${stands}, is not on ${bookmark}@origin: push it with \`jj bookmark set ${bookmark} -r @- && jj git push --bookmark ${bookmark}\`; the handoff's \`head\` must name that pushed commit, and the newest ${handoff.word} handoff of ${issue} (version ${record.version}) names ${head}, so when that is another commit, write the handoff again with \`head\` set to ${stands} (\`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`); then complete again`);
58573
57825
  }
57826
+ if (head !== stands) {
57827
+ throw new Error(`the newest ${handoff.word} handoff of ${issue} (version ${record.version}) names ${head} as its head, not the commit this workspace stands on, ${stands}, which ${bookmark}@origin carries: write the handoff again with \`head\` set to ${stands} (\`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`), then complete again`);
57828
+ }
57829
+ return { commit: head, ...report };
58574
57830
  }
58575
- function parseBody(schema, body) {
58576
- let json;
58577
- try {
58578
- json = JSON.parse(body);
58579
- } catch {
58580
- return { problem: "not JSON" };
57831
+
57832
+ // src/envoy-channel-server.ts
57833
+ var import_nats5 = __toESM(require_mod4(), 1);
57834
+
57835
+ // package.json
57836
+ var name2 = "@sjawhar/claude-envoy";
57837
+ var version2 = "4.16.0";
57838
+ var legion = {
57839
+ daemonApiVersion: 193
57840
+ };
57841
+ var package_default = {
57842
+ name: name2,
57843
+ version: version2,
57844
+ license: "Apache-2.0",
57845
+ description: "Claude Code plugin for Legion's Envoy bus",
57846
+ type: "module",
57847
+ files: [
57848
+ ".claude-plugin/**",
57849
+ ".mcp.json",
57850
+ ".omp-plugin/**",
57851
+ "bin/**",
57852
+ "dist/**",
57853
+ "hooks/**",
57854
+ "legion/**",
57855
+ "scripts/**",
57856
+ "skills/**",
57857
+ "src/**",
57858
+ "README.md",
57859
+ "AGENTS.md"
57860
+ ],
57861
+ legion,
57862
+ repository: {
57863
+ type: "git",
57864
+ url: "https://github.com/cybermonklabs/legion"
57865
+ },
57866
+ scripts: {
57867
+ channel: "bun bin/envoy-channel.ts",
57868
+ "verify-build": "bash scripts/verify-build.sh",
57869
+ prepack: "bash scripts/pack-skills.sh",
57870
+ postpack: "bash scripts/pack-skills.sh --restore",
57871
+ typecheck: "bunx tsc --noEmit",
57872
+ test: "bun test --timeout=60000",
57873
+ lint: "bunx biome check src/ hooks/ scripts/"
57874
+ },
57875
+ devDependencies: {
57876
+ "@biomejs/biome": "^2.3.14",
57877
+ "@legion/broker-client": "workspace:*",
57878
+ "@legion/contracts": "workspace:*",
57879
+ "@legion/envoy-client": "workspace:*",
57880
+ "@legion/pi-shared": "workspace:*",
57881
+ "@legion/test-fixtures": "workspace:*",
57882
+ "@modelcontextprotocol/sdk": "^1.30.0",
57883
+ "bun-types": "latest",
57884
+ nats: "^2.29.2",
57885
+ typescript: "^5.3.0",
57886
+ zod: "4.3.6"
58581
57887
  }
58582
- const parsed = schema.safeParse(json);
58583
- if (parsed.success)
58584
- return { value: parsed.data };
57888
+ };
57889
+
57890
+ // ../pi-shared/src/agent-stream.ts
57891
+ var encoder3 = new TextEncoder;
57892
+ var REPLAY_ARRAY_BYTES = 2;
57893
+ function jsonBytes(value) {
57894
+ return encoder3.encode(JSON.stringify(value)).length;
57895
+ }
57896
+ var SEQ_PER_MS = 1000;
57897
+ function modelReference(provider, id) {
57898
+ if (typeof id !== "string" || id === "")
57899
+ return;
57900
+ if (typeof provider !== "string" || provider === "")
57901
+ return;
57902
+ return `${provider}/${id}`;
57903
+ }
57904
+ function readModel(message) {
57905
+ const model = modelReference(message.provider, message.model);
57906
+ return model === undefined ? undefined : capAgentStreamText(model, AGENT_STREAM_LIMITS.modelChars);
57907
+ }
57908
+ function readMessage(raw) {
57909
+ if (typeof raw !== "object" || raw === null)
57910
+ return null;
57911
+ const message = raw;
57912
+ if (typeof message.role !== "string" || typeof message.timestamp !== "number")
57913
+ return null;
58585
57914
  return {
58586
- problem: parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ")
57915
+ host: message,
57916
+ isError: message.isError === true,
57917
+ model: readModel(message),
57918
+ role: message.role,
57919
+ timestamp: message.timestamp,
57920
+ toolCallId: typeof message.toolCallId === "string" ? message.toolCallId : undefined,
57921
+ toolName: typeof message.toolName === "string" ? message.toolName : undefined,
57922
+ tag: typeof message.tag === "string" ? message.tag : undefined
58587
57923
  };
58588
57924
  }
58589
- function createLegionDaemonClient(baseUrl, fetchFn = fetch) {
58590
- const endpoint = withoutTrailingSlashes(baseUrl);
58591
- const call = async (method, path, body, signal) => {
58592
- const response = await fetchFn(`${endpoint}${path}`, {
58593
- ...body === undefined ? {} : {
58594
- method,
58595
- headers: { "Content-Type": "application/json" },
58596
- body: JSON.stringify(body)
58597
- },
58598
- ...signal === undefined ? {} : { signal }
58599
- });
58600
- const text = await response.text();
58601
- if (response.ok)
58602
- return { status: response.status, text };
58603
- const refusal = parseBody(LegionErrorResponse, text);
58604
- if ("value" in refusal) {
58605
- throw new LegionDaemonApiError(method, path, response.status, refusal.value.code, refusal.value.error);
58606
- }
58607
- throw new LegionDaemonApiError(method, path, response.status, undefined, bodyForText(text, "", "the daemon's refusal shape"));
58608
- };
58609
- const read = async (method, path, schema, body, signal) => {
58610
- const { status, text } = await call(method, path, body, signal);
58611
- const parsed = parseBody(schema, text);
58612
- if ("problem" in parsed) {
58613
- throw new LegionDaemonContractError(method, path, status, parsed.problem);
58614
- }
58615
- return parsed.value;
58616
- };
58617
- const post = (path, request, response, body) => read("POST", path, response, request.parse(body));
58618
- const acknowledge = async (path, body, signal) => {
58619
- const { status, text } = await call("POST", path, body, signal);
58620
- if (status !== 204 || text !== "") {
58621
- throw new LegionDaemonContractError("POST", path, status, "the route answers 204 with no body");
58622
- }
58623
- };
58624
- return {
58625
- state: (options) => read("GET", "/legion/v1/state", LegionStateResponse, undefined, options?.signal),
58626
- register: (input) => read("POST", "/legion/v1/claims/register", LegionRegisterResponse, input),
58627
- registerController: (input) => read("POST", "/legion/v1/claims/register", LegionControllerRegisterResponse, input),
58628
- ready: (input, options) => acknowledge("/legion/v1/claims/ready", input, options?.signal),
58629
- readyForUpdate: (input) => acknowledge("/legion/v1/claims/ready-for-update", input),
58630
- exit: (input) => acknowledge("/legion/v1/claims/exit", input),
58631
- turnOutcome: (input) => post("/legion/v1/claims/turn-outcome", LegionTurnOutcomeRequest, LegionTurnOutcomeResponse, input),
58632
- activity: (input) => acknowledge("/legion/v1/claims/activity", input),
58633
- releaseRecords: (input) => post("/legion/v1/claims/release-records", LegionReleaseRecordsRequest, LegionReleaseRecordsResponse, input),
58634
- grant: (input) => post("/legion/v1/grants", LegionGrantRequest, LegionGrantResponse, input),
58635
- controllerGrant: (input) => post("/legion/v1/grants", LegionControllerGrantRequest, LegionGrantResponse, input),
58636
- handoffComplete: (input) => post("/legion/v1/handoff/complete", LegionHandoffCompleteRequest, LegionHandoffCompleteResponse, input),
58637
- issueStatus: (input) => post("/legion/v1/issues/status", LegionIssueStatusRequest, LegionEmptyResponse, input),
58638
- freshSession: (input) => post("/legion/v1/claims/fresh-session", LegionClaimRequest, LegionFreshSessionResponse, input),
58639
- compact: (input) => post("/legion/v1/claims/compact", LegionClaimRequest, LegionCompactResponse, input),
58640
- projectPause: (input) => post("/legion/v1/project/pause", LegionProjectPauseRequest, LegionProjectPauseResponse, input),
58641
- projectResume: (input) => post("/legion/v1/project/resume", LegionProjectResumeRequest, LegionProjectResumeResponse, input),
58642
- gateRegister: (input) => post("/legion/v1/gates/register", LegionGateRegisterRequest, LegionEmptyResponse, input),
58643
- waveRelease: (input) => post("/legion/v1/waves/release", LegionWaveReleaseRequest, LegionWaveReleaseResponse, input),
58644
- phaseBackward: (input) => post("/legion/v1/phase/backward", LegionPhaseBackwardRequest, LegionEmptyResponse, input),
58645
- phaseRetry: (input) => post("/legion/v1/phase/retry", LegionPhaseRetryRequest, LegionEmptyResponse, input),
58646
- signOff: (input) => post("/legion/v1/signoff", LegionSignOffRequest, LegionEmptyResponse, input),
58647
- rootClose: (input) => post("/legion/v1/roots/close", LegionRootCloseRequest, LegionEmptyResponse, input),
58648
- childPark: (input) => post("/legion/v1/children/park", LegionChildRequest, LegionEmptyResponse, input),
58649
- childRerun: (input) => post("/legion/v1/children/rerun", LegionChildRequest, LegionEmptyResponse, input)
58650
- };
58651
- }
58652
-
58653
- // ../pi-shared/src/handoff-record.ts
58654
- import { execFile as execFile2 } from "child_process";
58655
- import { promisify as promisify2 } from "util";
58656
-
58657
- // ../pi-shared/src/git-lock.ts
58658
- import { lstat } from "fs/promises";
58659
- var GIT_LOCK_REPORTS = [
58660
- /The lockfile at '([^']+)' might need manual deletion/g,
58661
- /Unable to create '([^']+)': File exists/g
58662
- ];
58663
- function age(ms) {
58664
- const total = Math.round(Math.abs(ms) / 1000);
58665
- const sign = ms < 0 && total > 0 ? "-" : "";
58666
- const hours = Math.floor(total / 3600);
58667
- const minutes = Math.floor(total % 3600 / 60);
58668
- const seconds = total % 60;
58669
- if (hours > 0)
58670
- return `${sign}${hours}h${minutes}m${seconds}s`;
58671
- if (minutes > 0)
58672
- return `${sign}${minutes}m${seconds}s`;
58673
- return `${sign}${seconds}s`;
58674
- }
58675
- async function staleGitLockNote(output, now = Date.now()) {
58676
- const locks = new Set;
58677
- for (const report of GIT_LOCK_REPORTS) {
58678
- for (const match of output.matchAll(report))
58679
- locks.add(match[1]);
57925
+ function keyFor(message) {
57926
+ if (message.role === "toolResult") {
57927
+ return message.toolCallId === undefined ? null : `t:${message.toolCallId}`;
58680
57928
  }
58681
- const notes = [];
58682
- for (const lock of locks) {
58683
- const written = await lstat(lock).then((info) => info.mtimeMs, () => {
58684
- return;
58685
- });
58686
- if (written === undefined)
57929
+ if (message.role === "assistant")
57930
+ return `m:a${message.timestamp}`;
57931
+ if (message.role !== "user")
57932
+ return null;
57933
+ return message.tag === undefined ? `m:u${message.timestamp}` : `m:u${message.timestamp}:${message.tag}`;
57934
+ }
57935
+ function contentText(content) {
57936
+ if (typeof content === "string")
57937
+ return content;
57938
+ if (!Array.isArray(content))
57939
+ return "";
57940
+ const pieces = [];
57941
+ for (const raw of content) {
57942
+ if (typeof raw !== "object" || raw === null)
58687
57943
  continue;
58688
- notes.push(`git lock ${lock} was last written ${age(now - written)} ago and blocks this command. The launcher of the issue's pod removes a git lock that no process of the pod holds open and that is more than 15 minutes old, and it looks again every minute. Under the tmux runtime nothing removes it: remove it by hand only once no git or jj process on the host is using the repository. Run the command again in about 16 minutes. If the lock is still there after that time, tell the issue's architect.`);
57944
+ const part = raw;
57945
+ if (typeof part.text === "string")
57946
+ pieces.push(part.text);
57947
+ else if (typeof part.type === "string")
57948
+ pieces.push(blockPlaceholder(part.type));
58689
57949
  }
58690
- return notes.join(`
57950
+ return pieces.join(`
58691
57951
  `);
58692
57952
  }
58693
-
58694
- // ../pi-shared/src/handoff-record.ts
58695
- var FILE_BACKED = {
58696
- planning: { word: "plan", role: "planner" },
58697
- implementing: { word: "implement", role: "implementer" },
58698
- testing: { word: "test", role: "tester" },
58699
- reviewing: { word: "review", role: "reviewer" }
58700
- };
58701
- var execFileAsync2 = promisify2(execFile2);
58702
- var pathJj = async (args, cwd) => {
58703
- try {
58704
- const { stdout } = await execFileAsync2("jj", ["-R", cwd, ...args], {
58705
- cwd,
58706
- maxBuffer: 16 * 1024 * 1024
58707
- });
58708
- return stdout.trim();
58709
- } catch (error) {
58710
- const detail = error !== null && typeof error === "object" && "stderr" in error ? String(error.stderr).trim() : error instanceof Error ? error.message : String(error);
58711
- const note = await staleGitLockNote(detail);
58712
- throw new Error(`jj ${args.join(" ")} failed: ${detail}${note === "" ? "" : `
58713
- ${note}`}`);
58714
- }
58715
- };
58716
- function paneLatestHandoff(file, env, cwd, session, fetchImpl = fetch) {
58717
- return async (issue, word) => {
58718
- const { dispatch } = sessionDispatchSettings(file, env, { cwd, session });
58719
- if (!dispatch.enabled) {
58720
- throw new Error(`Dispatch is off for this pane: ${dispatch.error ?? dispatch.notice}`);
58721
- }
58722
- return new DispatchClient(dispatch.url, dispatch.credential, fetchImpl).latestHandoff(issue, word);
58723
- };
58724
- }
58725
- function paneHandoffReport(file, env, cwd, session) {
58726
- return (phase, role) => findHandoffReport({
58727
- phase,
58728
- role,
58729
- env,
58730
- latestHandoff: paneLatestHandoff(file, env, cwd, session)
58731
- });
58732
- }
58733
- function requiredVariable(env, name, purpose) {
58734
- const value = env[name];
58735
- if (value === undefined || value === "") {
58736
- throw new Error(`${name} is not set, so ${purpose}`);
58737
- }
58738
- return value;
58739
- }
58740
- var FOR_HANDOFF = "handoff_complete cannot find what to report";
58741
- function issueBranch(env, purpose) {
58742
- const issue = requiredVariable(env, "LEGION_ISSUE", purpose);
58743
- if (!DISPATCH_KEY_PATTERN.test(issue)) {
58744
- throw new Error(`LEGION_ISSUE ${JSON.stringify(issue)} is not a Dispatch issue key like LEGION-1`);
58745
- }
58746
- return { issue, bookmark: `legion/${issue}` };
58747
- }
58748
- function pushedBranch(bookmark) {
58749
- return `remote_bookmarks(exact:${JSON.stringify(bookmark)}, exact:"origin")`;
57953
+ function boundedStrings(_key, value) {
57954
+ return typeof value === "string" ? capAgentStreamText(value, AGENT_STREAM_LIMITS.toolChars) : value;
58750
57955
  }
58751
- var STANDING = ["log", "-r", "@-", "--no-graph", "-T", "commit_id"];
58752
- var RECORD_HEAD = /^[0-9a-f]{40}$/;
58753
- function recordHead(body) {
58754
- let parsed;
57956
+ function renderArguments(value) {
57957
+ if (value === undefined || value === null)
57958
+ return "";
58755
57959
  try {
58756
- parsed = JSON.parse(body);
57960
+ return JSON.stringify(value, boundedStrings, 2) ?? "";
58757
57961
  } catch {
58758
- return;
57962
+ return "[unserialisable arguments]";
58759
57963
  }
58760
- if (parsed === null || typeof parsed !== "object" || !("head" in parsed))
58761
- return;
58762
- const head = parsed.head;
58763
- return typeof head === "string" && RECORD_HEAD.test(head) ? head : undefined;
58764
- }
58765
- async function findPushedBranchHead(input) {
58766
- const { env } = input;
58767
- const jj = input.jj ?? pathJj;
58768
- const purpose = "ready_for_update cannot find the branch head to report";
58769
- const workspace = requiredVariable(env, "LEGION_WORKSPACE", purpose);
58770
- const { bookmark } = issueBranch(env, purpose);
58771
- return jj(["log", "-r", pushedBranch(bookmark), "--no-graph", "-T", "commit_id"], workspace);
58772
57964
  }
58773
- function completedPhase(role, at) {
58774
- switch (role) {
58775
- case "planner":
58776
- return "planning";
58777
- case "tester":
58778
- return "testing";
58779
- case "reviewer":
58780
- return "reviewing";
58781
- case "merger":
58782
- return "merging";
58783
- case "implementer":
58784
- if (at === "implementing" || at === "retro")
58785
- return at;
58786
- return at === "merging" ? "retro" : "implementing";
58787
- case "architect":
58788
- return at;
57965
+ function conversationParts(content) {
57966
+ const { partChars, toolChars } = AGENT_STREAM_LIMITS;
57967
+ if (typeof content === "string") {
57968
+ return content === "" ? [] : [{ text: capAgentStreamText(content, partChars), type: "text" }];
58789
57969
  }
58790
- }
58791
- async function standingReport(env, jj) {
58792
- return { commit: await jj(STANDING, requiredVariable(env, "LEGION_WORKSPACE", FOR_HANDOFF)) };
58793
- }
58794
- async function findHandoffReport(input) {
58795
- const { role, env } = input;
58796
- const jj = input.jj ?? pathJj;
58797
- const of = completedPhase(role, input.phase);
58798
- const handoff = FILE_BACKED[of];
58799
- if (handoff === undefined || handoff.role !== role)
58800
- return standingReport(env, jj);
58801
- const works = of === input.phase;
58802
- const { issue, bookmark } = issueBranch(env, FOR_HANDOFF);
58803
- let record;
58804
- try {
58805
- record = await input.latestHandoff(issue, handoff.word);
58806
- } catch (error) {
58807
- if (error instanceof DispatchServiceError && error.fromDispatch && error.code === "HANDOFF_NOT_FOUND") {
58808
- if (!works)
58809
- return standingReport(env, jj);
58810
- throw new Error(`${issue} has no ${handoff.word} handoff in Dispatch: write it with \`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`, then complete again`);
58811
- }
58812
- const answer = error instanceof DispatchServiceError && error.fromDispatch ? `${error.status} ${error.code}: ${error.message}` : messageFor(error);
58813
- throw new Error(`handoff_complete could not read ${issue}'s newest ${handoff.word} handoff from Dispatch: ${answer}; complete again once Dispatch answers`);
58814
- }
58815
- const report = { handoffId: record.id, handoffVersion: record.version };
58816
- const head = recordHead(record.body);
58817
- if (role !== "implementer" || !works) {
58818
- if (head !== undefined)
58819
- return { commit: head, ...report };
58820
- if (role !== "implementer")
58821
- return report;
58822
- return standingReport(env, jj);
58823
- }
58824
- if (head === undefined) {
58825
- throw new Error(`the newest ${handoff.word} handoff of ${issue} (version ${record.version}) names no head: write the handoff again with \`head\` set to the 40-character lower-case commit you pushed as \`@-\`, as \`jj -R "$LEGION_WORKSPACE" log -r @- --no-graph -T commit_id\` prints it once the push succeeded (\`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`), then complete again`);
58826
- }
58827
- const workspace = requiredVariable(env, "LEGION_WORKSPACE", FOR_HANDOFF);
58828
- const stands = await jj(STANDING, workspace);
58829
- const tip = await jj(["log", "-r", `${pushedBranch(bookmark)} & ${stands}::`, "--no-graph", "-T", "commit_id"], workspace);
58830
- if (tip === "") {
58831
- throw new Error(`the commit this workspace stands on, ${stands}, is not on ${bookmark}@origin: push it with \`jj bookmark set ${bookmark} -r @- && jj git push --bookmark ${bookmark}\`; the handoff's \`head\` must name that pushed commit, and the newest ${handoff.word} handoff of ${issue} (version ${record.version}) names ${head}, so when that is another commit, write the handoff again with \`head\` set to ${stands} (\`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`); then complete again`);
58832
- }
58833
- if (head !== stands) {
58834
- throw new Error(`the newest ${handoff.word} handoff of ${issue} (version ${record.version}) names ${head} as its head, not the commit this workspace stands on, ${stands}, which ${bookmark}@origin carries: write the handoff again with \`head\` set to ${stands} (\`dispatch handoff-write --issue ${issue} --phase ${handoff.word} --body-file <file>\`), then complete again`);
58835
- }
58836
- return { commit: head, ...report };
58837
- }
58838
-
58839
- // src/envoy-channel-server.ts
58840
- var import_nats5 = __toESM(require_mod4(), 1);
58841
-
58842
- // package.json
58843
- var name2 = "@sjawhar/claude-envoy";
58844
- var version2 = "4.15.4";
58845
- var legion = {
58846
- daemonApiVersion: 189
58847
- };
58848
-
58849
- // ../pi-shared/src/agent-stream.ts
58850
- var encoder3 = new TextEncoder;
58851
- var REPLAY_ARRAY_BYTES = 2;
58852
- function jsonBytes(value) {
58853
- return encoder3.encode(JSON.stringify(value)).length;
58854
- }
58855
- var SEQ_PER_MS = 1000;
58856
- function modelReference(provider, id) {
58857
- if (typeof id !== "string" || id === "")
58858
- return;
58859
- if (typeof provider !== "string" || provider === "")
58860
- return;
58861
- return `${provider}/${id}`;
58862
- }
58863
- function readModel(message) {
58864
- const model = modelReference(message.provider, message.model);
58865
- return model === undefined ? undefined : capAgentStreamText(model, AGENT_STREAM_LIMITS.modelChars);
58866
- }
58867
- function readMessage(raw) {
58868
- if (typeof raw !== "object" || raw === null)
58869
- return null;
58870
- const message = raw;
58871
- if (typeof message.role !== "string" || typeof message.timestamp !== "number")
58872
- return null;
58873
- return {
58874
- host: message,
58875
- isError: message.isError === true,
58876
- model: readModel(message),
58877
- role: message.role,
58878
- timestamp: message.timestamp,
58879
- toolCallId: typeof message.toolCallId === "string" ? message.toolCallId : undefined,
58880
- toolName: typeof message.toolName === "string" ? message.toolName : undefined,
58881
- tag: typeof message.tag === "string" ? message.tag : undefined
58882
- };
58883
- }
58884
- function keyFor(message) {
58885
- if (message.role === "toolResult") {
58886
- return message.toolCallId === undefined ? null : `t:${message.toolCallId}`;
58887
- }
58888
- if (message.role === "assistant")
58889
- return `m:a${message.timestamp}`;
58890
- if (message.role !== "user")
58891
- return null;
58892
- return message.tag === undefined ? `m:u${message.timestamp}` : `m:u${message.timestamp}:${message.tag}`;
58893
- }
58894
- function contentText(content) {
58895
- if (typeof content === "string")
58896
- return content;
58897
- if (!Array.isArray(content))
58898
- return "";
58899
- const pieces = [];
58900
- for (const raw of content) {
58901
- if (typeof raw !== "object" || raw === null)
58902
- continue;
58903
- const part = raw;
58904
- if (typeof part.text === "string")
58905
- pieces.push(part.text);
58906
- else if (typeof part.type === "string")
58907
- pieces.push(blockPlaceholder(part.type));
58908
- }
58909
- return pieces.join(`
58910
- `);
58911
- }
58912
- function boundedStrings(_key, value) {
58913
- return typeof value === "string" ? capAgentStreamText(value, AGENT_STREAM_LIMITS.toolChars) : value;
58914
- }
58915
- function renderArguments(value) {
58916
- if (value === undefined || value === null)
58917
- return "";
58918
- try {
58919
- return JSON.stringify(value, boundedStrings, 2) ?? "";
58920
- } catch {
58921
- return "[unserialisable arguments]";
58922
- }
58923
- }
58924
- function conversationParts(content) {
58925
- const { partChars, toolChars } = AGENT_STREAM_LIMITS;
58926
- if (typeof content === "string") {
58927
- return content === "" ? [] : [{ text: capAgentStreamText(content, partChars), type: "text" }];
58928
- }
58929
- if (!Array.isArray(content))
58930
- return [];
58931
- const parts = [];
58932
- for (const raw of content) {
58933
- if (typeof raw !== "object" || raw === null)
58934
- continue;
58935
- const part = raw;
58936
- if (part.type === "text" && typeof part.text === "string") {
58937
- parts.push({ text: capAgentStreamText(part.text, partChars), type: "text" });
58938
- } else if (part.type === "thinking" && typeof part.thinking === "string") {
58939
- parts.push({ text: capAgentStreamText(part.thinking, partChars), type: "reasoning" });
58940
- } else if (part.type === "toolCall" && typeof part.id === "string") {
58941
- parts.push({
58942
- argsText: capAgentStreamText(renderArguments(part.arguments), toolChars),
58943
- toolCallId: part.id,
58944
- toolName: typeof part.name === "string" ? part.name : "tool",
58945
- type: "tool-call"
58946
- });
58947
- } else if (typeof part.type === "string") {
58948
- parts.push({ text: blockPlaceholder(part.type), type: "text" });
57970
+ if (!Array.isArray(content))
57971
+ return [];
57972
+ const parts = [];
57973
+ for (const raw of content) {
57974
+ if (typeof raw !== "object" || raw === null)
57975
+ continue;
57976
+ const part = raw;
57977
+ if (part.type === "text" && typeof part.text === "string") {
57978
+ parts.push({ text: capAgentStreamText(part.text, partChars), type: "text" });
57979
+ } else if (part.type === "thinking" && typeof part.thinking === "string") {
57980
+ parts.push({ text: capAgentStreamText(part.thinking, partChars), type: "reasoning" });
57981
+ } else if (part.type === "toolCall" && typeof part.id === "string") {
57982
+ parts.push({
57983
+ argsText: capAgentStreamText(renderArguments(part.arguments), toolChars),
57984
+ toolCallId: part.id,
57985
+ toolName: typeof part.name === "string" ? part.name : "tool",
57986
+ type: "tool-call"
57987
+ });
57988
+ } else if (typeof part.type === "string") {
57989
+ parts.push({ text: blockPlaceholder(part.type), type: "text" });
58949
57990
  }
58950
57991
  }
58951
57992
  return parts;
@@ -59790,349 +58831,1538 @@ var DeliveryIdentity = DedupeIdentitySchema.extend({
59790
58831
  source_event_id: DedupeIdentitySchema.shape.source_event_id.catch(undefined),
59791
58832
  topic: string2().min(1).optional().catch(undefined)
59792
58833
  });
59793
- var DEFAULT_DRAIN_TIMEOUT_MS = 1000;
59794
- function deliveryIdentity(raw) {
59795
- let parsed;
59796
- try {
59797
- parsed = JSON.parse(raw);
59798
- } catch {
59799
- return;
59800
- }
59801
- const identity = DeliveryIdentity.safeParse(parsed);
59802
- return identity.success ? identity.data : undefined;
59803
- }
59804
- function report(what, error) {
59805
- process.stderr.write(`envoy-channel: ${what} \u2014 ${natsFailureReason(error)}
59806
- `);
59807
- }
59808
- function createChannelTopics(connection, options = {}) {
59809
- const following = new Set;
59810
- const drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;
59811
- return {
59812
- follow(topic) {
59813
- for (const subject of expandSubscriptionTopics([topic]))
59814
- following.add(subject);
59815
- },
59816
- unfollow(topics) {
59817
- if (topics.length === 0) {
59818
- following.clear();
59819
- return;
59820
- }
59821
- for (const subject of expandSubscriptionTopics(topics))
59822
- following.delete(subject);
59823
- },
59824
- topics() {
59825
- return [...following];
59826
- },
59827
- isClosed() {
59828
- return connection().isClosed();
59829
- },
59830
- async close() {
59831
- following.clear();
59832
- const held = connection();
59833
- if (held.isClosed())
59834
- return;
59835
- const timeout = Promise.withResolvers();
59836
- const timer = setTimeout(timeout.resolve, drainTimeoutMs);
59837
- try {
59838
- await Promise.race([held.drain(), timeout.promise]);
59839
- } catch (error) {
59840
- report("draining the broker connection failed", error);
59841
- }
59842
- clearTimeout(timer);
59843
- if (held.isClosed())
59844
- return;
59845
- try {
59846
- await held.close();
59847
- } catch (error) {
59848
- report("closing the broker connection failed", error);
59849
- }
59850
- }
59851
- };
59852
- }
59853
-
59854
- // src/session-identity.ts
59855
- import { readFile as readFile3 } from "fs/promises";
59856
- import { basename as basename2, join as join8 } from "path";
59857
-
59858
- // src/session-state.ts
59859
- import { readFileSync as readFileSync6 } from "fs";
59860
- import { mkdir, readdir as readdir2, rename, rm, stat, utimes, writeFile } from "fs/promises";
59861
- import { dirname as dirname2, join as join7 } from "path";
59862
- async function writeAtomicStateFile(file, contents) {
59863
- await mkdir(dirname2(file), { recursive: true, mode: 448 });
59864
- const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
59865
- await writeFile(temporary, contents, { mode: 384 });
59866
- await rename(temporary, file);
59867
- }
59868
- async function touchStateFile(file) {
59869
- const now = new Date;
59870
- await utimes(file, now, now);
59871
- }
59872
- async function pruneStateDirectory(directory, isStale) {
59873
- const entries = await readdir2(directory).catch((error) => {
59874
- if (hasErrnoCode(error, "ENOENT"))
59875
- return [];
59876
- throw error;
59877
- });
59878
- for (const entry of entries) {
59879
- const file = join7(directory, entry);
59880
- if (!await isStale(file))
59881
- continue;
59882
- await rm(file, { recursive: true, force: true });
59883
- }
59884
- }
59885
- var STATE_FILE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
59886
- async function writtenLongAgo(file) {
59887
- const modified = await stat(file).then((stats) => stats.mtimeMs, () => {
59888
- return;
59889
- });
59890
- return modified !== undefined && Date.now() - modified > STATE_FILE_MAX_AGE_MS;
59891
- }
59892
- var TITLES_DIRECTORY = "titles";
59893
- function sessionTitleFile(stateDirectory, sessionId) {
59894
- return join7(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
59895
- }
59896
- async function writeChosenTitle(file, title) {
59897
- await writeAtomicStateFile(file, `${title}
59898
- `);
59899
- }
59900
- async function removeChosenTitle(file) {
59901
- await rm(file, { force: true });
59902
- }
59903
- function readChosenTitleSync(file) {
59904
- try {
59905
- return readFileSync6(file, "utf8");
59906
- } catch {
59907
- return;
59908
- }
59909
- }
59910
- async function recordChosenTitle(sessionId, title) {
59911
- const pluginData = configuredValue(process.env["CLAUDE_PLUGIN_DATA"]);
59912
- if (pluginData === undefined)
59913
- return;
59914
- const file = sessionTitleFile(pluginData, sessionId);
59915
- const chosen = configuredValue(title);
59916
- if (chosen === undefined)
59917
- await removeChosenTitle(file);
59918
- else
59919
- await writeChosenTitle(file, chosen);
59920
- }
59921
- async function pruneStaleSessionTitles(stateDirectory) {
59922
- await pruneStateDirectory(join7(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
59923
- }
59924
-
59925
- // src/session-identity.ts
59926
- var PersistedRole = object({
59927
- session_id: string2().min(1),
59928
- role: string2().min(1),
59929
- client_instance_id: string2().min(1).optional()
58834
+ var DEFAULT_DRAIN_TIMEOUT_MS = 1000;
58835
+ function deliveryIdentity(raw) {
58836
+ let parsed;
58837
+ try {
58838
+ parsed = JSON.parse(raw);
58839
+ } catch {
58840
+ return;
58841
+ }
58842
+ const identity = DeliveryIdentity.safeParse(parsed);
58843
+ return identity.success ? identity.data : undefined;
58844
+ }
58845
+ function report(what, error) {
58846
+ process.stderr.write(`envoy-channel: ${what} \u2014 ${natsFailureReason(error)}
58847
+ `);
58848
+ }
58849
+ function createChannelTopics(connection, options = {}) {
58850
+ const following = new Set;
58851
+ const drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;
58852
+ return {
58853
+ follow(topic) {
58854
+ for (const subject of expandSubscriptionTopics([topic]))
58855
+ following.add(subject);
58856
+ },
58857
+ unfollow(topics) {
58858
+ if (topics.length === 0) {
58859
+ following.clear();
58860
+ return;
58861
+ }
58862
+ for (const subject of expandSubscriptionTopics(topics))
58863
+ following.delete(subject);
58864
+ },
58865
+ topics() {
58866
+ return [...following];
58867
+ },
58868
+ isClosed() {
58869
+ return connection().isClosed();
58870
+ },
58871
+ async close() {
58872
+ following.clear();
58873
+ const held = connection();
58874
+ if (held.isClosed())
58875
+ return;
58876
+ const timeout = Promise.withResolvers();
58877
+ const timer = setTimeout(timeout.resolve, drainTimeoutMs);
58878
+ try {
58879
+ await Promise.race([held.drain(), timeout.promise]);
58880
+ } catch (error) {
58881
+ report("draining the broker connection failed", error);
58882
+ }
58883
+ clearTimeout(timer);
58884
+ if (held.isClosed())
58885
+ return;
58886
+ try {
58887
+ await held.close();
58888
+ } catch (error) {
58889
+ report("closing the broker connection failed", error);
58890
+ }
58891
+ }
58892
+ };
58893
+ }
58894
+
58895
+ // src/session-identity.ts
58896
+ import { readFile as readFile3 } from "fs/promises";
58897
+ import { basename as basename2, join as join8 } from "path";
58898
+
58899
+ // src/session-state.ts
58900
+ import { readFileSync as readFileSync6 } from "fs";
58901
+ import { mkdir, readdir as readdir2, rename, rm, stat, utimes, writeFile } from "fs/promises";
58902
+ import { dirname as dirname2, join as join7 } from "path";
58903
+ async function writeAtomicStateFile(file, contents) {
58904
+ await mkdir(dirname2(file), { recursive: true, mode: 448 });
58905
+ const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
58906
+ await writeFile(temporary, contents, { mode: 384 });
58907
+ await rename(temporary, file);
58908
+ }
58909
+ async function touchStateFile(file) {
58910
+ const now = new Date;
58911
+ await utimes(file, now, now);
58912
+ }
58913
+ async function pruneStateDirectory(directory, isStale) {
58914
+ const entries = await readdir2(directory).catch((error) => {
58915
+ if (hasErrnoCode(error, "ENOENT"))
58916
+ return [];
58917
+ throw error;
58918
+ });
58919
+ for (const entry of entries) {
58920
+ const file = join7(directory, entry);
58921
+ if (!await isStale(file))
58922
+ continue;
58923
+ await rm(file, { recursive: true, force: true });
58924
+ }
58925
+ }
58926
+ var STATE_FILE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
58927
+ async function writtenLongAgo(file) {
58928
+ const modified = await stat(file).then((stats) => stats.mtimeMs, () => {
58929
+ return;
58930
+ });
58931
+ return modified !== undefined && Date.now() - modified > STATE_FILE_MAX_AGE_MS;
58932
+ }
58933
+ var TITLES_DIRECTORY = "titles";
58934
+ function sessionTitleFile(stateDirectory, sessionId) {
58935
+ return join7(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
58936
+ }
58937
+ async function writeChosenTitle(file, title) {
58938
+ await writeAtomicStateFile(file, `${title}
58939
+ `);
58940
+ }
58941
+ async function removeChosenTitle(file) {
58942
+ await rm(file, { force: true });
58943
+ }
58944
+ function readChosenTitleSync(file) {
58945
+ try {
58946
+ return readFileSync6(file, "utf8");
58947
+ } catch {
58948
+ return;
58949
+ }
58950
+ }
58951
+ async function recordChosenTitle(sessionId, title) {
58952
+ const pluginData = configuredValue(process.env["CLAUDE_PLUGIN_DATA"]);
58953
+ if (pluginData === undefined)
58954
+ return;
58955
+ const file = sessionTitleFile(pluginData, sessionId);
58956
+ const chosen = configuredValue(title);
58957
+ if (chosen === undefined)
58958
+ await removeChosenTitle(file);
58959
+ else
58960
+ await writeChosenTitle(file, chosen);
58961
+ }
58962
+ async function pruneStaleSessionTitles(stateDirectory) {
58963
+ await pruneStateDirectory(join7(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
58964
+ }
58965
+
58966
+ // src/session-identity.ts
58967
+ var PersistedRole = object({
58968
+ session_id: string2().min(1),
58969
+ role: string2().min(1),
58970
+ client_instance_id: string2().min(1).optional()
58971
+ });
58972
+
58973
+ class SessionIdentity {
58974
+ directory;
58975
+ #id;
58976
+ constructor(id, directory) {
58977
+ this.directory = directory;
58978
+ this.#id = id;
58979
+ }
58980
+ get id() {
58981
+ return this.#id;
58982
+ }
58983
+ set(next) {
58984
+ this.#id = next;
58985
+ }
58986
+ }
58987
+ function sessionHandoffDirectory(stateDirectory, claudePid) {
58988
+ return join8(stateDirectory, "sessions", String(claudePid));
58989
+ }
58990
+ function sessionHandoffFile(stateDirectory, claudePid) {
58991
+ return join8(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
58992
+ }
58993
+ var ROLES_DIRECTORY = "roles";
58994
+ function roleStateFile(stateDirectory, sessionId) {
58995
+ return join8(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
58996
+ }
58997
+
58998
+ class UnparseableRoleRecordError extends Error {
58999
+ name = "UnparseableRoleRecordError";
59000
+ constructor(roleFile, cause) {
59001
+ super(`the role record ${roleFile} cannot be parsed (${messageFor(cause)})`, { cause });
59002
+ }
59003
+ }
59004
+ async function readPersistedRole(roleFile) {
59005
+ let bytes;
59006
+ try {
59007
+ bytes = await readFile3(roleFile, "utf8");
59008
+ } catch (error) {
59009
+ if (hasErrnoCode(error, "ENOENT"))
59010
+ return;
59011
+ throw error;
59012
+ }
59013
+ try {
59014
+ return PersistedRole.parse(JSON.parse(bytes));
59015
+ } catch (error) {
59016
+ throw new UnparseableRoleRecordError(roleFile, error);
59017
+ }
59018
+ }
59019
+ async function writePersistedRole(roleFile, state) {
59020
+ await writeAtomicStateFile(roleFile, `${JSON.stringify(state)}
59021
+ `);
59022
+ }
59023
+ async function writeSessionHandoff(file, sessionId) {
59024
+ await writeAtomicStateFile(file, `${sessionId.trim()}
59025
+ `);
59026
+ }
59027
+ async function readSessionHandoff(file) {
59028
+ try {
59029
+ const id = (await readFile3(file, "utf8")).trim();
59030
+ return id.length === 0 ? undefined : id;
59031
+ } catch (error) {
59032
+ if (hasErrnoCode(error, "ENOENT"))
59033
+ return;
59034
+ throw error;
59035
+ }
59036
+ }
59037
+ function processExists(pid) {
59038
+ try {
59039
+ process.kill(pid, 0);
59040
+ return true;
59041
+ } catch (error) {
59042
+ return hasErrnoCode(error, "EPERM");
59043
+ }
59044
+ }
59045
+ async function pruneStaleSessionHandoffs(stateDirectory) {
59046
+ await pruneStateDirectory(join8(stateDirectory, "sessions"), (file) => {
59047
+ const pid = basename2(file);
59048
+ return /^\d+$/.test(pid) && !processExists(Number(pid));
59049
+ });
59050
+ }
59051
+ async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
59052
+ const own = roleStateFile(stateDirectory, currentSessionId);
59053
+ await pruneStateDirectory(join8(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
59054
+ }
59055
+
59056
+ // src/envoy-off.ts
59057
+ function inboundOffChannelSession(options) {
59058
+ const { identity, stateDirectory, why } = options;
59059
+ return {
59060
+ delivery: { enqueue: async () => false, inbox: () => [] },
59061
+ topics: () => [],
59062
+ async follow() {
59063
+ throw new Error(`inbound messages are off for this session: ${why}`);
59064
+ },
59065
+ unfollow: async () => [],
59066
+ onRoleRegained: () => {
59067
+ return;
59068
+ },
59069
+ capabilitiesChanged: () => {
59070
+ return;
59071
+ },
59072
+ observe: () => {
59073
+ return;
59074
+ },
59075
+ messageOf: () => {
59076
+ return;
59077
+ },
59078
+ async rememberRole(role) {
59079
+ await writePersistedRole(roleStateFile(stateDirectory, identity.id), {
59080
+ session_id: identity.id,
59081
+ role
59082
+ });
59083
+ },
59084
+ shutdown: async () => {
59085
+ return;
59086
+ }
59087
+ };
59088
+ }
59089
+ async function serveEnvoyOff(serverInfo, refusal) {
59090
+ const server = new Server(serverInfo, { capabilities: { tools: {} } });
59091
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [] }));
59092
+ server.setRequestHandler(CallToolRequestSchema, async () => {
59093
+ throw new Error(refusal);
59094
+ });
59095
+ const stopped = Promise.withResolvers();
59096
+ process.stdin.once("end", stopped.resolve);
59097
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
59098
+ process.once(signal, () => stopped.resolve());
59099
+ }
59100
+ await server.connect(new StdioServerTransport);
59101
+ try {
59102
+ await stopped.promise;
59103
+ } finally {
59104
+ await server.close().catch(() => {
59105
+ return;
59106
+ });
59107
+ }
59108
+ }
59109
+
59110
+ // src/installed-build.ts
59111
+ import { sep } from "path";
59112
+ function pluginCacheSegments(bundlePath) {
59113
+ const parts = bundlePath.split(sep);
59114
+ for (let index = 0;index + 1 < parts.length; index++) {
59115
+ if (parts[index] === "plugins" && parts[index + 1] === "cache")
59116
+ return parts.slice(index + 2);
59117
+ }
59118
+ return;
59119
+ }
59120
+ function installedPluginVersion(bundlePath) {
59121
+ return pluginCacheSegments(bundlePath)?.[2];
59122
+ }
59123
+
59124
+ // src/legion-claim.ts
59125
+ import { readdir as readdir3, stat as stat2 } from "fs/promises";
59126
+ import { join as join10 } from "path";
59127
+ import { setTimeout as delay2 } from "timers/promises";
59128
+
59129
+ // ../pi-shared/src/stall-limits.ts
59130
+ var DEFAULT_STALL_LIMITS = {
59131
+ reminderMs: 300000,
59132
+ waitingMs: 900000,
59133
+ resumeMs: 120000,
59134
+ architectAfter: 3,
59135
+ callGraceMs: 300000,
59136
+ callBoundMs: 3600000,
59137
+ stepMs: 120000
59138
+ };
59139
+ var LONG_CALL_BOUND_MS = 14400000;
59140
+ var LONG_CALL_BOUND_ROLES = [
59141
+ "implementer",
59142
+ "reviewer"
59143
+ ];
59144
+ function defaultCallBoundMs(role) {
59145
+ return role !== undefined && LONG_CALL_BOUND_ROLES.includes(role) ? LONG_CALL_BOUND_MS : DEFAULT_STALL_LIMITS.callBoundMs;
59146
+ }
59147
+ function integerSetting(env, log, name, fallback, least) {
59148
+ const raw = env[name];
59149
+ if (raw === undefined)
59150
+ return fallback;
59151
+ const value = raw.trim() === "" ? Number.NaN : Number(raw);
59152
+ if (!Number.isInteger(value) || value < least) {
59153
+ log.warn(`legion: ${name} is not an integer of ${least} or more; using ${fallback}`, {
59154
+ value: raw
59155
+ });
59156
+ return fallback;
59157
+ }
59158
+ return value;
59159
+ }
59160
+ function stallLimits(env, log, role) {
59161
+ return {
59162
+ reminderMs: integerSetting(env, log, "LEGION_STALL_REMINDER_MS", DEFAULT_STALL_LIMITS.reminderMs, 0),
59163
+ waitingMs: integerSetting(env, log, "LEGION_STALL_WAITING_MS", DEFAULT_STALL_LIMITS.waitingMs, 0),
59164
+ resumeMs: integerSetting(env, log, "LEGION_STALL_RESUME_MS", DEFAULT_STALL_LIMITS.resumeMs, 0),
59165
+ architectAfter: integerSetting(env, log, "LEGION_STALL_ARCHITECT_AFTER", DEFAULT_STALL_LIMITS.architectAfter, 2),
59166
+ callGraceMs: integerSetting(env, log, "LEGION_STALL_CALL_GRACE_MS", DEFAULT_STALL_LIMITS.callGraceMs, 0),
59167
+ callBoundMs: integerSetting(env, log, "LEGION_STALL_CALL_BOUND_MS", defaultCallBoundMs(role), 0),
59168
+ stepMs: integerSetting(env, log, "LEGION_STALL_STEP_MS", DEFAULT_STALL_LIMITS.stepMs, 0)
59169
+ };
59170
+ }
59171
+
59172
+ // ../pi-shared/src/claim-first-turn-bound.ts
59173
+ var DEFAULT_CLAIM_FIRST_TURN_BOUND_MS = 30000;
59174
+ var BOUND_VARIABLE = "LEGION_CLAIM_FIRST_TURN_BOUND_MS";
59175
+ function claimFirstTurnBoundMs(env, log) {
59176
+ return integerSetting(env, log, BOUND_VARIABLE, DEFAULT_CLAIM_FIRST_TURN_BOUND_MS, 0);
59177
+ }
59178
+
59179
+ // ../contracts/src/legion-claim-recovery.ts
59180
+ var nonEmptyString = string2().min(1);
59181
+ var LegionClaimRequest = strictObject({
59182
+ grantId: nonEmptyString,
59183
+ issue: nonEmptyString,
59184
+ role: _enum2(LEGION_ROLES)
59185
+ });
59186
+ var LegionFreshSessionResponse = object({
59187
+ phaseNotRestarted: nonEmptyString.optional()
59188
+ });
59189
+ var LegionCompactResponse = object({
59190
+ compacted: boolean2().optional(),
59191
+ reason: string2().optional()
59192
+ });
59193
+
59194
+ // ../contracts/src/legion-api.ts
59195
+ var nonEmptyString2 = string2().min(1);
59196
+ var issueKey = string2().regex(DISPATCH_KEY_PATTERN);
59197
+ var timestamp = exports_iso.datetime({ offset: true });
59198
+ var LegionInstant = timestamp.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/, { error: "an RFC 3339 time with seconds, as 2026-11-02T09:00:00Z is" });
59199
+ var LEGION_WORKFLOW_PHASES = [
59200
+ "admitted",
59201
+ "awaiting_person",
59202
+ "planning",
59203
+ "implementing",
59204
+ "testing",
59205
+ "reviewing",
59206
+ "accepting",
59207
+ "retro",
59208
+ "merging",
59209
+ "integrating",
59210
+ "done",
59211
+ "held"
59212
+ ];
59213
+ var LEGION_PHASE_BACKWARD_TARGETS = [
59214
+ "admitted",
59215
+ "planning",
59216
+ "implementing",
59217
+ "testing",
59218
+ "reviewing",
59219
+ "accepting",
59220
+ "retro",
59221
+ "merging",
59222
+ "done",
59223
+ "held"
59224
+ ];
59225
+ var LEGION_PHASES = [...LEGION_WORKFLOW_PHASES, "unrecorded"];
59226
+ var LEGION_CLAIM_STATES = [
59227
+ "queued",
59228
+ "launch_uncertain",
59229
+ "launching",
59230
+ "shim_connected",
59231
+ "registered",
59232
+ "ready",
59233
+ "working",
59234
+ "idle",
59235
+ "suspended",
59236
+ "failed",
59237
+ "retired"
59238
+ ];
59239
+ var legionLocator = discriminatedUnion("runtime", [
59240
+ object({
59241
+ runtime: literal("tmux"),
59242
+ claim: nonEmptyString2.optional(),
59243
+ incarnation: nonEmptyString2.optional(),
59244
+ tmux: object({ window: nonEmptyString2.optional(), pane: nonEmptyString2.optional() }).optional()
59245
+ }),
59246
+ object({
59247
+ runtime: literal("sandbox"),
59248
+ claim: nonEmptyString2.optional(),
59249
+ incarnation: nonEmptyString2.optional(),
59250
+ sandbox: object({
59251
+ namespace: nonEmptyString2.optional(),
59252
+ name: nonEmptyString2.optional(),
59253
+ podUid: nonEmptyString2.optional(),
59254
+ container: nonEmptyString2.optional(),
59255
+ generation: number2().int().positive().optional()
59256
+ }).optional()
59257
+ })
59258
+ ]);
59259
+ var legionCapabilityReportView = object({
59260
+ measuredAt: timestamp.optional(),
59261
+ incarnation: string2().optional(),
59262
+ ok: array(nonEmptyString2).optional(),
59263
+ open: array(object({ name: nonEmptyString2.optional(), detail: nonEmptyString2.optional() })).optional()
59264
+ });
59265
+ var legionStepView = object({
59266
+ at: timestamp.optional(),
59267
+ turnStartedAt: timestamp.optional(),
59268
+ tool: nonEmptyString2.optional(),
59269
+ callId: nonEmptyString2.optional(),
59270
+ argsBytes: number2().int().positive().optional(),
59271
+ argsHash: nonEmptyString2.optional(),
59272
+ startedAt: timestamp.optional(),
59273
+ endedAt: timestamp.optional()
59274
+ });
59275
+ var legionPacedWake = {
59276
+ kind: nonEmptyString2.optional(),
59277
+ dueAt: timestamp.optional()
59278
+ };
59279
+ var LEGION_FAILURE_CAUSES = [
59280
+ "launch_refused",
59281
+ "died",
59282
+ "never_registered",
59283
+ "stale_plugin",
59284
+ "prompt_retires_exhausted",
59285
+ "provider_error",
59286
+ "unrecorded"
59287
+ ];
59288
+ var legionFailureCause = _enum2(LEGION_FAILURE_CAUSES);
59289
+ var legionClaimFailureView = object({
59290
+ cause: legionFailureCause.optional(),
59291
+ detail: string2().optional(),
59292
+ at: timestamp.optional(),
59293
+ attempts: object({
59294
+ launchFailures: number2().int().nonnegative().optional(),
59295
+ deaths: number2().int().nonnegative().optional(),
59296
+ promptFailures: number2().int().nonnegative().optional(),
59297
+ promptRetires: number2().int().nonnegative().optional()
59298
+ }).optional()
59299
+ });
59300
+ var legionPendingTaskView = object({
59301
+ phase: _enum2(LEGION_WORKFLOW_PHASES).optional(),
59302
+ queuedAt: timestamp.optional(),
59303
+ sendFailures: number2().int().positive().optional(),
59304
+ lastSendError: nonEmptyString2.optional()
59305
+ });
59306
+ var legionClaimView = object({
59307
+ session: string2().optional(),
59308
+ state: _enum2(LEGION_CLAIM_STATES),
59309
+ locator: legionLocator.optional(),
59310
+ capabilities: legionCapabilityReportView.optional(),
59311
+ servingGeneration: number2().int().positive().optional(),
59312
+ pluginContract: number2().int().nonnegative().optional(),
59313
+ updateRound: nonEmptyString2.optional(),
59314
+ updateHead: nonEmptyString2.optional(),
59315
+ updateReasons: nonEmptyString2.optional(),
59316
+ updateState: _enum2(["none", "open", "asked", "answered"]).optional(),
59317
+ providerErrorRun: number2().int().positive().optional(),
59318
+ pendingTask: legionPendingTaskView.optional(),
59319
+ lastTurnStart: timestamp.optional(),
59320
+ lastTurnEnd: timestamp.optional(),
59321
+ lastDeathCause: nonEmptyString2.optional(),
59322
+ lastStartFailure: nonEmptyString2.optional(),
59323
+ lastReady: timestamp.optional(),
59324
+ step: legionStepView.optional(),
59325
+ wake: object(legionPacedWake).optional(),
59326
+ failure: legionClaimFailureView.optional(),
59327
+ pendingCause: legionFailureCause.optional(),
59328
+ leakCheckCause: nonEmptyString2.optional()
59329
+ });
59330
+ var legionHandoffRecordView = object({
59331
+ id: nonEmptyString2.optional(),
59332
+ version: number2().int().positive().optional()
59333
+ });
59334
+ var legionPhaseView = object({
59335
+ claim: legionClaimView.optional(),
59336
+ handoffCommit: nonEmptyString2.optional(),
59337
+ handoffRecord: legionHandoffRecordView.optional(),
59338
+ pass: number2().int().nonnegative().optional(),
59339
+ rounds: number2().int().nonnegative().optional(),
59340
+ backwardMoves: record(string2(), number2().int().positive()).optional()
59341
+ });
59342
+ var legionMergeState = _enum2([
59343
+ "clean",
59344
+ "unstable",
59345
+ "has_hooks",
59346
+ "blocked",
59347
+ "dirty",
59348
+ "behind",
59349
+ "draft",
59350
+ "unknown"
59351
+ ]);
59352
+ var legionPullRequestView = object({
59353
+ repo: nonEmptyString2.optional(),
59354
+ number: number2().int().positive().optional(),
59355
+ head: nonEmptyString2.optional(),
59356
+ state: _enum2(["open", "merged", "closed"]).optional(),
59357
+ mergeState: legionMergeState.optional(),
59358
+ reviewDecision: nonEmptyString2.optional()
59359
+ });
59360
+ var legionMergeWaitView = object({
59361
+ waitsOn: nonEmptyString2.optional(),
59362
+ mergeState: legionMergeState.optional(),
59363
+ stateReadAt: timestamp.optional(),
59364
+ headUpdatedAt: timestamp.optional(),
59365
+ checkRuns: number2().int().nonnegative().optional(),
59366
+ toldHead: nonEmptyString2.optional(),
59367
+ toldState: legionMergeState.optional()
59368
+ });
59369
+ var legionGateView = object({
59370
+ artifactId: nonEmptyString2.optional(),
59371
+ currentVersion: number2().int().positive().optional(),
59372
+ approvedVersion: number2().int().positive().nullable().optional()
59373
+ });
59374
+ var legionDesignStep = _enum2(GATED_STEPS);
59375
+ var legionGatedStepView = object({
59376
+ step: legionDesignStep.optional(),
59377
+ artifactId: nonEmptyString2.optional(),
59378
+ currentVersion: number2().int().positive().optional(),
59379
+ approvedVersion: number2().int().positive().nullable().optional(),
59380
+ status: _enum2(["unregistered", "waiting", "approved", "changes_requested"]).optional(),
59381
+ changesReason: nonEmptyString2.optional()
59382
+ });
59383
+ var legionSlotView = object({
59384
+ index: number2().int().nonnegative().optional(),
59385
+ admittedAt: timestamp.optional(),
59386
+ lentTo: issueKey.optional()
59387
+ });
59388
+ var legionWaitingLineView = object({
59389
+ place: number2().int().positive().optional(),
59390
+ length: number2().int().positive().optional(),
59391
+ part: _enum2(["returned", "starting"]).optional(),
59392
+ kind: _enum2(["returning", "answered", "queued_root", "first_phase", "waiting_on_issue"]).optional(),
59393
+ partPlace: number2().int().positive().optional(),
59394
+ partLength: number2().int().positive().optional(),
59395
+ holdsSlot: boolean2().optional(),
59396
+ since: timestamp.optional(),
59397
+ rootRank: nonEmptyString2.optional(),
59398
+ ownRank: nonEmptyString2.optional(),
59399
+ rootKey: issueKey.optional(),
59400
+ reason: nonEmptyString2.optional()
59401
+ });
59402
+ var legionWhyView = object({
59403
+ state: _enum2(["claim_stopped", "waiting", "blocked", "unlisted"]).optional(),
59404
+ reason: nonEmptyString2.optional()
59405
+ });
59406
+ var legionCheckWakeView = object({
59407
+ kind: nonEmptyString2.optional(),
59408
+ detail: string2().optional(),
59409
+ at: timestamp.optional()
59410
+ });
59411
+ var legionCheckView = object({
59412
+ repo: nonEmptyString2.optional(),
59413
+ pullRequest: number2().int().positive().optional(),
59414
+ mergeCommit: string2().optional(),
59415
+ openedAt: timestamp.optional(),
59416
+ role: nonEmptyString2,
59417
+ looks: number2().int().nonnegative(),
59418
+ lookOpen: boolean2().optional(),
59419
+ lastWake: legionCheckWakeView.optional(),
59420
+ nextWakeAt: timestamp.optional(),
59421
+ last: boolean2()
59422
+ });
59423
+ var LEGION_WAIT_ANSWERS = [
59424
+ "ask",
59425
+ "retracted",
59426
+ "closed",
59427
+ "reply",
59428
+ "declined",
59429
+ "turn",
59430
+ "approved",
59431
+ "changes_requested",
59432
+ "version"
59433
+ ];
59434
+ var legionWaitTimes = {
59435
+ since: timestamp.optional(),
59436
+ answeredAt: timestamp.optional(),
59437
+ answeredBy: _enum2(LEGION_WAIT_ANSWERS).optional()
59438
+ };
59439
+ var legionWaitingOn = discriminatedUnion("kind", [
59440
+ object({ kind: literal("ask"), ask: nonEmptyString2.optional(), ...legionWaitTimes }),
59441
+ object({
59442
+ kind: literal("gate"),
59443
+ gateVersion: number2().int().positive().optional(),
59444
+ artifactId: nonEmptyString2.optional(),
59445
+ ...legionWaitTimes
59446
+ })
59447
+ ]).refine((wait) => wait.answeredAt === undefined === (wait.answeredBy === undefined), {
59448
+ message: "answeredAt and answeredBy appear together"
59449
+ });
59450
+ var legionPendingStatusWrite = object({
59451
+ issue: nonEmptyString2.optional(),
59452
+ payload: record(string2(), unknown()).optional(),
59453
+ attempts: number2().int().nonnegative().optional(),
59454
+ nextAt: timestamp.optional(),
59455
+ lastError: string2().optional()
59456
+ });
59457
+ var legionStrandedClaim = object({
59458
+ issue: issueKey.optional(),
59459
+ role: _enum2(LEGION_ROLES).optional(),
59460
+ state: _enum2(["suspended", "failed", "retired"]).optional()
59461
+ });
59462
+ var legionHeldOutboxRow = object({
59463
+ id: number2().int().positive().optional(),
59464
+ kind: nonEmptyString2.optional(),
59465
+ issue: nonEmptyString2.optional(),
59466
+ waitedSeconds: number2().int().nonnegative().optional(),
59467
+ waitsOn: number2().int().positive().optional()
59468
+ });
59469
+ var legionWakeWaiting = object({
59470
+ claim: nonEmptyString2.optional(),
59471
+ issue: issueKey.optional(),
59472
+ role: _enum2(LEGION_ROLES).optional(),
59473
+ ...legionPacedWake,
59474
+ dueAt: timestamp
59475
+ });
59476
+ var legionAssignment = object({
59477
+ experiment: nonEmptyString2.optional(),
59478
+ variant: string2().optional(),
59479
+ mode: string2().optional(),
59480
+ drawnAt: timestamp.optional()
59481
+ });
59482
+ var legionIssue = object({
59483
+ key: nonEmptyString2.optional(),
59484
+ generation: number2().int().nonnegative().optional(),
59485
+ phase: _enum2(LEGION_PHASES),
59486
+ status: nonEmptyString2.optional(),
59487
+ tree: issueKey.optional(),
59488
+ repo: nonEmptyString2.optional(),
59489
+ defaultBranch: nonEmptyString2.optional(),
59490
+ holdReason: literal("escalated").optional(),
59491
+ heldFrom: _enum2(LEGION_WORKFLOW_PHASES).optional(),
59492
+ lingerUntil: timestamp.optional(),
59493
+ ancestry: array(issueKey).optional(),
59494
+ architect: legionClaimView.optional(),
59495
+ workers: partialRecord(string2(), legionPhaseView).optional(),
59496
+ pullRequest: legionPullRequestView.optional(),
59497
+ designGate: legionGateView.optional(),
59498
+ gatedSteps: array(legionGatedStepView).optional(),
59499
+ slot: legionSlotView.optional(),
59500
+ waitingLine: legionWaitingLineView.optional(),
59501
+ why: legionWhyView.optional(),
59502
+ waitingOn: legionWaitingOn.optional(),
59503
+ check: legionCheckView.optional(),
59504
+ mergeWait: legionMergeWaitView.optional(),
59505
+ memoryGroup: _enum2(["memory", "none"]).optional(),
59506
+ memoryDrawMode: _enum2(["off", "on", "random"]).optional(),
59507
+ memoryDrawnAt: timestamp.optional(),
59508
+ phaseEntry: number2().int().nonnegative().optional(),
59509
+ givenEntry: number2().int().nonnegative().optional(),
59510
+ entryQueuedAt: timestamp.optional(),
59511
+ entryConfirmedAt: timestamp.optional(),
59512
+ architectStalls: array(_enum2(["took-nothing", "claim-unreachable", "slow-before-gate"])).optional(),
59513
+ treeMovedAt: timestamp.optional(),
59514
+ quietHours: number2().nonnegative().optional(),
59515
+ assignments: array(legionAssignment).optional()
59516
+ });
59517
+ var daemonInfo = object({
59518
+ project: nonEmptyString2.optional(),
59519
+ schemaVersion: number2().int().nonnegative().optional(),
59520
+ boots: number2().int().nonnegative().optional(),
59521
+ firstBootAt: timestamp.optional(),
59522
+ startedAt: timestamp.optional()
59523
+ });
59524
+ var legionContract = object({
59525
+ daemon: number2().int().positive().optional(),
59526
+ caller: number2().int().positive().optional()
59527
+ });
59528
+ var legionBlockedIssue = object({
59529
+ issue: issueKey.optional(),
59530
+ blockedBy: array(issueKey).optional()
59531
+ });
59532
+ var LEGION_HELD_REASONS = [
59533
+ "tree_closed",
59534
+ "tree_parked",
59535
+ "label_off",
59536
+ "ancestry",
59537
+ "root_awaiting_person",
59538
+ "design_gate",
59539
+ "dispatch_blocker",
59540
+ "children_first",
59541
+ "accepted_ancestor",
59542
+ "at_work",
59543
+ "unclassified"
59544
+ ];
59545
+ var legionHeldIssue = object({
59546
+ issue: issueKey.optional(),
59547
+ reason: _enum2(LEGION_HELD_REASONS).optional(),
59548
+ heldBy: array(issueKey).optional()
59549
+ });
59550
+ var legionAdmission = object({
59551
+ cap: number2().int().nonnegative().optional(),
59552
+ active: array(nonEmptyString2).optional(),
59553
+ waiting: array(nonEmptyString2).optional(),
59554
+ trees: array(issueKey).optional(),
59555
+ blocked: array(legionBlockedIssue).optional(),
59556
+ held: array(legionHeldIssue).optional(),
59557
+ free: number2().int().nonnegative().optional()
59558
+ });
59559
+ var legionControllerLocator = object({
59560
+ runtime: _enum2(["tmux", "kubernetes"]).optional(),
59561
+ external: literal(true).optional(),
59562
+ sessionId: nonEmptyString2.optional(),
59563
+ registeredAt: timestamp.optional(),
59564
+ pluginContract: number2().int().nonnegative().optional()
59565
+ });
59566
+ var legionAgentSecretsLoginView = object({
59567
+ state: string2().optional()
59568
+ });
59569
+ var legionCapabilityState = object({
59570
+ name: nonEmptyString2.optional(),
59571
+ status: _enum2(["present", "unchecked", "withheld", "decided", "open"]).optional(),
59572
+ detail: nonEmptyString2.optional(),
59573
+ decision: nonEmptyString2.optional(),
59574
+ configLine: nonEmptyString2.optional(),
59575
+ source: _enum2(["configuration", "boot"]).optional()
59576
+ });
59577
+ var legionSettings = looseObject({
59578
+ review_round_cap: number2().int().positive().optional(),
59579
+ worker_boot_timeout_seconds: number2().int().positive().optional()
59580
+ });
59581
+ var legionCacheView = object({
59582
+ repo: nonEmptyString2.optional(),
59583
+ sandbox: nonEmptyString2.optional(),
59584
+ state: _enum2(["starting", "cloning", "ready", "failing", "refused"]).optional(),
59585
+ reason: nonEmptyString2.optional(),
59586
+ ready: boolean2().optional(),
59587
+ address: nonEmptyString2.optional(),
59588
+ head: nonEmptyString2.optional(),
59589
+ lastFetchAt: timestamp.optional(),
59590
+ bytes: number2().int().positive().optional(),
59591
+ healthError: nonEmptyString2.optional(),
59592
+ retainedUntil: timestamp.optional()
59593
+ });
59594
+ var legionAppInstallations = object({
59595
+ implement: boolean2().optional(),
59596
+ review: boolean2().optional()
59597
+ });
59598
+ var legionRepositories = object({
59599
+ owners: array(nonEmptyString2).optional(),
59600
+ mapped: array(object({
59601
+ repo: nonEmptyString2.optional(),
59602
+ default: boolean2().optional(),
59603
+ apps: legionAppInstallations.optional(),
59604
+ cache: legionCacheView.optional()
59605
+ })).optional(),
59606
+ refused: array(object({
59607
+ repo: nonEmptyString2.optional(),
59608
+ reason: nonEmptyString2.optional(),
59609
+ apps: legionAppInstallations.optional()
59610
+ })).optional(),
59611
+ withoutWebhookApp: array(object({ repo: nonEmptyString2.optional(), reason: nonEmptyString2.optional() })).optional(),
59612
+ caches: array(legionCacheView).optional()
59613
+ });
59614
+ var legionConsumerLag = object({
59615
+ name: nonEmptyString2.optional(),
59616
+ waiting: number2().int().nonnegative().optional(),
59617
+ oldestAt: timestamp.nullable().optional(),
59618
+ oldestAgeSeconds: number2().int().nullable().optional(),
59619
+ lastHandledAt: timestamp.nullable().optional(),
59620
+ stalled: boolean2().optional(),
59621
+ unavailable: nonEmptyString2.optional()
59622
+ });
59623
+ var legionPauseActor = discriminatedUnion("kind", [
59624
+ object({ kind: literal("controller"), session: nonEmptyString2 }),
59625
+ object({ kind: literal("operator") })
59626
+ ]);
59627
+ var pauseFields = {
59628
+ id: number2().int().positive(),
59629
+ since: timestamp,
59630
+ by: legionPauseActor,
59631
+ reason: nonEmptyString2
59632
+ };
59633
+ var legionPause = object({
59634
+ ...pauseFields,
59635
+ endedAt: timestamp.optional(),
59636
+ endedBy: legionPauseActor.optional()
59637
+ });
59638
+ var legionEndedPause = object({
59639
+ ...pauseFields,
59640
+ endedAt: timestamp,
59641
+ endedBy: legionPauseActor
59642
+ });
59643
+ var legionPauseStop = object({
59644
+ claim: nonEmptyString2.optional(),
59645
+ issue: issueKey,
59646
+ role: _enum2(LEGION_ROLES),
59647
+ askedAt: timestamp.optional()
59648
+ });
59649
+ var legionPauseHeldRow = object({
59650
+ id: number2().int().positive().optional(),
59651
+ kind: nonEmptyString2.optional(),
59652
+ issue: nonEmptyString2.optional(),
59653
+ claim: nonEmptyString2.optional(),
59654
+ waitedSeconds: number2().int().nonnegative().optional()
59655
+ });
59656
+ var legionPaused = object({
59657
+ ...pauseFields,
59658
+ waitsOn: array(legionPauseStop),
59659
+ held: array(legionPauseHeldRow)
59660
+ });
59661
+ var LegionStateResponse = object({
59662
+ daemon: daemonInfo.optional(),
59663
+ contract: legionContract.optional(),
59664
+ admission: legionAdmission.optional(),
59665
+ issues: record(string2(), legionIssue),
59666
+ pendingStatusWrites: array(legionPendingStatusWrite).optional(),
59667
+ heldOutboxRows: array(legionHeldOutboxRow).optional(),
59668
+ strandedClaims: array(legionStrandedClaim).optional(),
59669
+ wakesWaiting: array(legionWakeWaiting).optional(),
59670
+ claimsToRefresh: number2().int().nonnegative().optional(),
59671
+ paused: legionPaused.optional(),
59672
+ lastPause: legionEndedPause.optional(),
59673
+ controllerLocator: legionControllerLocator.optional(),
59674
+ agentSecretsLogin: legionAgentSecretsLoginView.optional(),
59675
+ capabilities: array(legionCapabilityState).optional(),
59676
+ repositories: legionRepositories.optional(),
59677
+ settings: legionSettings.optional(),
59678
+ consumers: array(legionConsumerLag).optional(),
59679
+ lowestPluginContract: number2().int().positive().optional()
59680
+ });
59681
+ var LegionIssueRecordResponse = legionIssue;
59682
+ var LegionHealthResponse = object({
59683
+ status: nonEmptyString2.optional(),
59684
+ project: nonEmptyString2
59685
+ });
59686
+ var LegionRegisterResponse = object({
59687
+ claimToken: nonEmptyString2,
59688
+ tree: nonEmptyString2,
59689
+ issue: nonEmptyString2,
59690
+ role: _enum2(LEGION_ROLES),
59691
+ generation: number2().int().positive(),
59692
+ secret: nonEmptyString2,
59693
+ promptAgents: array(nonEmptyString2)
59694
+ });
59695
+ var LegionCapabilityReport = strictObject({
59696
+ measuredAt: timestamp,
59697
+ elapsedMs: number2().int().nonnegative(),
59698
+ rows: array(strictObject({ name: nonEmptyString2, ok: boolean2(), detail: string2() }))
59699
+ });
59700
+ var LegionReadyRequest = strictObject({
59701
+ claimToken: nonEmptyString2,
59702
+ sessionId: nonEmptyString2,
59703
+ secret: nonEmptyString2,
59704
+ generation: number2().int().positive(),
59705
+ capabilities: LegionCapabilityReport.optional()
59706
+ });
59707
+ var turnOutcomeFields = {
59708
+ generation: number2().int().positive(),
59709
+ sequence: number2().int().positive(),
59710
+ outcome: _enum2(["clean", "refused"]),
59711
+ message: string2().optional()
59712
+ };
59713
+ var LegionTurnOutcomeAgentRequest = strictObject({
59714
+ claimToken: nonEmptyString2,
59715
+ sessionId: nonEmptyString2,
59716
+ secret: nonEmptyString2,
59717
+ ...turnOutcomeFields
59718
+ });
59719
+ var LegionTurnOutcomeBootRequest = strictObject({
59720
+ bootToken: nonEmptyString2,
59721
+ ...turnOutcomeFields
59722
+ });
59723
+ var LegionTurnOutcomeRequest = union([
59724
+ LegionTurnOutcomeAgentRequest,
59725
+ LegionTurnOutcomeBootRequest
59726
+ ]);
59727
+ var LegionTurnOutcomeResponse = object({
59728
+ refusedRun: number2().int().nonnegative(),
59729
+ failed: boolean2()
59730
+ });
59731
+ var LegionReadyForUpdateRequest = strictObject({
59732
+ claimToken: nonEmptyString2,
59733
+ sessionId: nonEmptyString2,
59734
+ secret: nonEmptyString2,
59735
+ generation: number2().int().positive(),
59736
+ round: nonEmptyString2,
59737
+ head: string2().optional()
59738
+ });
59739
+ var LegionSessionActivity = strictObject({
59740
+ at: timestamp,
59741
+ backgroundWork: strictObject({ running: boolean2(), kinds: array(nonEmptyString2) }),
59742
+ phase: strictObject({ nextReminderAt: timestamp.nullable() })
59743
+ });
59744
+ var LegionActivityRequest = strictObject({
59745
+ claimToken: nonEmptyString2,
59746
+ sessionId: nonEmptyString2,
59747
+ secret: nonEmptyString2,
59748
+ activity: LegionSessionActivity
59749
+ });
59750
+ var legionReleaseRecord = object({
59751
+ id: number2().int().positive(),
59752
+ issue: issueKey,
59753
+ generation: number2().int().nonnegative().optional(),
59754
+ roles: array(nonEmptyString2),
59755
+ at: timestamp,
59756
+ bundleBytes: number2().int().nonnegative().optional()
59757
+ });
59758
+ var legionResumeRecord = object({
59759
+ id: number2().int().positive().optional(),
59760
+ release: number2().int().nonnegative(),
59761
+ issue: issueKey,
59762
+ role: nonEmptyString2.optional(),
59763
+ kind: nonEmptyString2,
59764
+ at: timestamp,
59765
+ podReadyAt: timestamp.optional(),
59766
+ firstTurnAt: timestamp.optional(),
59767
+ stuck: boolean2().optional(),
59768
+ pause: number2().int().positive().optional()
59769
+ });
59770
+ var legionHoldRecord = object({
59771
+ id: number2().int().positive().optional(),
59772
+ issue: issueKey.optional(),
59773
+ reason: nonEmptyString2,
59774
+ detail: nonEmptyString2.optional(),
59775
+ firstAt: timestamp.optional(),
59776
+ at: timestamp.optional(),
59777
+ passes: number2().int().positive().optional()
59778
+ });
59779
+ var LegionReleaseRecordsRequest = strictObject({
59780
+ claimToken: nonEmptyString2,
59781
+ secret: nonEmptyString2,
59782
+ since: LegionInstant
59783
+ });
59784
+ var LegionReleaseRecordsResponse = object({
59785
+ releases: array(legionReleaseRecord),
59786
+ resumes: array(legionResumeRecord),
59787
+ holds: array(legionHoldRecord)
59788
+ });
59789
+ var LegionControllerRegisterResponse = object({
59790
+ claimToken: nonEmptyString2,
59791
+ role: literal("controller").optional(),
59792
+ generation: number2().int().positive(),
59793
+ secret: nonEmptyString2
59794
+ });
59795
+ var LegionControllerSecretResponse = object({
59796
+ secret: nonEmptyString2,
59797
+ designGateSteps: array(legionDesignStep)
59798
+ });
59799
+ var LegionControllerCredentialResponse = object({
59800
+ owners: record(nonEmptyString2, object({
59801
+ hosts: nonEmptyString2,
59802
+ config: nonEmptyString2
59803
+ })),
59804
+ default: nonEmptyString2,
59805
+ app: _enum2(["implement", "review"]),
59806
+ expiresAt: timestamp,
59807
+ renames: array(object({ from: nonEmptyString2, to: nonEmptyString2 })).optional(),
59808
+ installed: array(nonEmptyString2)
59809
+ });
59810
+ var LegionErrorResponse = object({
59811
+ error: nonEmptyString2,
59812
+ code: nonEmptyString2.optional()
59813
+ });
59814
+ var legionDeliveryView = object({
59815
+ id: nonEmptyString2,
59816
+ task: nonEmptyString2,
59817
+ phase: _enum2(LEGION_WORKFLOW_PHASES).optional(),
59818
+ queuedAt: timestamp,
59819
+ deliveredAt: timestamp.optional(),
59820
+ confirmedAt: timestamp.optional(),
59821
+ interrupted: literal(true).optional(),
59822
+ sendFailures: number2().int().nonnegative().optional(),
59823
+ lastSendFailureAt: timestamp.optional(),
59824
+ lastSendError: nonEmptyString2.optional()
59825
+ });
59826
+ var legionSuspendedBy = _enum2(["unknown", "operator", "daemon", "exit", "released"]);
59827
+ var LegionOperatorClaimResponse = object({
59828
+ token: nonEmptyString2,
59829
+ tree: nonEmptyString2,
59830
+ issue: nonEmptyString2,
59831
+ role: _enum2(LEGION_ROLES),
59832
+ generation: number2().int().nonnegative(),
59833
+ state: _enum2(LEGION_CLAIM_STATES),
59834
+ session: string2(),
59835
+ sessionFile: string2(),
59836
+ forgottenSession: nonEmptyString2.optional(),
59837
+ forgottenSessionFile: nonEmptyString2.optional(),
59838
+ phaseNotRestarted: nonEmptyString2.optional(),
59839
+ locator: legionLocator.optional(),
59840
+ budgets: object({
59841
+ launchFailures: number2().int().nonnegative(),
59842
+ deaths: number2().int().nonnegative(),
59843
+ promptFailures: number2().int().nonnegative(),
59844
+ promptRetires: number2().int().nonnegative()
59845
+ }),
59846
+ uncertainStreak: number2().int().nonnegative(),
59847
+ pending: legionDeliveryView.optional(),
59848
+ suspendedBy: legionSuspendedBy.optional(),
59849
+ suspensionHeld: literal(true).optional(),
59850
+ suspensionHeldBy: legionSuspendedBy.optional(),
59851
+ compacting: literal(true).optional(),
59852
+ processGone: literal(true).optional(),
59853
+ pluginContract: number2().int().nonnegative(),
59854
+ updateRound: nonEmptyString2.optional(),
59855
+ updateHead: nonEmptyString2.optional(),
59856
+ lastTurnStart: timestamp.optional(),
59857
+ lastTurnEnd: timestamp.optional(),
59858
+ lastDeathCause: nonEmptyString2.optional(),
59859
+ lastStartFailure: nonEmptyString2.optional(),
59860
+ lastReady: timestamp.optional(),
59861
+ step: legionStepView.optional(),
59862
+ failure: legionClaimFailureView.optional(),
59863
+ leakCheckCause: nonEmptyString2.optional()
59864
+ });
59865
+ var legionPodUpdateRounds = object({
59866
+ swept: boolean2(),
59867
+ max_open_rounds: number2().int().nullable(),
59868
+ rounds_per_minute: number2().int().nullable(),
59869
+ in_round: array(nonEmptyString2),
59870
+ waiting_on_max_open_rounds: array(nonEmptyString2),
59871
+ waiting_on_rounds_per_minute: array(nonEmptyString2)
59872
+ });
59873
+ var LegionOperatorClaimsResponse = object({
59874
+ claims: array(LegionOperatorClaimResponse),
59875
+ pod_update_rounds: legionPodUpdateRounds
59930
59876
  });
59931
-
59932
- class SessionIdentity {
59933
- directory;
59934
- #id;
59935
- constructor(id, directory) {
59936
- this.directory = directory;
59937
- this.#id = id;
59938
- }
59939
- get id() {
59940
- return this.#id;
59941
- }
59942
- set(next) {
59943
- this.#id = next;
59944
- }
59945
- }
59946
- function sessionHandoffDirectory(stateDirectory, claudePid) {
59947
- return join8(stateDirectory, "sessions", String(claudePid));
59948
- }
59949
- function sessionHandoffFile(stateDirectory, claudePid) {
59950
- return join8(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
59951
- }
59952
- var ROLES_DIRECTORY = "roles";
59953
- function roleStateFile(stateDirectory, sessionId) {
59954
- return join8(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
59955
- }
59956
-
59957
- class UnparseableRoleRecordError extends Error {
59958
- name = "UnparseableRoleRecordError";
59959
- constructor(roleFile, cause) {
59960
- super(`the role record ${roleFile} cannot be parsed (${messageFor(cause)})`, { cause });
59961
- }
59962
- }
59963
- async function readPersistedRole(roleFile) {
59964
- let bytes;
59965
- try {
59966
- bytes = await readFile3(roleFile, "utf8");
59967
- } catch (error) {
59968
- if (hasErrnoCode(error, "ENOENT"))
59969
- return;
59970
- throw error;
59971
- }
59972
- try {
59973
- return PersistedRole.parse(JSON.parse(bytes));
59974
- } catch (error) {
59975
- throw new UnparseableRoleRecordError(roleFile, error);
59976
- }
59977
- }
59978
- async function writePersistedRole(roleFile, state) {
59979
- await writeAtomicStateFile(roleFile, `${JSON.stringify(state)}
59980
- `);
59981
- }
59982
- async function writeSessionHandoff(file, sessionId) {
59983
- await writeAtomicStateFile(file, `${sessionId.trim()}
59984
- `);
59985
- }
59986
- async function readSessionHandoff(file) {
59987
- try {
59988
- const id = (await readFile3(file, "utf8")).trim();
59989
- return id.length === 0 ? undefined : id;
59990
- } catch (error) {
59991
- if (hasErrnoCode(error, "ENOENT"))
59992
- return;
59993
- throw error;
59994
- }
59995
- }
59996
- function processExists(pid) {
59997
- try {
59998
- process.kill(pid, 0);
59999
- return true;
60000
- } catch (error) {
60001
- return hasErrnoCode(error, "EPERM");
60002
- }
59877
+ var LegionGrantResponse = object({
59878
+ grantId: nonEmptyString2,
59879
+ expiresAt: timestamp.optional()
59880
+ });
59881
+ var LegionEmptyResponse = object({});
59882
+ var LegionHandoffCompleteResponse = object({});
59883
+ var LegionWaveReleaseResponse = object({
59884
+ released: array(nonEmptyString2).optional(),
59885
+ started: array(issueKey).optional(),
59886
+ held: array(legionBlockedIssue).optional()
59887
+ });
59888
+ var legionAnsweredPause = object({
59889
+ id: number2().int().positive().optional(),
59890
+ since: timestamp.optional(),
59891
+ by: legionPauseActor.optional(),
59892
+ reason: nonEmptyString2.optional(),
59893
+ endedAt: timestamp.optional(),
59894
+ endedBy: legionPauseActor.optional()
59895
+ });
59896
+ var LegionProjectPauseResponse = object({
59897
+ pause: legionAnsweredPause.optional()
59898
+ });
59899
+ var LegionProjectResumeResponse = object({
59900
+ pause: legionAnsweredPause.optional(),
59901
+ released: number2().int().nonnegative().optional()
59902
+ });
59903
+ var LegionPauseFailureResponse = object({
59904
+ code: nonEmptyString2,
59905
+ error: nonEmptyString2,
59906
+ setting: nonEmptyString2.optional(),
59907
+ pause: legionPause.optional(),
59908
+ lastPause: legionEndedPause.optional()
59909
+ });
59910
+ var LegionGrantRequest = strictObject({
59911
+ sessionId: nonEmptyString2,
59912
+ secret: nonEmptyString2,
59913
+ tree: nonEmptyString2,
59914
+ issue: nonEmptyString2
59915
+ });
59916
+ var LegionControllerGrantRequest = strictObject({
59917
+ sessionId: nonEmptyString2,
59918
+ secret: nonEmptyString2
59919
+ });
59920
+ function legionPlanRatingScale(rating, refusal) {
59921
+ const error = refusal === undefined ? undefined : { error: refusal };
59922
+ return rating.int(error).min(LEGION_PLAN_RATING_LEAST, error).max(LEGION_PLAN_RATING_MOST, error);
60003
59923
  }
60004
- async function pruneStaleSessionHandoffs(stateDirectory) {
60005
- await pruneStateDirectory(join8(stateDirectory, "sessions"), (file) => {
60006
- const pid = basename2(file);
60007
- return /^\d+$/.test(pid) && !processExists(Number(pid));
60008
- });
59924
+ function legionPlanReasonRules(reason, refusals) {
59925
+ return reason.refine((text) => !goBlankPattern.test(text), { error: refusals.blank, abort: true }).refine((text) => [...text].length <= LEGION_PLAN_REASON_MAX, { error: refusals.long });
60009
59926
  }
60010
- async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
60011
- const own = roleStateFile(stateDirectory, currentSessionId);
60012
- await pruneStateDirectory(join8(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
59927
+ var legionPlanReason = legionPlanReasonRules(string2(), {
59928
+ blank: "planReason says why",
59929
+ long: `planReason holds at most ${LEGION_PLAN_REASON_MAX} characters`
59930
+ });
59931
+ function legionPlanRatingLoneField(rating, reason) {
59932
+ if (rating !== undefined && reason === undefined)
59933
+ return "rating";
59934
+ if (reason !== undefined && rating === undefined)
59935
+ return "reason";
59936
+ return;
60013
59937
  }
59938
+ var LegionHandoffCompleteRequest = strictObject({
59939
+ grantId: nonEmptyString2,
59940
+ summary: nonEmptyString2,
59941
+ verdict: string2(),
59942
+ commit: nonEmptyString2.optional(),
59943
+ handoffId: nonEmptyString2.optional(),
59944
+ handoffVersion: number2().int().positive().optional(),
59945
+ wakeAt: LegionInstant.optional(),
59946
+ planRating: legionPlanRatingScale(number2()).optional(),
59947
+ planReason: legionPlanReason.optional()
59948
+ }).refine((request) => legionPlanRatingLoneField(request.planRating, request.planReason) === undefined, { message: "planRating and planReason appear together" });
59949
+ var LegionIssueStatusRequest = strictObject({
59950
+ grantId: nonEmptyString2,
59951
+ issue: nonEmptyString2,
59952
+ status: _enum2(["todo", "backlog", "icebox"])
59953
+ });
59954
+ var LegionProjectPauseRequest = strictObject({
59955
+ grantId: nonEmptyString2,
59956
+ reason: nonEmptyString2
59957
+ });
59958
+ var LegionProjectResumeRequest = strictObject({
59959
+ grantId: nonEmptyString2
59960
+ });
59961
+ var LegionOperatorProjectPauseRequest = strictObject({
59962
+ reason: nonEmptyString2
59963
+ });
59964
+ var LegionGateRegisterRequest = strictObject({
59965
+ grantId: nonEmptyString2,
59966
+ issue: nonEmptyString2,
59967
+ artifactId: uuid2(),
59968
+ version: number2().int().positive(),
59969
+ step: legionDesignStep.optional()
59970
+ });
59971
+ var LegionWaveReleaseRequest = strictObject({
59972
+ grantId: nonEmptyString2,
59973
+ issues: array(nonEmptyString2)
59974
+ });
59975
+ var LegionPhaseBackwardRequest = strictObject({
59976
+ grantId: nonEmptyString2,
59977
+ to: _enum2(LEGION_PHASE_BACKWARD_TARGETS),
59978
+ reason: nonEmptyString2,
59979
+ issue: nonEmptyString2.optional()
59980
+ });
59981
+ var LegionPhaseRetryRequest = strictObject({
59982
+ grantId: nonEmptyString2,
59983
+ issue: nonEmptyString2,
59984
+ decision: _enum2(["retry", "escalate"]),
59985
+ reason: nonEmptyString2.optional()
59986
+ });
59987
+ var LegionEscalateRequest = strictObject({
59988
+ grantId: nonEmptyString2,
59989
+ issue: nonEmptyString2,
59990
+ reason: nonEmptyString2
59991
+ });
59992
+ var LegionSignOffRequest = strictObject({
59993
+ grantId: nonEmptyString2,
59994
+ issue: nonEmptyString2
59995
+ });
59996
+ var LegionRootCloseRequest = strictObject({
59997
+ grantId: nonEmptyString2,
59998
+ issue: nonEmptyString2,
59999
+ reason: nonEmptyString2
60000
+ });
60001
+ var LegionChildRequest = strictObject({
60002
+ grantId: nonEmptyString2,
60003
+ issue: nonEmptyString2
60004
+ });
60005
+ var ISSUE_RECORD_READS = [
60006
+ "phase",
60007
+ "status",
60008
+ "holdReason",
60009
+ "architect",
60010
+ "architect.state",
60011
+ "architect.lastTurnStart",
60012
+ "architect.lastTurnEnd",
60013
+ "workers",
60014
+ "workers{}.claim",
60015
+ "workers{}.claim.state",
60016
+ "workers{}.claim.lastTurnStart",
60017
+ "workers{}.claim.lastTurnEnd",
60018
+ "check",
60019
+ "check.role",
60020
+ "check.looks",
60021
+ "check.last",
60022
+ "designGate",
60023
+ "designGate.currentVersion",
60024
+ "designGate.approvedVersion",
60025
+ "slot",
60026
+ "slot.index",
60027
+ "slot.admittedAt",
60028
+ "slot.lentTo"
60029
+ ];
60030
+ var LEGION_ANSWER_READS = {
60031
+ LegionStateResponse: [
60032
+ "issues",
60033
+ ...ISSUE_RECORD_READS.map((field) => `issues{}.${field}`),
60034
+ "admission",
60035
+ "admission.blocked[].issue",
60036
+ "admission.blocked[].blockedBy",
60037
+ "capabilities",
60038
+ "capabilities[].name",
60039
+ "capabilities[].status",
60040
+ "capabilities[].detail",
60041
+ "capabilities[].configLine",
60042
+ "wakesWaiting",
60043
+ "wakesWaiting[].dueAt",
60044
+ "paused",
60045
+ "paused.id",
60046
+ "paused.since",
60047
+ "paused.by",
60048
+ "paused.by|0.kind",
60049
+ "paused.by|1.kind",
60050
+ "paused.by|0.session",
60051
+ "paused.reason",
60052
+ "paused.waitsOn",
60053
+ "paused.waitsOn[].issue",
60054
+ "paused.waitsOn[].role",
60055
+ "paused.held",
60056
+ "lastPause",
60057
+ "lastPause.id",
60058
+ "lastPause.since",
60059
+ "lastPause.by",
60060
+ "lastPause.by|0.kind",
60061
+ "lastPause.by|1.kind",
60062
+ "lastPause.by|0.session",
60063
+ "lastPause.reason",
60064
+ "lastPause.endedAt",
60065
+ "lastPause.endedBy",
60066
+ "lastPause.endedBy|0.kind",
60067
+ "lastPause.endedBy|1.kind",
60068
+ "lastPause.endedBy|0.session"
60069
+ ],
60070
+ LegionIssueRecordResponse: ISSUE_RECORD_READS,
60071
+ LegionHealthResponse: ["project"],
60072
+ LegionRegisterResponse: [
60073
+ "claimToken",
60074
+ "tree",
60075
+ "issue",
60076
+ "role",
60077
+ "generation",
60078
+ "secret",
60079
+ "promptAgents"
60080
+ ],
60081
+ LegionControllerRegisterResponse: ["claimToken", "generation", "secret"],
60082
+ LegionGrantResponse: ["grantId"],
60083
+ LegionErrorResponse: ["error", "code"],
60084
+ LegionReleaseRecordsResponse: [
60085
+ "releases",
60086
+ "releases[].id",
60087
+ "releases[].issue",
60088
+ "releases[].roles",
60089
+ "releases[].at",
60090
+ "resumes",
60091
+ "resumes[].release",
60092
+ "resumes[].issue",
60093
+ "resumes[].at",
60094
+ "resumes[].kind",
60095
+ "resumes[].firstTurnAt",
60096
+ "resumes[].pause",
60097
+ "holds",
60098
+ "holds[].reason"
60099
+ ],
60100
+ LegionProjectPauseResponse: [
60101
+ "pause.by|0.kind",
60102
+ "pause.by|1.kind",
60103
+ "pause.by|0.session",
60104
+ "pause.endedBy|0.kind",
60105
+ "pause.endedBy|1.kind",
60106
+ "pause.endedBy|0.session"
60107
+ ],
60108
+ LegionProjectResumeResponse: [
60109
+ "pause.by|0.kind",
60110
+ "pause.by|1.kind",
60111
+ "pause.by|0.session",
60112
+ "pause.endedBy|0.kind",
60113
+ "pause.endedBy|1.kind",
60114
+ "pause.endedBy|0.session"
60115
+ ],
60116
+ LegionTurnOutcomeResponse: ["refusedRun", "failed"]
60117
+ };
60014
60118
 
60015
- // src/envoy-off.ts
60016
- function inboundOffChannelSession(options) {
60017
- const { identity, stateDirectory, why } = options;
60018
- return {
60019
- delivery: { enqueue: async () => false, inbox: () => [] },
60020
- topics: () => [],
60021
- async follow() {
60022
- throw new Error(`inbound messages are off for this session: ${why}`);
60023
- },
60024
- unfollow: async () => [],
60025
- onRoleRegained: () => {
60026
- return;
60027
- },
60028
- capabilitiesChanged: () => {
60029
- return;
60030
- },
60031
- observe: () => {
60032
- return;
60033
- },
60034
- messageOf: () => {
60035
- return;
60036
- },
60037
- async rememberRole(role) {
60038
- await writePersistedRole(roleStateFile(stateDirectory, identity.id), {
60039
- session_id: identity.id,
60040
- role
60041
- });
60042
- },
60043
- shutdown: async () => {
60044
- return;
60045
- }
60046
- };
60047
- }
60048
- async function serveEnvoyOff(serverInfo, refusal) {
60049
- const server = new Server(serverInfo, { capabilities: { tools: {} } });
60050
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [] }));
60051
- server.setRequestHandler(CallToolRequestSchema, async () => {
60052
- throw new Error(refusal);
60053
- });
60054
- const stopped = Promise.withResolvers();
60055
- process.stdin.once("end", stopped.resolve);
60056
- for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
60057
- process.once(signal, () => stopped.resolve());
60119
+ // ../pi-shared/src/daemon-client.ts
60120
+ class LegionDaemonApiError extends Error {
60121
+ method;
60122
+ path;
60123
+ status;
60124
+ code;
60125
+ detail;
60126
+ constructor(method, path, status, code, detail) {
60127
+ super(`${method} ${path} failed with ${status}${code === undefined ? "" : ` ${code}`}: ${detail}`);
60128
+ this.method = method;
60129
+ this.path = path;
60130
+ this.status = status;
60131
+ this.code = code;
60132
+ this.detail = detail;
60133
+ this.name = "LegionDaemonApiError";
60058
60134
  }
60059
- await server.connect(new StdioServerTransport);
60060
- try {
60061
- await stopped.promise;
60062
- } finally {
60063
- await server.close().catch(() => {
60064
- return;
60065
- });
60135
+ }
60136
+ function contractStanding(mine, daemon) {
60137
+ if (daemon === undefined) {
60138
+ return `This build speaks daemon API contract ${mine}. The daemon stated no contract, so this build cannot say which side is behind.`;
60139
+ }
60140
+ if (mine < daemon) {
60141
+ return `This build speaks daemon API contract ${mine}. The daemon speaks ${daemon}. This process is behind the daemon and waits for its replacement.`;
60066
60142
  }
60143
+ if (mine > daemon) {
60144
+ return `This build speaks daemon API contract ${mine}. The daemon speaks ${daemon}. The daemon is older than this build.`;
60145
+ }
60146
+ return `This build speaks daemon API contract ${mine}. The daemon speaks ${daemon}. Neither side is behind.`;
60147
+ }
60148
+ function unreadableBody(text) {
60149
+ return `a body of ${new TextEncoder().encode(text).length} bytes`;
60067
60150
  }
60068
60151
 
60069
- // src/installed-build.ts
60070
- import { sep } from "path";
60071
- function pluginCacheSegments(bundlePath) {
60072
- const parts = bundlePath.split(sep);
60073
- for (let index = 0;index + 1 < parts.length; index++) {
60074
- if (parts[index] === "plugins" && parts[index + 1] === "cache")
60075
- return parts.slice(index + 2);
60152
+ class LegionDaemonContractError extends Error {
60153
+ method;
60154
+ path;
60155
+ status;
60156
+ pluginContract;
60157
+ daemonContract;
60158
+ problem;
60159
+ constructor(method, path, status, pluginContract, daemonContract, problem) {
60160
+ super(`${method} ${path} answered ${status} with a body the daemon API contract does not describe: ${problem}. ${contractStanding(pluginContract, daemonContract)}`);
60161
+ this.method = method;
60162
+ this.path = path;
60163
+ this.status = status;
60164
+ this.pluginContract = pluginContract;
60165
+ this.daemonContract = daemonContract;
60166
+ this.problem = problem;
60167
+ this.name = "LegionDaemonContractError";
60076
60168
  }
60077
- return;
60078
60169
  }
60079
- function installedPluginVersion(bundlePath) {
60080
- return pluginCacheSegments(bundlePath)?.[2];
60170
+ var READY_RETRY_ATTEMPTS = 3;
60171
+ var READY_RETRY_DELAY_MS = 1000;
60172
+ function isNetworkOrTimeoutError(error) {
60173
+ if (!(error instanceof Error))
60174
+ return false;
60175
+ if (error.name === "NetworkError" || error.name === "TimeoutError")
60176
+ return true;
60177
+ const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
60178
+ return code === "ConnectionRefused" || code === "ConnectionTimeout" || code === "EAI_AGAIN" || code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EHOSTUNREACH" || code === "ENETUNREACH" || code === "ENOTFOUND" || code === "ETIMEDOUT" || error instanceof TypeError && (error.message === "Failed to fetch" || error.message === "fetch failed");
60081
60179
  }
60082
-
60083
- // src/legion-claim.ts
60084
- import { readdir as readdir3, stat as stat2 } from "fs/promises";
60085
- import { join as join10 } from "path";
60086
- import { setTimeout as delay2 } from "timers/promises";
60087
-
60088
- // ../pi-shared/src/stall-limits.ts
60089
- var DEFAULT_STALL_LIMITS = {
60090
- reminderMs: 300000,
60091
- waitingMs: 900000,
60092
- resumeMs: 120000,
60093
- architectAfter: 3,
60094
- callGraceMs: 300000,
60095
- callBoundMs: 3600000,
60096
- stepMs: 120000
60097
- };
60098
- var LONG_CALL_BOUND_MS = 14400000;
60099
- var LONG_CALL_BOUND_ROLES = [
60100
- "implementer",
60101
- "reviewer"
60102
- ];
60103
- function defaultCallBoundMs(role) {
60104
- return role !== undefined && LONG_CALL_BOUND_ROLES.includes(role) ? LONG_CALL_BOUND_MS : DEFAULT_STALL_LIMITS.callBoundMs;
60180
+ async function callReadyWithRetry(label, call) {
60181
+ for (let attempt = 1;; attempt++) {
60182
+ try {
60183
+ await call();
60184
+ return;
60185
+ } catch (error) {
60186
+ const retryable = error instanceof LegionDaemonApiError ? error.status >= 500 && error.status < 600 : isNetworkOrTimeoutError(error);
60187
+ if (!retryable)
60188
+ throw error;
60189
+ if (attempt === READY_RETRY_ATTEMPTS) {
60190
+ console.error(`[legion] ${label} failed after ${attempt} attempts: ${messageFor(error)}`);
60191
+ throw error;
60192
+ }
60193
+ console.error(`[legion] ${label} failed (attempt ${attempt}/${READY_RETRY_ATTEMPTS}), retrying: ${messageFor(error)}`);
60194
+ const retryDelay = Promise.withResolvers();
60195
+ setTimeout(retryDelay.resolve, READY_RETRY_DELAY_MS);
60196
+ await retryDelay.promise;
60197
+ }
60198
+ }
60105
60199
  }
60106
- function integerSetting(env, log, name, fallback, least) {
60107
- const raw = env[name];
60108
- if (raw === undefined)
60109
- return fallback;
60110
- const value = raw.trim() === "" ? Number.NaN : Number(raw);
60111
- if (!Number.isInteger(value) || value < least) {
60112
- log.warn(`legion: ${name} is not an integer of ${least} or more; using ${fallback}`, {
60113
- value: raw
60114
- });
60115
- return fallback;
60200
+ var DAEMON_RESTART_BUDGET_MS = 10 * 60000;
60201
+ var DAEMON_RESTART_FIRST_DELAY_MS = 500;
60202
+ var DAEMON_RESTART_MAX_DELAY_MS = 30000;
60203
+ function daemonUnreachable(error) {
60204
+ if (error instanceof LegionDaemonApiError) {
60205
+ return (error.status === 502 || error.status === 503) && error.code === undefined ? "dropped" : undefined;
60116
60206
  }
60117
- return value;
60207
+ if (!(error instanceof Error))
60208
+ return;
60209
+ const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
60210
+ if (code === "ConnectionRefused" || code === "ECONNREFUSED")
60211
+ return "refused";
60212
+ if (code === "ConnectionClosed" || code === "ECONNRESET" || code === "EPIPE")
60213
+ return "dropped";
60214
+ return error instanceof TypeError && (error.message === "Failed to fetch" || error.message === "fetch failed") ? "dropped" : undefined;
60118
60215
  }
60119
- function stallLimits(env, log, role) {
60216
+ async function retryWhileDaemonRestarts(label, call, options = {}) {
60217
+ const { signal } = options;
60218
+ const now = options.now ?? Date.now;
60219
+ const sleep = options.sleep ?? ((ms, abort) => {
60220
+ const wait = Promise.withResolvers();
60221
+ const timer = setTimeout(wait.resolve, ms);
60222
+ abort?.addEventListener("abort", () => {
60223
+ clearTimeout(timer);
60224
+ wait.resolve();
60225
+ }, { once: true });
60226
+ return wait.promise;
60227
+ });
60228
+ const deadline = now() + DAEMON_RESTART_BUDGET_MS;
60229
+ let delay = DAEMON_RESTART_FIRST_DELAY_MS;
60230
+ let told = false;
60231
+ let dropped = false;
60232
+ let lastFailure;
60233
+ for (;; ) {
60234
+ if (signal?.aborted && lastFailure !== undefined) {
60235
+ throw new Error(`${label}: the Legion daemon was unreachable (${messageFor(lastFailure)}) and the call was aborted${dropped ? "; an attempt lost its connection before the daemon answered and may have been applied, so read the record before calling again" : "; call it again once the daemon is back"}`);
60236
+ }
60237
+ try {
60238
+ return await call();
60239
+ } catch (error) {
60240
+ const unreachable = daemonUnreachable(error);
60241
+ if (unreachable === undefined) {
60242
+ if (dropped && (error instanceof LegionDaemonApiError || error instanceof LegionDaemonContractError)) {
60243
+ error.message += ` (an earlier attempt of ${label} lost its connection before the daemon answered, and may have been applied: read_record of your own issue says whether it landed)`;
60244
+ }
60245
+ throw error;
60246
+ }
60247
+ lastFailure = error;
60248
+ dropped ||= unreachable === "dropped";
60249
+ const remaining = deadline - now();
60250
+ if (remaining <= 0) {
60251
+ throw new Error(`${label}: the Legion daemon was unreachable (${messageFor(error)}) and stayed so for ${DAEMON_RESTART_BUDGET_MS / 60000} minutes${dropped ? "; an attempt lost its connection before the daemon answered and may have been applied, so read the record before calling again" : "; call it again once the daemon is back"}`);
60252
+ }
60253
+ if (!told && !signal?.aborted) {
60254
+ told = true;
60255
+ const message = `The Legion daemon is unreachable, most likely restarting (${messageFor(error)}); ${label} is being retried for up to ${DAEMON_RESTART_BUDGET_MS / 60000} minutes.`;
60256
+ console.error(`[legion] ${message}`);
60257
+ options.onRetrying?.(message);
60258
+ }
60259
+ if (!signal?.aborted)
60260
+ await sleep(Math.min(delay, remaining), signal);
60261
+ delay = Math.min(delay * 2, DAEMON_RESTART_MAX_DELAY_MS);
60262
+ }
60263
+ }
60264
+ }
60265
+ function parseBody(schema, body) {
60266
+ let json;
60267
+ try {
60268
+ json = JSON.parse(body);
60269
+ } catch {
60270
+ return { problem: "not JSON" };
60271
+ }
60272
+ const parsed = schema.safeParse(json);
60273
+ if (parsed.success)
60274
+ return { value: parsed.data };
60120
60275
  return {
60121
- reminderMs: integerSetting(env, log, "LEGION_STALL_REMINDER_MS", DEFAULT_STALL_LIMITS.reminderMs, 0),
60122
- waitingMs: integerSetting(env, log, "LEGION_STALL_WAITING_MS", DEFAULT_STALL_LIMITS.waitingMs, 0),
60123
- resumeMs: integerSetting(env, log, "LEGION_STALL_RESUME_MS", DEFAULT_STALL_LIMITS.resumeMs, 0),
60124
- architectAfter: integerSetting(env, log, "LEGION_STALL_ARCHITECT_AFTER", DEFAULT_STALL_LIMITS.architectAfter, 2),
60125
- callGraceMs: integerSetting(env, log, "LEGION_STALL_CALL_GRACE_MS", DEFAULT_STALL_LIMITS.callGraceMs, 0),
60126
- callBoundMs: integerSetting(env, log, "LEGION_STALL_CALL_BOUND_MS", defaultCallBoundMs(role), 0),
60127
- stepMs: integerSetting(env, log, "LEGION_STALL_STEP_MS", DEFAULT_STALL_LIMITS.stepMs, 0)
60276
+ problem: parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ")
60128
60277
  };
60129
60278
  }
60130
-
60131
- // ../pi-shared/src/claim-first-turn-bound.ts
60132
- var DEFAULT_CLAIM_FIRST_TURN_BOUND_MS = 30000;
60133
- var BOUND_VARIABLE = "LEGION_CLAIM_FIRST_TURN_BOUND_MS";
60134
- function claimFirstTurnBoundMs(env, log) {
60135
- return integerSetting(env, log, BOUND_VARIABLE, DEFAULT_CLAIM_FIRST_TURN_BOUND_MS, 0);
60279
+ var PLUGIN_CONTRACT_HEADER = "Legion-Plugin-Contract";
60280
+ var DAEMON_CONTRACT_HEADER = "Legion-Daemon-Contract";
60281
+ function statedContract(headers) {
60282
+ const stated = headers.get(DAEMON_CONTRACT_HEADER);
60283
+ if (stated === null)
60284
+ return;
60285
+ const contract = Number(stated);
60286
+ return Number.isSafeInteger(contract) && contract > 0 ? contract : undefined;
60287
+ }
60288
+ function createLegionDaemonClient(baseUrl, options) {
60289
+ const endpoint = withoutTrailingSlashes(baseUrl);
60290
+ const pluginContract = options.pluginContract;
60291
+ const fetchFn = options.fetch ?? fetch;
60292
+ const call = async (method, path, body, signal) => {
60293
+ const response = await fetchFn(`${endpoint}${path}`, {
60294
+ method,
60295
+ headers: {
60296
+ [PLUGIN_CONTRACT_HEADER]: String(pluginContract),
60297
+ ...body === undefined ? {} : { "Content-Type": "application/json" }
60298
+ },
60299
+ ...body === undefined ? {} : { body: JSON.stringify(body) },
60300
+ ...signal === undefined ? {} : { signal }
60301
+ });
60302
+ const text = await response.text();
60303
+ const daemonContract = statedContract(response.headers);
60304
+ if (response.ok)
60305
+ return { status: response.status, text, daemonContract };
60306
+ const refusal = parseBody(LegionErrorResponse, text);
60307
+ if ("value" in refusal) {
60308
+ throw new LegionDaemonApiError(method, path, response.status, refusal.value.code, refusal.value.error);
60309
+ }
60310
+ throw new LegionDaemonApiError(method, path, response.status, undefined, `${unreadableBody(text)} is not the daemon's refusal shape (${refusal.problem}). ${contractStanding(pluginContract, daemonContract)}`);
60311
+ };
60312
+ const read = async (method, path, schema, body, signal) => {
60313
+ const { status, text, daemonContract } = await call(method, path, body, signal);
60314
+ const parsed = parseBody(schema, text);
60315
+ if ("problem" in parsed) {
60316
+ throw new LegionDaemonContractError(method, path, status, pluginContract, daemonContract, parsed.problem);
60317
+ }
60318
+ return parsed.value;
60319
+ };
60320
+ const post = (path, request, response, body) => read("POST", path, response, request.parse(body));
60321
+ const acknowledge = async (path, body, signal) => {
60322
+ const { status, text, daemonContract } = await call("POST", path, body, signal);
60323
+ if (status !== 204 || text !== "") {
60324
+ throw new LegionDaemonContractError("POST", path, status, pluginContract, daemonContract, "the route answers 204 with no body");
60325
+ }
60326
+ };
60327
+ return {
60328
+ state: (reading) => read("GET", "/legion/v1/state", LegionStateResponse, undefined, reading?.signal),
60329
+ record: async (issue, reading) => {
60330
+ try {
60331
+ return await read("GET", `/legion/v1/issues/${encodeURIComponent(issue)}/record`, LegionIssueRecordResponse, undefined, reading?.signal);
60332
+ } catch (error) {
60333
+ if (error instanceof LegionDaemonApiError && error.status === 404 && error.code === "RECORD_NOT_FOUND") {
60334
+ return;
60335
+ }
60336
+ throw error;
60337
+ }
60338
+ },
60339
+ health: (reading) => read("GET", "/healthz", LegionHealthResponse, undefined, reading?.signal),
60340
+ daemonContract: async (reading) => (await call("GET", "/healthz", undefined, reading?.signal)).daemonContract,
60341
+ register: (input) => read("POST", "/legion/v1/claims/register", LegionRegisterResponse, input),
60342
+ registerController: (input) => read("POST", "/legion/v1/claims/register", LegionControllerRegisterResponse, input),
60343
+ ready: (input, options) => acknowledge("/legion/v1/claims/ready", input, options?.signal),
60344
+ readyForUpdate: (input) => acknowledge("/legion/v1/claims/ready-for-update", input),
60345
+ exit: (input) => acknowledge("/legion/v1/claims/exit", input),
60346
+ turnOutcome: (input) => post("/legion/v1/claims/turn-outcome", LegionTurnOutcomeRequest, LegionTurnOutcomeResponse, input),
60347
+ activity: (input) => acknowledge("/legion/v1/claims/activity", input),
60348
+ releaseRecords: (input) => post("/legion/v1/claims/release-records", LegionReleaseRecordsRequest, LegionReleaseRecordsResponse, input),
60349
+ grant: (input) => post("/legion/v1/grants", LegionGrantRequest, LegionGrantResponse, input),
60350
+ controllerGrant: (input) => post("/legion/v1/grants", LegionControllerGrantRequest, LegionGrantResponse, input),
60351
+ handoffComplete: (input) => post("/legion/v1/handoff/complete", LegionHandoffCompleteRequest, LegionHandoffCompleteResponse, input),
60352
+ issueStatus: (input) => post("/legion/v1/issues/status", LegionIssueStatusRequest, LegionEmptyResponse, input),
60353
+ freshSession: (input) => post("/legion/v1/claims/fresh-session", LegionClaimRequest, LegionFreshSessionResponse, input),
60354
+ compact: (input) => post("/legion/v1/claims/compact", LegionClaimRequest, LegionCompactResponse, input),
60355
+ projectPause: (input) => post("/legion/v1/project/pause", LegionProjectPauseRequest, LegionProjectPauseResponse, input),
60356
+ projectResume: (input) => post("/legion/v1/project/resume", LegionProjectResumeRequest, LegionProjectResumeResponse, input),
60357
+ gateRegister: (input) => post("/legion/v1/gates/register", LegionGateRegisterRequest, LegionEmptyResponse, input),
60358
+ waveRelease: (input) => post("/legion/v1/waves/release", LegionWaveReleaseRequest, LegionWaveReleaseResponse, input),
60359
+ phaseBackward: (input) => post("/legion/v1/phase/backward", LegionPhaseBackwardRequest, LegionEmptyResponse, input),
60360
+ phaseRetry: (input) => post("/legion/v1/phase/retry", LegionPhaseRetryRequest, LegionEmptyResponse, input),
60361
+ signOff: (input) => post("/legion/v1/signoff", LegionSignOffRequest, LegionEmptyResponse, input),
60362
+ rootClose: (input) => post("/legion/v1/roots/close", LegionRootCloseRequest, LegionEmptyResponse, input),
60363
+ childPark: (input) => post("/legion/v1/children/park", LegionChildRequest, LegionEmptyResponse, input),
60364
+ childRerun: (input) => post("/legion/v1/children/rerun", LegionChildRequest, LegionEmptyResponse, input)
60365
+ };
60136
60366
  }
60137
60367
 
60138
60368
  // ../pi-shared/src/legion-claim-core.ts
@@ -60429,7 +60659,7 @@ function createPhaseReminder(deps) {
60429
60659
  return { reminds: true };
60430
60660
  let record;
60431
60661
  try {
60432
- record = (await withBound(deps.readState, boundMs)).issues[claim.issue];
60662
+ record = await withBound((signal) => deps.readRecord(claim.issue, signal), boundMs);
60433
60663
  } catch (error) {
60434
60664
  deps.log.debug("legion: the daemon did not answer the phase reminder's record check", {
60435
60665
  issue: claim.issue,
@@ -60451,7 +60681,7 @@ function createPhaseReminder(deps) {
60451
60681
  });
60452
60682
  return { reminds: false, record };
60453
60683
  }
60454
- const state = record.workers[claim.role]?.claim.state;
60684
+ const state = record.workers?.[claim.role]?.claim?.state;
60455
60685
  if (state === "failed") {
60456
60686
  deps.log.debug("legion: the daemon has failed this claim; no reminder is sent", {
60457
60687
  issue: claim.issue,
@@ -60848,7 +61078,7 @@ function createPhaseHookEndpoint(deps) {
60848
61078
  armTimer,
60849
61079
  saveEntry: saveRecord,
60850
61080
  claim: deps.claim,
60851
- readState: deps.readState,
61081
+ readRecord: deps.readRecord,
60852
61082
  publisher: () => deps.publish,
60853
61083
  project: configuredValue(deps.env["LEGION_PROJECT"]),
60854
61084
  limits,
@@ -60973,6 +61203,9 @@ function legionPane(env) {
60973
61203
  launcherSaves: configuredValue(env["LEGION_CLAUDE_SESSION_ID"]) !== undefined
60974
61204
  };
60975
61205
  }
61206
+ function paneDaemonClient(daemonUrl) {
61207
+ return createLegionDaemonClient(daemonUrl, { pluginContract: legion.daemonApiVersion });
61208
+ }
60976
61209
  function logLegion(line) {
60977
61210
  process.stderr.write(`[legion] ${line}
60978
61211
  `);
@@ -61168,7 +61401,8 @@ var PHASE_OPS = [
61168
61401
  "read_release_records",
61169
61402
  "handoff_complete",
61170
61403
  "request_backward_move",
61171
- "ready_for_update"
61404
+ "ready_for_update",
61405
+ "read_build"
61172
61406
  ];
61173
61407
  var requiredString = (op, field) => {
61174
61408
  const message = `${op} requires ${field}`;
@@ -61220,7 +61454,8 @@ var PhaseOpArguments = discriminatedUnion("op", [
61220
61454
  }),
61221
61455
  reason: requiredString("request_backward_move", "reason")
61222
61456
  }),
61223
- operation("ready_for_update", { round: requiredString("ready_for_update", "round") })
61457
+ operation("ready_for_update", { round: requiredString("ready_for_update", "round") }),
61458
+ operation("read_build", {})
61224
61459
  ], {
61225
61460
  error: (issue) => issue.code === "invalid_union" ? `op is one of ${PHASE_OPS.join(", ")}` : undefined
61226
61461
  });
@@ -61256,14 +61491,22 @@ function phaseOpParameters(zod) {
61256
61491
  return byField;
61257
61492
  }
61258
61493
  var PHASE_OP_SENTENCES = {
61259
- readRecord: "read_record returns the record of `issue` from the daemon's state, your own issue when you leave `issue` out. " + "A held issue names in `heldFrom` the phase the hold took it out of. A failed claim carries `failure`: the " + "`cause` word for what failed it, the `detail` sentence beside that word, `at`, when it failed, and " + "`attempts`, the four counts it failed with. A todo written on a held root releases the hold and starts " + "that phase again, as the architect's retry_or_escalate with retry does. ",
61494
+ readRecord: "read_record returns the record of `issue` from the daemon's record route for that issue, your own issue when you leave `issue` out. " + "A held issue names in `heldFrom` the phase the hold took it out of. A failed claim carries `failure`: the " + "`cause` word for what failed it, the `detail` sentence beside that word, `at`, when it failed, and " + "`attempts`, the four counts it failed with. A todo written on a held root releases the hold and starts " + "that phase again, as the architect's retry_or_escalate with retry does. ",
61260
61495
  readReleaseRecords: "read_release_records returns this deployment's idle-release records from `since` (an RFC 3339 time) on, read with this session's own claim: " + "every release, resume and hold the daemon recorded, and over them the counts of releases, of the releases among them that suspended no " + "role, of resumes by wake kind and of holds by reason, the pod-hours released, the share of releases woken again within ten minutes, and " + "the median, 90th percentile and maximum seconds from a wake to the woken role's first turn. A wake that a project pause held is " + "counted as `heldByPause` and left out of those seconds, since its wait measures the pause. A release that suspended no role is woken by " + "nothing, so the pod-hours released and the woken share count the releases that suspended a role alone. ",
61261
- requestBackwardMove: "request_backward_move returns an issue to an earlier phase (`to`, `reason`). A phase worker moves its own issue. " + "The architect that owns an issue in accepting moves it, named by `issue`, back to implementing or testing. That move counts a review round. "
61496
+ requestBackwardMove: "request_backward_move returns an issue to an earlier phase (`to`, `reason`). A phase worker moves its own issue. " + "The architect that owns an issue in accepting moves it, named by `issue`, back to implementing or testing. That move counts a review round. ",
61497
+ readBuild: "read_build reports the build this process runs: the plugin package and version the process loaded, and the contract that build speaks. " + "It also reports the contract the daemon states on its answer to the health route. " + "That contract is null where the daemon stated none, where the daemon refused the health route and where no answer reached this process at all, and a note of its own says which. " + "The two numbers can differ, and the answer shows both. " + "Report the version this call answers, never the one at the plugin's path on the image. " + "In a pod, an Oh My Pi role relaunched onto the daemon's contract loads the build that relaunch installed under the role's own state home, " + "and a Claude Code role installs no plugin: it loads its pod image's own claude-envoy. " + "read_build reads no project state. "
61262
61498
  };
61263
61499
  var STALE_ENTRY_INSTRUCTION = "End this turn without completing. The task of the entry the phase is on is owed to this claim, and the daemon sends it by itself. " + "That task is work of its own: do what it asks at the head it names and complete it with a handoff of its own, never this completion's " + "record, commit or verdict";
61264
61500
  function legionToolDescription(host) {
61265
61501
  return "Perform the workflow operation the Legion daemon assigned this role. The daemon advances phases; this tool cannot spawn workers. " + (host.before ?? "") + "handoff_complete (phase workers alone: the daemon refuses an architect's completion, with ACCEPTANCE_IS_SIGN_OFF where nothing else refuses it first, since an architect accepts with sign_off; " + "the daemon accepts a completion only from the role working the issue's current phase, " + "or a role's first completion of the phase it left, which it records and which moves nothing, " + "and the checking role's report on a look of its closed issue's production check) reports this phase complete: `summary` (two sentences for the " + "architect), `verdict` pass|fail from the tester alone on a phase completion (the daemon refuses a verdict from " + "any other role there) and pass|pending|fail on a production check report (pending: production does not carry the merge " + "yet, or carries it with a requirement only the deploy can show still unobserved and a look still to follow). " + "A planning, implementing, testing or reviewing phase ends with a handoff record on the " + "Dispatch issue: write it with `dispatch handoff-write --issue <issue> --phase <plan|implement|test|review> --body-file <file>` before " + "calling. This call reads from Dispatch the newest record of the phase your role works or, once the issue has moved on, of the phase it left, " + "and reports it with `commit`, the head that record's body names " + "(`head`, the 40-character lower-case commit the work it reports was done against); in implementing, the implementer's must be the commit its " + "workspace stands on, `@-`, pushed to `legion/<issue>@origin`, so push the branch first; retro, the merger's completion and a phase you left with no record, or with an implement record naming no head, report the commit the workspace stands on. It " + "refuses, posting nothing, a phase you work with no record, a Dispatch that does not answer, and, in implementing, an implement record naming no head, an " + "implementer's `@-` not yet on `legion/<issue>@origin`, or an implement record whose head is not that pushed `@-`, each naming the remedy. A production check report " + "(the task whose first line is `Production check of <KEY>`, handed once the merge closed the issue to the role the check records) needs no " + "handoff and no commit: it carries its verdict and summary alone. A pending report also names `wake_at`, an RFC 3339 time: when you want the " + "next look. A pass, a fail, and a pending on the check's last look end the check, so none of them carries `wake_at` " + "(CHECK_WAKE_UNEXPECTED), and a pending on any other look is refused without one (CHECK_WAKE_REQUIRED). A report on an issue whose check is " + "closed or never opened is refused (CHECK_NOT_OPEN), and so is one from a role the check does not record (CHECK_ROLE_MISMATCH). " + `The completion that ends the retro carries \`plan_rating\` (${LEGION_PLAN_RATING_LEAST} to ${LEGION_PLAN_RATING_MOST}) and \`plan_reason\`, as ` + "skill://legion-retro says, and the daemon refuses a completion that breaks that skill's rating rule " + "(PLAN_RATING_REQUIRED, PLAN_RATING_UNEXPECTED or PLAN_RATING_INPUT). " + "The daemon refuses " + "HANDOFF_SESSION_MISMATCH (another session wrote the record), HANDOFF_NOT_NEW (the record is the one you named for your previous phase: " + "write this phase's handoff), " + "HANDOFF_STALE_ENTRY (this completion is of a phase entry behind the one your role's phases row names, because the phase was entered " + `again while your turn ran, and nothing was recorded. ${STALE_ENTRY_INSTRUCTION}), the implementer's completion of implementing with no open ` + "pull request on `legion/<issue>` and none recorded " + "merged (HANDOFF_NO_PULL_REQUEST: open it; one naming a closed pull request is the architect's to decide); a refused completion changed " + "nothing, so fix what it names and complete again. " + "ready_for_update answers the daemon's update message on this issue's pod: `round` is the round id that message names, and the " + "daemon takes your answer for that round alone. Push every commit you want kept to the issue branch " + "first. Then let each subagent and each background job that you started finish, or stop it. Commit and push what it made " + "before you answer. The daemon replaces the pod and its disk when the round ends. The round ends at the moment the message " + "names. It can end earlier, once every role has answered, no role is in a turn and each role's last report names no running " + "subagent or background job. No answer delays that moment, and the end of a turn is no answer. If a subagent or a background " + "job finishes after you answer, commit and push what it made. Then call ready_for_update again with the same round. " + "The call ends no phase. The daemon holds your next task until your process comes back on the new pod, in this same session. " + (host.after ?? "") + `What a later phase needs goes in your handoff; a question for another live role goes to its role topic with ${host.envoyPublish}.`;
61266
61502
  }
61503
+ function pluginBuildOf(manifest) {
61504
+ return {
61505
+ name: manifest.name,
61506
+ version: manifest.version,
61507
+ pluginContract: manifest.legion.daemonApiVersion
61508
+ };
61509
+ }
61267
61510
  async function mintClaimGrant(daemon, claim) {
61268
61511
  const { grantId } = await daemon.grant({
61269
61512
  sessionId: claim.sessionID,
@@ -61273,13 +61516,38 @@ async function mintClaimGrant(daemon, claim) {
61273
61516
  });
61274
61517
  return grantId;
61275
61518
  }
61276
- function recordFrom(state, issue) {
61277
- const record = state.issues[issue];
61519
+ async function recordFrom(daemon, issue) {
61520
+ const record = await daemon.record(issue);
61278
61521
  if (record === undefined)
61279
61522
  throw new Error(`The daemon has no record for ${issue}`);
61280
61523
  return record;
61281
61524
  }
61282
61525
  var ROOT_COMPLETION_REFUSAL = "handoff_complete is not available to a root architect session, which runs no phase";
61526
+ var DAEMON_STATED_NO_CONTRACT = "the daemon stated no contract";
61527
+ var DAEMON_REFUSED_ROUTE = "the daemon refused the health route";
61528
+ var DAEMON_DID_NOT_ANSWER = "the daemon did not answer at all";
61529
+ async function statedDaemonContract(daemon) {
61530
+ let stated;
61531
+ try {
61532
+ stated = await daemon.daemonContract();
61533
+ } catch (error) {
61534
+ return {
61535
+ contract: null,
61536
+ note: error instanceof LegionDaemonApiError ? DAEMON_REFUSED_ROUTE : DAEMON_DID_NOT_ANSWER
61537
+ };
61538
+ }
61539
+ return stated === undefined ? { contract: null, note: DAEMON_STATED_NO_CONTRACT } : { contract: stated, note: null };
61540
+ }
61541
+ async function readBuild(runtime) {
61542
+ const stated = await statedDaemonContract(runtime.daemon);
61543
+ return {
61544
+ plugin: runtime.build.name,
61545
+ version: runtime.build.version,
61546
+ pluginContract: runtime.build.pluginContract,
61547
+ daemonContract: stated.contract,
61548
+ daemonContractNote: stated.note
61549
+ };
61550
+ }
61283
61551
  async function executePhaseOp(runtime, input) {
61284
61552
  const { daemon, claim } = runtime;
61285
61553
  const parsed = PhaseOpArguments.safeParse(input);
@@ -61298,7 +61566,7 @@ async function executePhaseOp(runtime, input) {
61298
61566
  case "read_record": {
61299
61567
  const named = args.issue?.trim() ?? "";
61300
61568
  const issue = named !== "" ? named : claim.issue;
61301
- return { record: recordFrom(await daemon.state(), issue) };
61569
+ return { record: await recordFrom(daemon, issue) };
61302
61570
  }
61303
61571
  case "read_release_records":
61304
61572
  return releaseRecords(runtime, args.since);
@@ -61353,6 +61621,8 @@ async function executePhaseOp(runtime, input) {
61353
61621
  note: "The daemon has your ready_for_update signal. The signal reports no branch head, " + "because the branch-head lookup failed. The daemon checks no head, so your signal " + "counts without one. Repair what the lookup's message names before your next jj " + `command. The lookup said: ${failure}`
61354
61622
  };
61355
61623
  }
61624
+ case "read_build":
61625
+ return readBuild(runtime);
61356
61626
  }
61357
61627
  }
61358
61628
  var WOKEN_SOON_MS = 10 * 60 * 1000;
@@ -61452,7 +61722,7 @@ async function releaseRecords(runtime, since) {
61452
61722
  }
61453
61723
  async function completeHandoff(runtime, args, rating) {
61454
61724
  const { daemon, claim } = runtime;
61455
- const record = recordFrom(await daemon.state(), claim.issue);
61725
+ const record = await recordFrom(daemon, claim.issue);
61456
61726
  if (record.phase === "done") {
61457
61727
  const check = record.check;
61458
61728
  if (check !== undefined) {
@@ -61495,6 +61765,7 @@ async function completeHandoff(runtime, args, rating) {
61495
61765
  }
61496
61766
 
61497
61767
  // src/legion-tool.ts
61768
+ var BUILD = pluginBuildOf(package_default);
61498
61769
  var LEGION_TOOL_NAME = "legion";
61499
61770
  function legionToolDefinition() {
61500
61771
  return {
@@ -61502,7 +61773,7 @@ function legionToolDefinition() {
61502
61773
  description: legionToolDescription({
61503
61774
  envoyPublish: "mcp__legion__envoy_publish",
61504
61775
  before: PHASE_OP_SENTENCES.readRecord + PHASE_OP_SENTENCES.readReleaseRecords,
61505
- after: PHASE_OP_SENTENCES.requestBackwardMove
61776
+ after: PHASE_OP_SENTENCES.requestBackwardMove + PHASE_OP_SENTENCES.readBuild
61506
61777
  }),
61507
61778
  inputSchema: toJSONSchema(object({ op: _enum2(PHASE_OPS), ...phaseOpParameters(exports_external) }))
61508
61779
  };
@@ -61515,6 +61786,7 @@ async function executeLegionTool(runtime, input, signal) {
61515
61786
  return executePhaseOp({
61516
61787
  daemon: runtime.daemon,
61517
61788
  claim,
61789
+ build: BUILD,
61518
61790
  handoffReport: runtime.handoffReport,
61519
61791
  branchHead: runtime.branchHead,
61520
61792
  ...signal === undefined ? {} : { restart: { signal } }
@@ -63984,7 +64256,7 @@ async function runEnvoyChannelServer() {
63984
64256
  let runtime;
63985
64257
  let starting = "it reads its settings";
63986
64258
  let claim;
63987
- const daemon = pane === undefined ? undefined : createLegionDaemonClient(pane.daemonUrl);
64259
+ const daemon = pane === undefined ? undefined : paneDaemonClient(pane.daemonUrl);
63988
64260
  const phaseLog = paneReminderLog(logLegion);
63989
64261
  const claimBooted = Promise.withResolvers();
63990
64262
  let reportFirstTurn;
@@ -63993,7 +64265,7 @@ async function runEnvoyChannelServer() {
63993
64265
  claim: () => claim?.capability(),
63994
64266
  booted: claimBooted.promise,
63995
64267
  firstTurnStarted: () => reportFirstTurn?.(),
63996
- readState: (signal) => daemon.state({ signal }),
64268
+ readRecord: (issue, signal) => daemon.record(issue, { signal }),
63997
64269
  reportActivity: (input) => daemon.activity(input),
63998
64270
  inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
63999
64271
  publish: client.publish,