@sjawhar/claude-envoy 5.23.7 → 5.25.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.
@@ -36872,6 +36872,8 @@ var ASK_OPTIONS_CONTRACT = "Options carry the genuinely different approaches. Ea
36872
36872
  var ASK_IS_FOR_A_PERSON = "An ask is a question for a person, never a request to another agent. Ask an agent by envoy_send or a comment on the issue.";
36873
36873
  var ASK_WAITS_ON_THE_ASSIGNEE = "An ask waits on its asked-of person, else the issue's assignee, else the project's default assignee; no agent hands one on.";
36874
36874
  var HUMAN_AGREED_TO_DOCUMENT = "the human has agreed to every point in the document";
36875
+ var DOCUMENT_OWNER_RULE = "Exactly one of issue and project is required; with project, artifact names the document.";
36876
+ var NAMED_DOCUMENT_OWNER_RULE = "Exactly one of issue and project is required; artifact or ref must name the document.";
36875
36877
  function documentOwnerValidation(requireArtifact, alwaysRequireArtifact = false) {
36876
36878
  return {
36877
36879
  check: (value) => {
@@ -36882,15 +36884,21 @@ function documentOwnerValidation(requireArtifact, alwaysRequireArtifact = false)
36882
36884
  const hasRef = typeof input.ref === "string";
36883
36885
  return (hasIssue !== hasProject || !hasIssue && !hasProject && hasRef) && (!hasProject || !requireArtifact || hasArtifact) && (!alwaysRequireArtifact || hasArtifact || hasRef);
36884
36886
  },
36885
- message: alwaysRequireArtifact ? "Exactly one of issue and project is required; artifact or ref must name the document." : "Exactly one of issue and project is required; with project, artifact names the document."
36887
+ message: alwaysRequireArtifact ? NAMED_DOCUMENT_OWNER_RULE : DOCUMENT_OWNER_RULE
36886
36888
  };
36887
36889
  }
36888
36890
  var ARTIFACT_SOURCE_RULE = "Give at most one of path and content. A call with neither makes an empty document under the name, which a person or an agent writes in afterwards with dispatch doc-edit.";
36889
- var ARTIFACT_OWNER_AND_SOURCE_RULE = `${ARTIFACT_SOURCE_RULE} Exactly one of issue and project is required; with project, artifact names the document.`;
36891
+ var ARTIFACT_OWNER_AND_SOURCE_RULE = `${ARTIFACT_SOURCE_RULE} ${DOCUMENT_OWNER_RULE}`;
36890
36892
  function brokenParts(parts) {
36891
36893
  const broken = parts.filter(([kept]) => !kept).map(([, message]) => message);
36892
36894
  return broken.length === 0 ? undefined : broken.join(" ");
36893
36895
  }
36896
+ function withoutOwnerRule(refusal) {
36897
+ const rule = DISPATCH_OWNER_RULES.find((owner) => refusal === owner || refusal.startsWith(`${owner} `));
36898
+ if (rule === undefined)
36899
+ return refusal;
36900
+ return refusal === rule ? undefined : refusal.slice(rule.length + 1);
36901
+ }
36894
36902
  var CONTENT_IS_MARKDOWN = "content is stored as a Markdown document, which rewrites other text (a JSONL file's lines come back joined into one paragraph)";
36895
36903
  var DOCUMENT_IS_MARKDOWN = "a document holds Markdown, which rewrites other text (a JSONL file's lines come back joined into one paragraph)";
36896
36904
  var PATH_KEEPS_BYTES = "path (--path <file>), which stores a file whose path does not end in .md or .markdown as its bytes, unchanged";
@@ -36934,18 +36942,13 @@ function pathKeepsBytesOf(name) {
36934
36942
  var artifactOwner = documentOwnerValidation(false);
36935
36943
  function artifactProblem(value) {
36936
36944
  const input = value;
36937
- const ownerOrSourceProblem = brokenParts([
36945
+ const extension = typeof input.path === "string" || typeof input.name !== "string" ? undefined : NAME_EXTENSION.exec(input.name.trim())?.[1];
36946
+ const nameProblem = extension === undefined || MARKDOWN_EXTENSION.test(extension) ? undefined : `${DOCUMENT_IS_MARKDOWN}, and ${JSON.stringify(input.name)} is not a Markdown name. Upload the file under the same name with ${PATH_KEEPS_BYTES}; a document takes a name ending in .md or .markdown or with no extension.`;
36947
+ return brokenParts([
36938
36948
  [artifactOwner.check(value), artifactOwner.message],
36939
- [typeof input.path !== "string" || typeof input.content !== "string", ARTIFACT_SOURCE_RULE]
36949
+ [typeof input.path !== "string" || typeof input.content !== "string", ARTIFACT_SOURCE_RULE],
36950
+ [nameProblem === undefined, nameProblem ?? ""]
36940
36951
  ]);
36941
- if (ownerOrSourceProblem !== undefined)
36942
- return ownerOrSourceProblem;
36943
- if (typeof input.path === "string" || typeof input.name !== "string")
36944
- return;
36945
- const extension = NAME_EXTENSION.exec(input.name.trim())?.[1];
36946
- if (extension === undefined || MARKDOWN_EXTENSION.test(extension))
36947
- return;
36948
- return `${DOCUMENT_IS_MARKDOWN}, and ${JSON.stringify(input.name)} is not a Markdown name. Upload the file under the same name with ${PATH_KEEPS_BYTES}; a document takes a name ending in .md or .markdown or with no extension.`;
36949
36952
  }
36950
36953
  var documentEditOwner = documentOwnerValidation(true);
36951
36954
  var PRECONDITION_RULE = "A precondition selects exactly one of document or blocks.";
@@ -37040,34 +37043,100 @@ var ISSUE_UPDATE_FIELDS_RULE = "Issue update requires at least one field besides
37040
37043
  var ISSUE_UPDATE_DONE_RULE = "status done requires reason, a non-empty note saying why the issue is closing, posted on the issue before it closes so the close carries its note";
37041
37044
  var ISSUE_UPDATE_REASON_RULE = "reason goes only with status done";
37042
37045
  var ISSUE_UPDATE_LABELS_RULE = "labels_add goes without labels";
37043
- var ISSUE_UPDATE_RULE = `${ISSUE_UPDATE_FIELDS_RULE} ${ISSUE_UPDATE_DONE_RULE}; ${ISSUE_UPDATE_REASON_RULE}; ${ISSUE_UPDATE_LABELS_RULE}.`;
37044
- function issueUpdateProblem(value) {
37045
- const input = value;
37046
+ var ISSUE_UPDATE_LABELS_REFUSAL = `${ISSUE_UPDATE_LABELS_RULE}: labels replaces every label the issue holds and labels_add adds to them, so name the labels to add in labels_add alone, or the whole set in labels alone.`;
37047
+ var ISSUE_STATUS_OPTIONS = [
37048
+ "include_children",
37049
+ "unlink_children",
37050
+ "include_parent"
37051
+ ];
37052
+ function issueStatusOptionsOf(input) {
37053
+ return ISSUE_STATUS_OPTIONS.filter((option) => input[option] === true);
37054
+ }
37055
+ var ISSUE_UPDATE_PATCH_FIELDS = [
37056
+ "title",
37057
+ "labels",
37058
+ "labels_add",
37059
+ "priority",
37060
+ "assignee",
37061
+ "external_links",
37062
+ "route",
37063
+ "parent",
37064
+ "blocked_by",
37065
+ "advances",
37066
+ "advances_revision",
37067
+ "components",
37068
+ "repo",
37069
+ "before",
37070
+ "after"
37071
+ ];
37072
+ var ISSUE_UPDATE_OPTIONS_RULE = "include_children, unlink_children and include_parent go with status, and with reason when the status is done, and with no other field. include_children does not go with unlink_children, or with status done.";
37073
+ var ISSUE_UPDATE_RULE = `${ISSUE_UPDATE_FIELDS_RULE} ${ISSUE_UPDATE_DONE_RULE}; ${ISSUE_UPDATE_REASON_RULE}; ${ISSUE_UPDATE_LABELS_RULE}. ${ISSUE_UPDATE_OPTIONS_RULE}`;
37074
+ function issueStatusOptionsProblem(input) {
37075
+ const options = issueStatusOptionsOf(input);
37076
+ if (options.length === 0)
37077
+ return;
37078
+ const named = options.join(", ").replace(/, ([^,]*)$/, " and $1");
37079
+ const others = ISSUE_UPDATE_PATCH_FIELDS.filter((field) => input[field] !== undefined);
37080
+ return brokenParts([
37081
+ [
37082
+ !(input["include_children"] === true && input["unlink_children"] === true),
37083
+ "include_children does not go with unlink_children. The open children move with the issue or leave it, so name one of the two."
37084
+ ],
37085
+ [
37086
+ !(input["include_children"] === true && input["status"] === "done"),
37087
+ "include_children does not go with status done. Only a person who is signed in at a browser can close the open issues under an issue together with it, and this call presents a token. That person does it on the issue's page in Dispatch: Close issue, then Move them with it."
37088
+ ],
37089
+ [
37090
+ typeof input["status"] === "string",
37091
+ `status is required with ${named}. Add status, or drop ${named}.`
37092
+ ],
37093
+ [
37094
+ others.length === 0,
37095
+ `With ${named}, give status alone, and reason when the status is done. This call also names ${others.join(", ")}. Send those fields in a call of their own.`
37096
+ ]
37097
+ ]);
37098
+ }
37099
+ function issueReasonProblem(input) {
37046
37100
  if (input.status === "done") {
37047
- if (typeof input.reason !== "string" || input.reason.trim() === "") {
37048
- return `${ISSUE_UPDATE_DONE_RULE}.`;
37049
- }
37050
- } else if (input.reason !== undefined) {
37051
- const status = typeof input.status === "string" ? `status ${input.status}` : "an update without status done";
37052
- return `${ISSUE_UPDATE_REASON_RULE}: it is the note posted on the issue as it closes, and ${status} closes nothing. Drop reason, or set status done to close the issue.`;
37053
- }
37054
- if (input.labels !== undefined && input.labels_add !== undefined) {
37055
- return `${ISSUE_UPDATE_LABELS_RULE}: labels replaces every label the issue holds and labels_add adds to them, so name the labels to add in labels_add alone, or the whole set in labels alone.`;
37101
+ return typeof input.reason !== "string" || input.reason.trim() === "" ? `${ISSUE_UPDATE_DONE_RULE}.` : undefined;
37056
37102
  }
37103
+ if (input.reason === undefined)
37104
+ return;
37105
+ const status = typeof input.status === "string" ? `status ${input.status}` : "an update without status done";
37106
+ return `${ISSUE_UPDATE_REASON_RULE}: it is the note posted on the issue as it closes, and ${status} closes nothing. Drop reason, or set status done to close the issue.`;
37107
+ }
37108
+ function issueUpdateProblem(value) {
37109
+ const input = value;
37110
+ const reasonProblem = issueReasonProblem(input);
37111
+ const optionsProblem = issueStatusOptionsProblem(value);
37112
+ const broken = brokenParts([
37113
+ [reasonProblem === undefined, reasonProblem ?? ""],
37114
+ [input.labels === undefined || input.labels_add === undefined, ISSUE_UPDATE_LABELS_REFUSAL],
37115
+ [optionsProblem === undefined, optionsProblem ?? ""]
37116
+ ]);
37117
+ if (broken !== undefined)
37118
+ return broken;
37057
37119
  const changesAField = typeof input.status === "string" || typeof input.title === "string" || Array.isArray(input.labels) || Array.isArray(input.labels_add) || typeof input.priority === "number" || input.priority === null || typeof input.assignee === "string" || input.assignee === null || Array.isArray(input.external_links) || typeof input.route === "string" || typeof input.parent === "string" || Array.isArray(input.blocked_by) || Array.isArray(input.advances) || typeof input.components === "object" && input.components !== null || typeof input.repo === "string" || typeof input.before === "string" || typeof input.after === "string";
37058
37120
  return changesAField ? undefined : ISSUE_UPDATE_FIELDS_RULE;
37059
37121
  }
37122
+ var MESSAGE_OWNER_RULE = "issue is required unless in_reply_to names a message delivered to this session, which is the one message with no issue.";
37060
37123
  var messageValidation = {
37061
37124
  check: (value) => {
37062
37125
  const input = value;
37063
37126
  return typeof input.issue === "string" || typeof input.in_reply_to === "string";
37064
37127
  },
37065
- message: "issue is required unless in_reply_to names a message delivered to this session, which is the one message with no issue."
37128
+ message: MESSAGE_OWNER_RULE
37066
37129
  };
37067
37130
  var readOwner = documentOwnerValidation(false);
37068
37131
  var READ_OWNER_RULE = "Exactly one of issue and project is required; project alone lists its documents, and with artifact names one.";
37069
37132
  var READ_MESSAGE_RULE = "message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it.";
37070
37133
  var READ_HISTORY_RULE = "history reads each body an edit or the delete of one post replaced, so it needs a ref naming one comment or one issue message: message stands alone and names a whole conversation, which keeps no history of its own.";
37134
+ var DISPATCH_OWNER_RULES = [
37135
+ DOCUMENT_OWNER_RULE,
37136
+ NAMED_DOCUMENT_OWNER_RULE,
37137
+ READ_OWNER_RULE,
37138
+ MESSAGE_OWNER_RULE
37139
+ ];
37071
37140
  function readProblem(value) {
37072
37141
  const input = value;
37073
37142
  const historyKept = input.history !== true || typeof input.ref === "string";
@@ -37258,11 +37327,14 @@ var dispatchToolSpecs = [
37258
37327
  priority: 1,
37259
37328
  before: "DSP-2"
37260
37329
  },
37261
- description: "Update an existing issue: move its lifecycle status, retitle it, add labels to it or " + "replace its labels, set " + "its priority, set or clear its assignee, link a URL (the pull request that delivers it, a " + "run, a document), set its " + "route, set or clear its parent, replace the issues it is blocked by, replace the " + "priorities it advances, attach it to " + "architecture components, set the repository it targets, or move it on its project's " + "board. Status is one of " + `${ISSUE_STATUSES.join(", ")}; outside Legion, move it yourself as the work advances; inside ` + "Legion the daemon moves it. labels_add adds labels and keeps every label the issue holds; " + "labels replaces the whole set, so a label it does not name is removed, and the two never " + "go together. A non-empty external_links is " + "merged into the issue's existing links by URL, so linking the pull request you just opened " + "keeps every earlier link; an empty external_links removes every link instead. components " + "replaces the issue's own attachment. Closing an issue " + "(status done) requires reason, the note that says why: it is posted on the issue as a " + "message, then the issue closes, so the close carries its note; closing an issue that is " + "already closed is refused (ISSUE_CLOSED) before anything is posted. Reason goes only " + "with status done. Closing an issue withdraws every open ask " + "it holds (resolution kind withdrawn, naming the closer), and reopening it brings exactly " + "those asks back. " + "A closed issue still takes messages and comments, though not asks or artifacts; of this " + "tool's fields it takes only a board move " + "(before, after), components, " + "a reopening status (any status but done), and an external_links write that adds no new " + "link (so a link can move to the issue that replaced it); everything else, priority " + "included, waits for the reopen. " + "priority is yours to set and a human overrides it. assignee is the person who answers " + "this issue's asks, and every ask on it waits on them until a person hands that ask on. " + "Passing null unassigns the issue, and every ask on it then waits on the project's default " + "assignee: a question reaches the person it was handed to, else the issue's assignee, else " + "the project's default assignee, so every question reaches a person. " + "Set the assignee when a person said who owns the work, as you " + "file the issue or hand it over. before and after move the issue on " + "its project's board: before puts it above that issue, after below, and both together " + "land it between them. A project's board order is one agent's to keep; in a Legion " + "deployment that is the controller. Never reassign an issue a person holds to get a " + "faster answer: who holds it is their call. At least one " + `field besides issue is required. ${ISSUE_REFERENCE}`,
37330
+ description: "Update an existing issue: move its lifecycle status, retitle it, add labels to it or " + "replace its labels, set " + "its priority, set or clear its assignee, link a URL (the pull request that delivers it, a " + "run, a document), set its " + "route, set or clear its parent, replace the issues it is blocked by, replace the " + "priorities it advances, attach it to " + "architecture components, set the repository it targets, or move it on its project's " + "board. Status is one of " + `${ISSUE_STATUSES.join(", ")}; outside Legion, move it yourself as the work advances; inside ` + "Legion the daemon moves it. labels_add adds labels and keeps every label the issue holds; " + "labels replaces the whole set, so a label it does not name is removed, and the two never " + "go together. A non-empty external_links is " + "merged into the issue's existing links by URL, so linking the pull request you just opened " + "keeps every earlier link; an empty external_links removes every link instead. components " + "replaces the issue's own attachment. Closing an issue " + "(status done) requires reason, the note that says why: it is posted on the issue as a " + "message, then the issue closes, so the close carries its note; closing an issue that is " + "already closed is refused (ISSUE_CLOSED) before anything is posted. Reason goes only " + "with status done. Closing an issue withdraws every open ask " + "it holds (resolution kind withdrawn, naming the closer), and reopening it brings exactly " + "those asks back. " + "Dispatch puts the statuses in three groups: not started (triage, icebox, backlog), in work " + "(todo, in_progress, testing, needs_review, retro) and done. A parent is done only when each " + "child is done, and while a child is in work its parent is in work. Where Dispatch keeps " + "this rule, it refuses a status or parent change that breaks it with 409 " + "PARENT_STATUS_CONFLICT, which names each issue that holds it. include_children, " + "unlink_children and include_parent tell Dispatch what to do with those issues. Each goes " + "with status alone, and with reason when the status is done. include_children does not go " + "with done: only a person signed in at a browser closes the open issues under an issue " + "together with it, on the issue's page. " + "A closed issue still takes messages and comments, though not asks or artifacts; of this " + "tool's fields it takes only a board move " + "(before, after), components, " + "a reopening status (any status but done), and an external_links write that adds no new " + "link (so a link can move to the issue that replaced it); everything else, priority " + "included, waits for the reopen. " + "priority is yours to set and a human overrides it. assignee is the person who answers " + "this issue's asks, and every ask on it waits on them until a person hands that ask on. " + "Passing null unassigns the issue, and every ask on it then waits on the project's default " + "assignee: a question reaches the person it was handed to, else the issue's assignee, else " + "the project's default assignee, so every question reaches a person. " + "Set the assignee when a person said who owns the work, as you " + "file the issue or hand it over. before and after move the issue on " + "its project's board: before puts it above that issue, after below, and both together " + "land it between them. A project's board order is one agent's to keep; in a Legion " + "deployment that is the controller. Never reassign an issue a person holds to get a " + "faster answer: who holds it is their call. At least one " + `field besides issue is required. ${ISSUE_REFERENCE}`,
37262
37331
  arguments: (z) => ({
37263
37332
  issue: z.string().describe(ISSUE_REFERENCE),
37264
37333
  status: z.enum(ISSUE_STATUSES).describe("New lifecycle status.").optional(),
37265
37334
  reason: z.string().describe(`Required with status done, and only with it: why the issue is closing. Posted on the issue as a message before it closes. ${BODY_BLOCK_RULE}`).optional(),
37335
+ include_children: z.boolean().describe("With status, also write that status on each open issue under this issue, at any depth, whose status is in another group. Not with status done, which this tool refuses before anything is sent: only a person who is signed in at a browser can close the open issues under an issue together with it, on the issue's page in Dispatch (Close issue, then Move them with it).").optional(),
37336
+ unlink_children: z.boolean().describe("With status, also remove each open child from this issue, so that it has no parent. Each child keeps its status, and a done child stays.").optional(),
37337
+ include_parent: z.boolean().describe("With status, also move each issue above this issue that is not in work to in_progress, a done one included.").optional(),
37266
37338
  title: z.string({ min: 1, max: ISSUE_TITLE_MAX }).describe("Replacement title, at most 1,000 characters.").optional(),
37267
37339
  labels: z.array(z.string({ min: 1, max: ISSUE_LABEL_MAX }), { max: MAX_ISSUE_LABELS }).describe(`Replacement label set, at most ${MAX_ISSUE_LABELS} labels of up to ${ISSUE_LABEL_MAX} characters; replaces every existing label, so a label it does not name is removed. To add labels and keep the others, use labels_add. Not with labels_add.`).optional(),
37268
37340
  labels_add: z.array(z.string({ min: 1, max: ISSUE_LABEL_MAX }), { max: MAX_ISSUE_LABELS }).describe(`Labels to add, at most ${MAX_ISSUE_LABELS} of up to ${ISSUE_LABEL_MAX} characters: each is added to the labels the issue holds when the write lands, and every label it holds stays; the issue holds at most ${MAX_ISSUE_LABELS} in all. Not with labels.`).optional(),
@@ -37716,7 +37788,7 @@ var dispatchToolSpecs = [
37716
37788
  {
37717
37789
  name: "dispatch_issues",
37718
37790
  example: { project: "PROJ", limit: 250, offset: 250 },
37719
- description: "List a project's issues for a roadmap or backlog pass: every issue in one project, each carrying " + "its status, priority, parent, labels, open-ask count, progress (its spec's task-list items and " + "its direct children, each done of total, as `tasks 3/7 \xB7 children 2/5`, each only when it has " + "any), and route with whether it reaches anyone, " + "so you can see backlog shape without opening every issue. Optionally filter by status, parent, " + "label, priority, route status, or how recently it changed; priority takes one or more of 0-3 " + "(P0-P3) and null for an issue with no priority, so an owner's P0/P1 audit is priority [0, 1]. " + 'route_status "no_holder" lists every open issue whose route names a role nobody holds or a ' + "session that is not running, as of the server's copy of the listener's session list, at " + "most 5 s old, whatever its priority. A restarting " + "session is absent for minutes, so an issue is unowned only when a read ten minutes later agrees. " + "Do not use it to search by keyword or phrase; dispatch search remains the keyword surface. " + "Dispatch pages the list: limit sets the page size (default " + `${DEFAULT_ISSUE_PAGE_LIMIT}, max ${MAX_ISSUE_PAGE_LIMIT}) and offset selects where it starts ` + "(default 0), and the answer names how many issues match, so repeat with the next offset to " + "walk every matching issue. A walk is exact only while the list does not change: an issue " + "that enters or leaves what the filters match, or whose status or rank changes, between two " + "pages shifts rows across a page boundary, so one issue can come back twice and another never. " + "all takes the whole filtered list in one read instead, for a caller that must not miss or " + "repeat a row while other writers change the list, and especially for one whose own writes " + "move issues out of what it filtered on.",
37791
+ description: "List a project's issues for a roadmap or backlog pass: every issue in one project, each carrying " + "its status, priority, parent, labels, open-ask count, progress (its spec's task-list items and " + "its direct children, each done of total, as `tasks 3/7 \xB7 children 2/5`, each only when it has " + "any), and route with whether it reaches anyone, " + "so you can see backlog shape without opening every issue. Optionally filter by status, parent, " + "label, priority, route status, or how recently it changed; priority takes one or more of 0-3 " + "(P0-P3) and null for an issue with no priority, so an owner's P0/P1 audit is priority [0, 1]. " + 'route_status "no_holder" lists every open issue whose route names a role nobody holds or a ' + "session that is not running, as of the server's copy of the listener's session list, at " + "most 5 s old, whatever its priority. A restarting " + "session is absent for minutes, so an issue is unowned only when a read ten minutes later agrees. " + "Do not use it to search by keyword or phrase; dispatch search remains the keyword surface. " + "Dispatch pages the list: limit sets the page size (default " + `${DEFAULT_ISSUE_PAGE_LIMIT}, max ${MAX_ISSUE_PAGE_LIMIT}) and offset selects where it starts ` + "(default 0), and the answer names how many issues match, so repeat with the next offset to " + "walk every matching issue. A walk is exact only while the list does not change: an issue " + "that enters or leaves what the filters match, or whose status or rank changes, between two " + "pages shifts rows across a page boundary, so one issue can come back twice and another never. " + "all takes the whole filtered list in one read instead, for a caller that must not miss or " + "repeat a row while other writers change the list, and especially for one whose own writes " + "move issues out of what it filtered on. json prints the listing as one JSON object, for a " + "program such as jq to read.",
37720
37792
  arguments: (z) => ({
37721
37793
  project: z.string().describe("Project key to list issues from."),
37722
37794
  status: z.enum(ISSUE_STATUSES).describe("Optional lifecycle status filter.").optional(),
@@ -37727,7 +37799,8 @@ var dispatchToolSpecs = [
37727
37799
  route_status: z.enum(ISSUE_ROUTE_STATUSES).describe("Optional: only open issues whose route is in this state. live: a running session holds " + "the role or is the routed session. holder_unresponsive: that session has missed its " + "heartbeats without ending, so the route still reaches it and its messages wait. " + "no_holder: nobody running holds the role, or the session is gone, right now. " + "unknown: the Envoy listener did not answer.").optional(),
37728
37800
  limit: z.number({ int: true, min: 1, max: MAX_ISSUE_PAGE_LIMIT }).describe(`Maximum rows, 1-${MAX_ISSUE_PAGE_LIMIT}; default ${DEFAULT_ISSUE_PAGE_LIMIT}.`).optional(),
37729
37801
  offset: z.number({ int: true, min: 0 }).describe("Rows to skip before the page; nonnegative integer; default 0.").optional(),
37730
- all: z.boolean().describe("Take every matching issue in one unpaged read, so no row is missed or repeated while " + "the list changes. Refused with limit or offset.").optional()
37802
+ all: z.boolean().describe("Take every matching issue in one unpaged read, so no row is missed or repeated while " + "the list changes. Refused with limit or offset.").optional(),
37803
+ json: z.boolean().describe("Print the listing as one JSON object and nothing else: {issues, total, offset, limit}, " + "each issue with its status, parent and labels. The dispatch command prints it whole, " + "also on a host that cuts long output.").optional()
37731
37804
  })
37732
37805
  },
37733
37806
  {
@@ -40098,6 +40171,9 @@ function errorClass(error) {
40098
40171
  return `${ERROR_NAME.test(error.name) ? error.name : "Error"} (message withheld)`;
40099
40172
  }
40100
40173
 
40174
+ // ../cipher-client/src/device-login.ts
40175
+ import { generateKeyPairSync as generateKeyPairSync2, randomUUID as randomUUID4 } from "crypto";
40176
+
40101
40177
  // ../contracts/src/trailing-slash.ts
40102
40178
  function withoutTrailingSlashes(url) {
40103
40179
  let end = url.length;
@@ -40106,762 +40182,188 @@ function withoutTrailingSlashes(url) {
40106
40182
  return url.slice(0, end);
40107
40183
  }
40108
40184
 
40109
- // ../envoy-client/src/envoy-config.ts
40110
- import {
40111
- chmodSync,
40112
- closeSync,
40113
- existsSync,
40114
- lstatSync,
40115
- mkdtempSync,
40116
- openSync,
40117
- readFileSync as readFileSync2,
40118
- readlinkSync,
40119
- rmSync,
40120
- statSync
40121
- } from "fs";
40122
- import { homedir, tmpdir } from "os";
40123
- import * as path from "path";
40124
-
40125
- // ../envoy-client/src/errors.ts
40126
- function dispatchCode(error) {
40127
- if (!("fromDispatch" in error) || !("code" in error))
40128
- return;
40129
- const code = error.code;
40130
- return typeof code === "string" && code !== "" ? code : undefined;
40131
- }
40132
- function messageFor(error) {
40133
- if (!(error instanceof Error))
40134
- return scrub(String(error));
40135
- const code = dispatchCode(error);
40136
- return scrub(code === undefined || error.message.startsWith(code) ? error.message : `${code}: ${error.message}`);
40137
- }
40138
- function hasErrnoCode(error, code) {
40139
- return error instanceof Error && "code" in error && error.code === code;
40140
- }
40141
- var NOT_CONNECTED = new Set(["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH"]);
40142
- function reachedNothing(error) {
40143
- if (!(error instanceof Error))
40144
- return false;
40145
- const { code, syscall } = error;
40146
- return syscall === "getaddrinfo" || typeof code === "string" && NOT_CONNECTED.has(code);
40147
- }
40148
-
40149
- class LoggableError extends Error {
40150
- constructor(message) {
40151
- super(message);
40152
- }
40153
- }
40154
- var SERVER_REFUSALS = [
40155
- "Authorization Violation",
40156
- "User Authentication Expired",
40157
- "Account Authentication Expired",
40158
- "Authentication Timeout"
40159
- ];
40160
- var SERVER_ERROR_CODES = {
40161
- AUTHORIZATION_VIOLATION: true,
40162
- AUTHENTICATION_EXPIRED: true,
40163
- AUTHENTICATION_TIMEOUT: true,
40164
- ACCOUNT_EXPIRED: true,
40165
- PERMISSIONS_VIOLATION: true,
40166
- NATS_PROTOCOL_ERR: true
40167
- };
40168
- function serverText(code, text) {
40169
- const said = text.trim().replace(/^'(.*)'$/s, "$1").trim().toLowerCase();
40170
- const refusal = SERVER_REFUSALS.find((fixed) => fixed.toLowerCase() === said);
40171
- if (refusal !== undefined)
40172
- return refusal;
40173
- return code === "PERMISSIONS_VIOLATION" ? "the server refused a permission (its text is withheld)" : "the server refused the connection (its text is withheld)";
40174
- }
40175
- function natsFailureReason(error) {
40176
- if (error instanceof LoggableError)
40177
- return scrub(error.message);
40178
- if (error instanceof Error && error.name === "NatsError") {
40179
- const { code } = error;
40180
- if (typeof code === "string" && code !== "")
40181
- return SERVER_ERROR_CODES[code] === true ? serverText(code, error.message) : code;
40185
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
40186
+ var encoder2 = new TextEncoder;
40187
+ var decoder = new TextDecoder;
40188
+ var strictDecoder = new TextDecoder("utf-8", { fatal: true });
40189
+ var MAX_INT32 = 2 ** 32;
40190
+ function concat(...buffers) {
40191
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
40192
+ const buf = new Uint8Array(size);
40193
+ let i = 0;
40194
+ for (const buffer of buffers) {
40195
+ buf.set(buffer, i);
40196
+ i += buffer.length;
40182
40197
  }
40183
- return errorClass(error);
40198
+ return buf;
40184
40199
  }
40185
-
40186
- // ../envoy-client/src/json-position.ts
40187
- function jsonErrorPosition(text) {
40188
- let at = 0;
40189
- const fail = () => {
40190
- throw new RangeError("not JSON");
40191
- };
40192
- const space = () => {
40193
- while (at < text.length && `
40194
- \r`.includes(text.charAt(at)))
40195
- at += 1;
40196
- };
40197
- const expect = (char) => {
40198
- if (text.charAt(at) !== char)
40199
- fail();
40200
- at += 1;
40201
- };
40202
- const string = () => {
40203
- expect('"');
40204
- while (at < text.length) {
40205
- const char = text.charAt(at);
40206
- if (char === '"') {
40207
- at += 1;
40208
- return;
40209
- }
40210
- if (char < " ")
40211
- fail();
40212
- at += char === "\\" ? 2 : 1;
40213
- }
40214
- fail();
40215
- };
40216
- const value = () => {
40217
- space();
40218
- const char = text.charAt(at);
40219
- if (char === "{" || char === "[") {
40220
- const close = char === "{" ? "}" : "]";
40221
- at += 1;
40222
- space();
40223
- if (text.charAt(at) === close) {
40224
- at += 1;
40225
- return;
40226
- }
40227
- for (;; ) {
40228
- if (close === "}") {
40229
- space();
40230
- string();
40231
- space();
40232
- expect(":");
40233
- }
40234
- value();
40235
- space();
40236
- if (text.charAt(at) === ",") {
40237
- at += 1;
40238
- continue;
40239
- }
40240
- expect(close);
40241
- return;
40242
- }
40243
- }
40244
- if (char === '"') {
40245
- string();
40246
- return;
40247
- }
40248
- for (const word of ["true", "false", "null"]) {
40249
- if (text.startsWith(word, at)) {
40250
- at += word.length;
40251
- return;
40252
- }
40200
+ function encode3(string) {
40201
+ const bytes = new Uint8Array(string.length);
40202
+ for (let i = 0;i < string.length; i++) {
40203
+ const code = string.charCodeAt(i);
40204
+ if (code > 127) {
40205
+ throw new TypeError("non-ASCII string encountered in encode()");
40253
40206
  }
40254
- const number = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(text.slice(at));
40255
- if (number === null)
40256
- fail();
40257
- at += number?.[0].length ?? 0;
40258
- };
40259
- try {
40260
- value();
40261
- space();
40262
- if (at < text.length)
40263
- fail();
40264
- return;
40265
- } catch {
40266
- const before = text.slice(0, at).split(`
40267
- `);
40268
- return `line ${before.length}, column ${(before.at(-1)?.length ?? 0) + 1}`;
40207
+ bytes[i] = code;
40269
40208
  }
40209
+ return bytes;
40270
40210
  }
40271
40211
 
40272
- // ../envoy-client/src/secret-file.ts
40273
- import { readFileSync } from "fs";
40274
-
40275
- // ../cipher-client/src/error-text.ts
40276
- function messageOf(error) {
40277
- return error instanceof Error ? error.message : String(error);
40278
- }
40279
- var READ_ERROR_CODE = /^[A-Z][A-Z0-9_]{0,31}$/;
40280
- function readErrorCode(error) {
40281
- const { code } = error ?? {};
40282
- return typeof code === "string" && READ_ERROR_CODE.test(code) ? code : "an error";
40212
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/crypto_key.js
40213
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
40214
+ function checkUsage(key, usage) {
40215
+ if (usage && !key.usages.includes(usage)) {
40216
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
40217
+ }
40283
40218
  }
40284
-
40285
- // ../envoy-client/src/secret-file.ts
40286
- function sendable(value) {
40287
- return !/[\s\p{Cc}]/u.test(value);
40219
+ function checkModulusLength(alg, key) {
40220
+ const { modulusLength } = key.algorithm;
40221
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
40222
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
40223
+ }
40288
40224
  }
40289
- function readSecretFile(variable, filePath) {
40290
- let contents;
40291
- try {
40292
- contents = readFileSync(filePath, "utf8");
40293
- } catch (error) {
40294
- throw new Error(`${variable} names a file that could not be read (${readErrorCode(error)})`);
40225
+ function checkCryptoKey(key, expected, usage) {
40226
+ const algorithm = key.algorithm;
40227
+ if (algorithm.name !== expected.name) {
40228
+ throw unusable(expected.name);
40295
40229
  }
40296
- const value = contents.trim();
40297
- if (value.length === 0)
40298
- throw new Error(`${variable} names a file that is empty`);
40299
- if (!sendable(value)) {
40300
- throw new Error(`${variable} names a file that holds whitespace or a control character`);
40230
+ if (expected.hash && algorithm.hash?.name !== expected.hash) {
40231
+ throw unusable(expected.hash, "algorithm.hash");
40301
40232
  }
40302
- return holdSecret(value);
40303
- }
40304
-
40305
- // ../envoy-client/src/envoy-config.ts
40306
- var COMMAND_TIMEOUT_MS = 1e4;
40307
- var COMMAND_TIMEOUT_VARIABLE = "ENVOY_COMMAND_TIMEOUT_MS";
40308
- var LONGEST_TIMEOUT_MS = 2147483647;
40309
- function commandTimeoutMs(env) {
40310
- const text = env[COMMAND_TIMEOUT_VARIABLE] ?? "";
40311
- const ms = /^[1-9]\d*$/.test(text) ? Number(text) : Number.NaN;
40312
- return ms <= LONGEST_TIMEOUT_MS ? ms : COMMAND_TIMEOUT_MS;
40313
- }
40314
- function nonEmpty(value) {
40315
- return value === undefined || value === "" ? undefined : value;
40316
- }
40317
- function absolute(name, value) {
40318
- if (value !== undefined && !path.isAbsolute(value)) {
40319
- throw new Error(`${name} is ${value}, which is not an absolute path`);
40233
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
40234
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
40320
40235
  }
40321
- return value;
40322
- }
40323
- function neutralConfig(env) {
40324
- const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
40325
- if (xdgConfigHome !== undefined && !path.isAbsolute(xdgConfigHome)) {
40326
- return { error: `XDG_CONFIG_HOME is ${xdgConfigHome}, which is not an absolute path` };
40236
+ if (expected.length !== undefined && algorithm.length !== expected.length) {
40237
+ throw unusable(expected.length, "algorithm.length");
40327
40238
  }
40328
- const configHome = xdgConfigHome ?? path.join(nonEmpty(env.HOME) ?? homedir(), ".config");
40329
- return { path: path.resolve(configHome, "legion", "envoy.json") };
40239
+ checkUsage(key, usage);
40330
40240
  }
40331
- var HARNESS_DIRECTORY_VARIABLE = {
40332
- omp: "PI_CODING_AGENT_DIR",
40333
- claude: "CLAUDE_CONFIG_DIR"
40334
- };
40335
- var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
40336
- function namedDirectory(harness, env) {
40337
- if (harness === "omp") {
40338
- const profile = nonEmpty(env.OMP_PROFILE);
40339
- if (profile === undefined || profile === "default")
40340
- return;
40241
+
40242
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/invalid_key_input.js
40243
+ function message(msg, actual, ...types) {
40244
+ if (types.length > 2) {
40245
+ const last = types.pop();
40246
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
40247
+ } else if (types.length === 2) {
40248
+ msg += `one of type ${types[0]} or ${types[1]}.`;
40249
+ } else {
40250
+ msg += `of type ${types[0]}.`;
40341
40251
  }
40342
- return nonEmpty(env[HARNESS_DIRECTORY_VARIABLE[harness]]);
40343
- }
40344
- function harnessDirectory(harness, env) {
40345
- if (harness === "codex")
40346
- return;
40347
- for (const plugin of harness === "command" ? PLUGIN_HARNESSES : [harness]) {
40348
- if (harness === "command" && plugin === "claude" && env.CLAUDE_CODE_CHILD_SESSION !== "1") {
40349
- continue;
40252
+ if (actual == null) {
40253
+ msg += ` Received ${actual}`;
40254
+ } else if (typeof actual === "function" && actual.name) {
40255
+ msg += ` Received function ${actual.name}`;
40256
+ } else if (typeof actual === "object" && actual != null) {
40257
+ if (actual.constructor?.name) {
40258
+ msg += ` Received an instance of ${actual.constructor.name}`;
40350
40259
  }
40351
- const directory = namedDirectory(plugin, env);
40352
- if (directory !== undefined)
40353
- return absolute(HARNESS_DIRECTORY_VARIABLE[plugin], directory);
40354
40260
  }
40355
- return;
40261
+ return msg;
40356
40262
  }
40357
- function handedConfigPath(env) {
40358
- const handed = nonEmpty(env.ENVOY_CONFIG_FILE);
40359
- return handed === undefined ? undefined : path.resolve(absolute("ENVOY_CONFIG_FILE", handed));
40263
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
40264
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
40265
+
40266
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/errors.js
40267
+ class JOSEError extends Error {
40268
+ static code = "ERR_JOSE_GENERIC";
40269
+ code = "ERR_JOSE_GENERIC";
40270
+ constructor(message, options) {
40271
+ super(message, options);
40272
+ this.name = this.constructor.name;
40273
+ Error.captureStackTrace?.(this, this.constructor);
40274
+ }
40360
40275
  }
40361
- function envoyConfigPath(harness, env) {
40362
- const handedFirst = harness === "command" ? handedConfigPath(env) : undefined;
40363
- if (handedFirst !== undefined)
40364
- return handedFirst;
40365
- const directory = harnessDirectory(harness, env);
40366
- if (directory !== undefined)
40367
- return path.resolve(directory, "envoy.json");
40368
- const handed = handedConfigPath(env);
40369
- if (handed !== undefined)
40370
- return handed;
40371
- const neutral = neutralConfig(env);
40372
- if ("error" in neutral)
40373
- throw new Error(neutral.error);
40374
- return neutral.path;
40276
+ class JOSENotSupported extends JOSEError {
40277
+ static code = "ERR_JOSE_NOT_SUPPORTED";
40278
+ code = "ERR_JOSE_NOT_SUPPORTED";
40375
40279
  }
40376
- var httpUrlSchema = url({ protocol: /^https?$/, error: "must be an http or https URL" });
40377
- var DispatchSectionSchema = strictObject({
40378
- enabled: boolean2().optional(),
40379
- serverUrl: httpUrlSchema.optional(),
40380
- token: string2().optional()
40381
- });
40382
- var EnvoySectionSchema = strictObject({
40383
- enabled: boolean2().optional(),
40384
- url: httpUrlSchema.optional(),
40385
- natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
40386
- token: string2().optional(),
40387
- natsSeed: string2().optional(),
40388
- natsAuth: string2().optional(),
40389
- inbound: string2().optional()
40390
- });
40391
- var EnvoyFileSchema = looseObject({
40392
- $schema: string2().optional(),
40393
- dispatch: DispatchSectionSchema.optional(),
40394
- envoy: EnvoySectionSchema.optional()
40395
- });
40396
- var CheckoutFileSchema = looseObject({
40397
- $schema: string2().optional(),
40398
- dispatch: DispatchSectionSchema.optional()
40399
- });
40400
- var AskgateSectionSchema = strictObject({ enabled: boolean2().optional() });
40401
- function offWithNotice(notice) {
40402
- return { enabled: false, notice, error: null };
40280
+ class JWSInvalid extends JOSEError {
40281
+ static code = "ERR_JWS_INVALID";
40282
+ code = "ERR_JWS_INVALID";
40403
40283
  }
40404
- function offWithError(error) {
40405
- return { enabled: false, notice: null, error };
40284
+ class JWKInvalid extends JOSEError {
40285
+ static code = "ERR_JWK_INVALID";
40286
+ code = "ERR_JWK_INVALID";
40406
40287
  }
40407
- function httpUrl2(value) {
40408
- let url2;
40288
+
40289
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/is_key_like.js
40290
+ var isCryptoKey = (key) => {
40291
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
40292
+ return true;
40409
40293
  try {
40410
- url2 = new URL(value);
40294
+ return key instanceof CryptoKey;
40411
40295
  } catch {
40412
- return;
40296
+ return false;
40413
40297
  }
40414
- return url2.protocol === "http:" || url2.protocol === "https:" ? url2 : undefined;
40415
- }
40416
- function describeSchemaIssue(filePath, error) {
40417
- const issue = error.issues[0];
40418
- if (!issue)
40419
- return `${filePath}: invalid envoy.json`;
40420
- if (issue.code === "unrecognized_keys") {
40421
- const section = issue.path.join(".");
40422
- const keys = issue.keys.map((key) => `${section}.${key}`).join(", ");
40423
- return `${filePath}: unrecognized ${section} key(s): ${keys}`;
40298
+ };
40299
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
40300
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
40301
+
40302
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/base64.js
40303
+ function encodeBase64(input) {
40304
+ if (Uint8Array.prototype.toBase64) {
40305
+ return input.toBase64();
40424
40306
  }
40425
- return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
40307
+ const CHUNK_SIZE = 32768;
40308
+ const arr = [];
40309
+ for (let i = 0;i < input.length; i += CHUNK_SIZE) {
40310
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
40311
+ }
40312
+ return btoa(arr.join(""));
40426
40313
  }
40427
- function danglingLink(filePath) {
40428
- try {
40429
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
40430
- } catch {
40431
- return null;
40314
+ function decodeBase64(encoded) {
40315
+ if (Uint8Array.fromBase64) {
40316
+ return Uint8Array.fromBase64(encoded);
40317
+ }
40318
+ const binary = atob(encoded);
40319
+ const bytes = new Uint8Array(binary.length);
40320
+ for (let i = 0;i < binary.length; i++) {
40321
+ bytes[i] = binary.charCodeAt(i);
40432
40322
  }
40323
+ return bytes;
40433
40324
  }
40434
- function parseFile(filePath, schema, checkout) {
40435
- let raw;
40436
- try {
40437
- raw = readFileSync2(filePath, "utf-8");
40438
- } catch (error) {
40439
- if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
40440
- return { kind: "absent", link: danglingLink(filePath) };
40325
+
40326
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/base64url.js
40327
+ var invalid = "The input to be decoded is not correctly encoded.";
40328
+ function decode3(input) {
40329
+ if (Uint8Array.fromBase64) {
40330
+ try {
40331
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
40332
+ alphabet: "base64url"
40333
+ });
40334
+ } catch (cause) {
40335
+ throw new TypeError(invalid, { cause });
40441
40336
  }
40442
- return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
40443
40337
  }
40444
- let parsedJson;
40338
+ let encoded = input;
40339
+ if (encoded instanceof Uint8Array) {
40340
+ encoded = decoder.decode(encoded);
40341
+ }
40342
+ if (encoded.includes("+") || encoded.includes("/")) {
40343
+ throw new TypeError(invalid);
40344
+ }
40345
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
40445
40346
  try {
40446
- parsedJson = JSON.parse(raw);
40347
+ return decodeBase64(encoded);
40447
40348
  } catch {
40448
- const position = jsonErrorPosition(raw);
40449
- return {
40450
- kind: "invalid",
40451
- reason: `${filePath}: invalid JSON${position === undefined ? "" : ` at ${position}`}`
40452
- };
40349
+ throw new TypeError(invalid);
40453
40350
  }
40454
- if (typeof parsedJson === "object" && parsedJson !== null && "natsUrls" in parsedJson) {
40455
- return {
40456
- kind: "invalid",
40457
- reason: checkout ? `${filePath}: the top-level natsUrls is not read, and a checkout's envoy.json holds only a dispatch section` : `${filePath}: the top-level natsUrls is not read; move it to envoy.natsUrls`
40458
- };
40351
+ }
40352
+ function encode4(input) {
40353
+ let unencoded = input;
40354
+ if (typeof unencoded === "string") {
40355
+ unencoded = encoder2.encode(unencoded);
40459
40356
  }
40460
- const parsed = schema.safeParse(parsedJson);
40461
- if (!parsed.success) {
40462
- return { kind: "invalid", reason: describeSchemaIssue(filePath, parsed.error) };
40357
+ if (Uint8Array.prototype.toBase64) {
40358
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
40463
40359
  }
40464
- return { kind: "valid", settings: parsed.data };
40360
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
40465
40361
  }
40466
- var FAILURE_KEPT_MS = 60000;
40467
- var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
40468
- var processGlobal = globalThis;
40469
- var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
40470
- processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
40471
- function runCommand(command, env, cwd) {
40472
- const timeoutMs = commandTimeoutMs(env);
40473
- const childEnv = {};
40474
- for (const [name, variable] of Object.entries(env)) {
40475
- if (variable !== undefined)
40476
- childEnv[name] = variable;
40477
- }
40478
- const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
40479
- try {
40480
- chmodSync(directory, 448);
40481
- const output = path.join(directory, "stdout");
40482
- const fd = openSync(output, "wx", 384);
40483
- let result;
40484
- try {
40485
- result = Bun.spawnSync(["/bin/sh", "-c", command], {
40486
- cwd,
40487
- env: childEnv,
40488
- stdin: "ignore",
40489
- stdout: fd,
40490
- stderr: "ignore",
40491
- timeout: timeoutMs,
40492
- detached: true
40493
- });
40494
- } catch (error) {
40495
- return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
40496
- } finally {
40497
- closeSync(fd);
40498
- }
40499
- try {
40500
- process.kill(-result.pid, "SIGKILL");
40501
- } catch {}
40502
- if (result.exitedDueToTimeout) {
40503
- return {
40504
- failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
40505
- timedOut: true
40506
- };
40507
- }
40508
- if (!result.success) {
40509
- return {
40510
- failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
40511
- timedOut: false
40512
- };
40513
- }
40514
- const value = readFileSync2(output, "utf-8").trim();
40515
- if (value.length === 0)
40516
- return { failure: "printed nothing", timedOut: false };
40517
- if (!sendable(value)) {
40518
- return {
40519
- failure: "printed more than one line, or whitespace inside its value",
40520
- timedOut: false
40521
- };
40522
- }
40523
- return { value };
40524
- } finally {
40525
- rmSync(directory, { recursive: true, force: true });
40526
- }
40527
- }
40528
- function fileValue(value, field, filePath, env, commands = "run") {
40529
- if (!value.startsWith("!")) {
40530
- if (!sendable(value)) {
40531
- throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
40532
- }
40533
- return value;
40534
- }
40535
- const command = value.slice(1);
40536
- const cwd = path.dirname(path.resolve(filePath));
40537
- const key = JSON.stringify([command, filePath, cwd]);
40538
- let outcome = commandOutcomes.get(key);
40539
- if (commands === "kept") {
40540
- if (outcome === undefined) {
40541
- throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
40542
- }
40543
- } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
40544
- outcome = { ...runCommand(command, env, cwd), at: Date.now() };
40545
- commandOutcomes.set(key, outcome);
40546
- }
40547
- if ("failure" in outcome)
40548
- throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
40549
- return outcome.value;
40550
- }
40551
- function statDevice(directory) {
40552
- try {
40553
- return statSync(directory).dev;
40554
- } catch {
40555
- return;
40556
- }
40557
- }
40558
- function moveNotice(oldFile, newFile, move, deviceOf) {
40559
- const oldDevice = deviceOf(path.dirname(oldFile));
40560
- let ancestor = path.dirname(newFile);
40561
- let newDevice = deviceOf(ancestor);
40562
- while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
40563
- ancestor = path.dirname(ancestor);
40564
- newDevice = deviceOf(ancestor);
40565
- }
40566
- if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
40567
- return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
40568
- }
40569
- return `${oldFile} is not read: ${move}`;
40570
- }
40571
- function oldUserFileNotice(filePath, env, deviceOf) {
40572
- const home = nonEmpty(env.HOME) ?? homedir();
40573
- const old = path.join(home, ".config", "opencode", "envoy.json");
40574
- if (!existsSync(old))
40575
- return;
40576
- const selected = path.resolve(filePath);
40577
- const userFile = path.resolve(home, ".config", "legion", "envoy.json");
40578
- if (selected === userFile) {
40579
- return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
40580
- }
40581
- const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
40582
- if (profileFile) {
40583
- return `${old} is not read for this profile; copy or link it to ${filePath}, or write that file`;
40584
- }
40585
- const configHome = nonEmpty(env.XDG_CONFIG_HOME);
40586
- const neutral = neutralConfig(env);
40587
- if (configHome !== undefined && path.isAbsolute(configHome) && "path" in neutral && selected === neutral.path) {
40588
- return `${old} is not read under XDG_CONFIG_HOME=${configHome}`;
40589
- }
40590
- return;
40591
- }
40592
- function missingConfigNotice(filePath, missing, off) {
40593
- const link = missing.link === null ? "" : ` (a link to ${missing.link}, which does not exist)`;
40594
- const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
40595
- return `no envoy.json at ${filePath}${link}: ${off}${old}`;
40596
- }
40597
- function readEnvoyConfig(filePath, env, options) {
40598
- const deviceOf = options.deviceOf ?? statDevice;
40599
- const chosen = parseFile(filePath, EnvoyFileSchema, false);
40600
- if (chosen.kind === "invalid")
40601
- return { kind: "failed", path: filePath, error: chosen.reason };
40602
- const resolvedChosen = path.resolve(filePath);
40603
- const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
40604
- const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
40605
- const own = chosen.kind === "valid" ? chosen.settings : {};
40606
- let checkout = null;
40607
- if (checkoutFile.kind === "invalid") {
40608
- checkout = { kind: "invalid", path: checkoutPath, error: checkoutFile.reason };
40609
- } else if (checkoutFile.kind === "valid") {
40610
- checkout = {
40611
- kind: "valid",
40612
- path: checkoutPath,
40613
- dispatch: checkoutFile.settings.dispatch ?? {},
40614
- envoyError: Object.hasOwn(checkoutFile.settings, "envoy") ? `${checkoutPath}: envoy is not read from a checkout's envoy.json; put it in ${filePath}` : null,
40615
- askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
40616
- };
40617
- }
40618
- const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
40619
- const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
40620
- moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
40621
- ] : [];
40622
- const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
40623
- return {
40624
- kind: "read",
40625
- path: filePath,
40626
- dispatch: own.dispatch ?? {},
40627
- envoy: own.envoy ?? {},
40628
- checkout,
40629
- missing: chosen.kind === "absent" ? {
40630
- link: chosen.link,
40631
- ...unreadOldUserFile === undefined ? {} : { oldUserFileNotice: unreadOldUserFile }
40632
- } : null,
40633
- warnings
40634
- };
40635
- }
40636
-
40637
- // ../envoy-client/src/bearer.ts
40638
- function credentialDeadline(deadline, deadlineMs) {
40639
- const reserveMs = Math.min(1000, deadlineMs / 2);
40640
- return AbortSignal.any([deadline, AbortSignal.timeout(Math.ceil(deadlineMs - reserveMs))]);
40641
- }
40642
- function bearerCredential(token) {
40643
- holdSecret(token);
40644
- return {
40645
- scheme: "Bearer",
40646
- headers: () => ({ Authorization: `Bearer ${token}` }),
40647
- secret: () => token
40648
- };
40649
- }
40650
- function bearerSource(env, section, written) {
40651
- const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
40652
- if (pointer !== undefined) {
40653
- return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
40654
- }
40655
- const plain = nonEmpty(env[`${section}_TOKEN`]);
40656
- if (plain !== undefined) {
40657
- if (!sendable(plain)) {
40658
- throw new Error(`${section}_TOKEN holds whitespace or a control character`);
40659
- }
40660
- return { kind: "variable", token: plain };
40661
- }
40662
- const bearer = written();
40663
- return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
40664
- }
40665
- function fileBearer(bearer, url, section, env, commands = "run") {
40666
- const named = httpUrl2(url)?.origin;
40667
- const paired = httpUrl2(bearer.server)?.origin;
40668
- if (named !== paired) {
40669
- throw new Error(`${section}_URL names ${named}, but ${bearer.path}'s ${bearer.field} is for ${paired}; set ${section}_TOKEN or ${section}_TOKEN_FILE for it`);
40670
- }
40671
- if (bearer.checkout && bearer.token.startsWith("!")) {
40672
- throw new Error(`${bearer.path}: ${bearer.field} is a command, which a checkout's envoy.json cannot run`);
40673
- }
40674
- if (bearer.token === "") {
40675
- throw new Error(`${bearer.field} in ${bearer.path} must be a non-empty bearer token`);
40676
- }
40677
- return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
40678
- }
40679
-
40680
- // ../cipher-client/src/device-login.ts
40681
- import { generateKeyPairSync as generateKeyPairSync2, randomUUID as randomUUID4 } from "crypto";
40682
-
40683
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
40684
- var encoder2 = new TextEncoder;
40685
- var decoder = new TextDecoder;
40686
- var strictDecoder = new TextDecoder("utf-8", { fatal: true });
40687
- var MAX_INT32 = 2 ** 32;
40688
- function concat(...buffers) {
40689
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
40690
- const buf = new Uint8Array(size);
40691
- let i = 0;
40692
- for (const buffer of buffers) {
40693
- buf.set(buffer, i);
40694
- i += buffer.length;
40695
- }
40696
- return buf;
40697
- }
40698
- function encode3(string) {
40699
- const bytes = new Uint8Array(string.length);
40700
- for (let i = 0;i < string.length; i++) {
40701
- const code = string.charCodeAt(i);
40702
- if (code > 127) {
40703
- throw new TypeError("non-ASCII string encountered in encode()");
40704
- }
40705
- bytes[i] = code;
40706
- }
40707
- return bytes;
40708
- }
40709
-
40710
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/crypto_key.js
40711
- var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
40712
- function checkUsage(key, usage) {
40713
- if (usage && !key.usages.includes(usage)) {
40714
- throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
40715
- }
40716
- }
40717
- function checkModulusLength(alg, key) {
40718
- const { modulusLength } = key.algorithm;
40719
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
40720
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
40721
- }
40722
- }
40723
- function checkCryptoKey(key, expected, usage) {
40724
- const algorithm = key.algorithm;
40725
- if (algorithm.name !== expected.name) {
40726
- throw unusable(expected.name);
40727
- }
40728
- if (expected.hash && algorithm.hash?.name !== expected.hash) {
40729
- throw unusable(expected.hash, "algorithm.hash");
40730
- }
40731
- if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
40732
- throw unusable(expected.namedCurve, "algorithm.namedCurve");
40733
- }
40734
- if (expected.length !== undefined && algorithm.length !== expected.length) {
40735
- throw unusable(expected.length, "algorithm.length");
40736
- }
40737
- checkUsage(key, usage);
40738
- }
40739
-
40740
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/invalid_key_input.js
40741
- function message(msg, actual, ...types) {
40742
- if (types.length > 2) {
40743
- const last = types.pop();
40744
- msg += `one of type ${types.join(", ")}, or ${last}.`;
40745
- } else if (types.length === 2) {
40746
- msg += `one of type ${types[0]} or ${types[1]}.`;
40747
- } else {
40748
- msg += `of type ${types[0]}.`;
40749
- }
40750
- if (actual == null) {
40751
- msg += ` Received ${actual}`;
40752
- } else if (typeof actual === "function" && actual.name) {
40753
- msg += ` Received function ${actual.name}`;
40754
- } else if (typeof actual === "object" && actual != null) {
40755
- if (actual.constructor?.name) {
40756
- msg += ` Received an instance of ${actual.constructor.name}`;
40757
- }
40758
- }
40759
- return msg;
40760
- }
40761
- var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
40762
- var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
40763
-
40764
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/errors.js
40765
- class JOSEError extends Error {
40766
- static code = "ERR_JOSE_GENERIC";
40767
- code = "ERR_JOSE_GENERIC";
40768
- constructor(message, options) {
40769
- super(message, options);
40770
- this.name = this.constructor.name;
40771
- Error.captureStackTrace?.(this, this.constructor);
40772
- }
40773
- }
40774
- class JOSENotSupported extends JOSEError {
40775
- static code = "ERR_JOSE_NOT_SUPPORTED";
40776
- code = "ERR_JOSE_NOT_SUPPORTED";
40777
- }
40778
- class JWSInvalid extends JOSEError {
40779
- static code = "ERR_JWS_INVALID";
40780
- code = "ERR_JWS_INVALID";
40781
- }
40782
- class JWKInvalid extends JOSEError {
40783
- static code = "ERR_JWK_INVALID";
40784
- code = "ERR_JWK_INVALID";
40785
- }
40786
-
40787
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/is_key_like.js
40788
- var isCryptoKey = (key) => {
40789
- if (key?.[Symbol.toStringTag] === "CryptoKey")
40790
- return true;
40791
- try {
40792
- return key instanceof CryptoKey;
40793
- } catch {
40794
- return false;
40795
- }
40796
- };
40797
- var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
40798
- var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
40799
-
40800
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/base64.js
40801
- function encodeBase64(input) {
40802
- if (Uint8Array.prototype.toBase64) {
40803
- return input.toBase64();
40804
- }
40805
- const CHUNK_SIZE = 32768;
40806
- const arr = [];
40807
- for (let i = 0;i < input.length; i += CHUNK_SIZE) {
40808
- arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
40809
- }
40810
- return btoa(arr.join(""));
40811
- }
40812
- function decodeBase64(encoded) {
40813
- if (Uint8Array.fromBase64) {
40814
- return Uint8Array.fromBase64(encoded);
40815
- }
40816
- const binary = atob(encoded);
40817
- const bytes = new Uint8Array(binary.length);
40818
- for (let i = 0;i < binary.length; i++) {
40819
- bytes[i] = binary.charCodeAt(i);
40820
- }
40821
- return bytes;
40822
- }
40823
-
40824
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/base64url.js
40825
- var invalid = "The input to be decoded is not correctly encoded.";
40826
- function decode3(input) {
40827
- if (Uint8Array.fromBase64) {
40828
- try {
40829
- return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
40830
- alphabet: "base64url"
40831
- });
40832
- } catch (cause) {
40833
- throw new TypeError(invalid, { cause });
40834
- }
40835
- }
40836
- let encoded = input;
40837
- if (encoded instanceof Uint8Array) {
40838
- encoded = decoder.decode(encoded);
40839
- }
40840
- if (encoded.includes("+") || encoded.includes("/")) {
40841
- throw new TypeError(invalid);
40842
- }
40843
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
40844
- try {
40845
- return decodeBase64(encoded);
40846
- } catch {
40847
- throw new TypeError(invalid);
40848
- }
40849
- }
40850
- function encode4(input) {
40851
- let unencoded = input;
40852
- if (typeof unencoded === "string") {
40853
- unencoded = encoder2.encode(unencoded);
40854
- }
40855
- if (Uint8Array.prototype.toBase64) {
40856
- return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
40857
- }
40858
- return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
40859
- }
40860
-
40861
- // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/type_checks.js
40862
- function isObject2(input) {
40863
- if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
40864
- return false;
40362
+
40363
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/type_checks.js
40364
+ function isObject2(input) {
40365
+ if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
40366
+ return false;
40865
40367
  }
40866
40368
  const prototype = Object.getPrototypeOf(input);
40867
40369
  if (prototype === null) {
@@ -42661,38 +42163,6 @@ async function genericGrantRequest(config, grantType, parameters, options) {
42661
42163
  return result;
42662
42164
  }
42663
42165
 
42664
- // ../cipher-client/src/device-login-file.ts
42665
- import { createPrivateKey, randomUUID as randomUUID2 } from "crypto";
42666
- import { constants as constants2 } from "fs";
42667
- import {
42668
- access,
42669
- lstat as lstat2,
42670
- mkdir,
42671
- open as open2,
42672
- readFile as readFile2,
42673
- readlink,
42674
- rename as rename2,
42675
- rm as rm2,
42676
- stat as stat2
42677
- } from "fs/promises";
42678
- import { userInfo } from "os";
42679
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join4 } from "path";
42680
-
42681
- // ../cipher-client/src/device-login-lock.ts
42682
- import { randomUUID } from "crypto";
42683
- import { closeSync as closeSync2, constants, fstatSync, openSync as openSync2, readSync } from "fs";
42684
- import {
42685
- link,
42686
- lstat,
42687
- open,
42688
- readdir as readdir2,
42689
- rename,
42690
- rm,
42691
- stat,
42692
- utimes
42693
- } from "fs/promises";
42694
- import { basename, dirname as dirname2, join as join3 } from "path";
42695
-
42696
42166
  // ../cipher-client/src/wire.ts
42697
42167
  var TOKEN_PATH = "/v1/oauth/token";
42698
42168
  var GRANT_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
@@ -42701,6 +42171,10 @@ var FORM_SESSION = "session";
42701
42171
  var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
42702
42172
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
42703
42173
  var FORM_PROJECTS = "projects";
42174
+ var FORM_SCOPE = "scope";
42175
+ var SCOPE_READ = "read";
42176
+ var FORM_AS_OF = "as_of";
42177
+ var HEADER_DPOP_HOLDER = "DPoP-Holder";
42704
42178
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
42705
42179
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
42706
42180
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
@@ -42813,6 +42287,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
42813
42287
  "The machine login the subject token belongs to has ended\\.",
42814
42288
  "The machine login has ended\\.",
42815
42289
  "Another live machine login holds the key this proof was signed with\\. A (?:machine makes a key of its own|sign-in makes a box key of its own)\\.",
42290
+ "A live read token is bound to the key this proof was signed with\\. Make a new key\\.",
42816
42291
  `${PERSON_SLOT} is a restricted member, whose token names its projects: set AGENT_SECRETS_PROJECTS to the projects this session works on\\.`,
42817
42292
  `The token names a project its person cannot see: ${PROJECT_SLOT}\\.`,
42818
42293
  `The subject token was refused: its entry names the project ${PROJECT_SLOT}, which its person ${PERSON_SLOT} cannot see\\.`,
@@ -42825,6 +42300,19 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
42825
42300
  `The session name '${SESSION_SLOT}' belongs to another daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
42826
42301
  `The session name '${SESSION_SLOT}' is bound to no daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
42827
42302
  `${PERSON_SLOT}'s credentials are held by Dispatch; they work again when \\k<person> signs in to Dispatch, or when Dispatch can confirm \\k<person> with Google again`,
42303
+ "The 'as_of' parameter names a cut, and only a trade that asks for the scope read may name one\\.",
42304
+ "The 'as_of' parameter is not an RFC 3339 time with at most six fractional digits\\.",
42305
+ "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
42306
+ "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
42307
+ "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
42308
+ `${PERSON_SLOT}'s sign-in on this machine holds no launcher credential yet, and a read trade makes none\\. Sign in with \`agent-secrets login\` first\\.`,
42309
+ `${PERSON_SLOT}'s sign-in on this machine holds a launcher credential that has lapsed, and a read trade renews none\\. One ordinary trade of the sign-in renews it, as \`agent-secrets\` makes; then trade for read again\\.`,
42310
+ "A person's read trade sends a DPoP-Holder proof: the box key proves the sign-in and is bound to no read token, so the token is bound to a key made for its holder\\.",
42311
+ "The DPoP-Holder header binds a read token to its holder's key, and this trade does not ask for the scope read\\. Ask for it, or send no DPoP-Holder header\\.",
42312
+ "The DPoP-Holder proof was refused: a trade sends one, a DPoP proof of this request signed with the key it embeds, spent nowhere before\\.",
42313
+ "The DPoP-Holder proof is signed with the key the DPoP proof is signed with, and the holder's key is a key of its own\\.",
42314
+ "The key this read token would be bound to signs launcher proofs: a live launcher credential is bound to it, and no read token is bound to such a key\\. Send a DPoP-Holder proof by a key made for the token's holder, and the token is bound to that key\\.",
42315
+ "The key this proof was signed with signs launcher proofs: a live launcher credential is bound to it, and no read token is bound to such a key\\. Ask for the scope read with a DPoP-Holder proof by a key made for the token's holder, or trade with a key that holds no launcher credential\\.",
42828
42316
  ...POLICY_REFUSAL_PATTERNS
42829
42317
  ].map((source) => new RegExp(`^${source}$`));
42830
42318
  var LIBRARY_DESCRIPTIONS = [
@@ -42891,7 +42379,19 @@ function shownOAuthCode(code) {
42891
42379
 
42892
42380
  // ../cipher-client/src/signins.ts
42893
42381
  import { readdir, readFile } from "fs/promises";
42894
- import { join as join2 } from "path";
42382
+ import { join } from "path";
42383
+
42384
+ // ../cipher-client/src/error-text.ts
42385
+ function messageOf(error) {
42386
+ return error instanceof Error ? error.message : String(error);
42387
+ }
42388
+ var READ_ERROR_CODE = /^[A-Z][A-Z0-9_]{0,31}$/;
42389
+ function readErrorCode(error) {
42390
+ const { code } = error ?? {};
42391
+ return typeof code === "string" && READ_ERROR_CODE.test(code) ? code : "an error";
42392
+ }
42393
+
42394
+ // ../cipher-client/src/signins.ts
42895
42395
  var SIGNIN_DIR_VAR = "AGENT_SECRETS_SIGNIN_DIR";
42896
42396
  var PERSON_VAR = "AGENT_SECRETS_PERSON";
42897
42397
  var PERSON_TRADE_VAR = "PERSON_SIGNIN_TRADE";
@@ -42916,8 +42416,8 @@ function signInDirectory(env) {
42916
42416
  if (named !== "")
42917
42417
  return named;
42918
42418
  const state = env.XDG_STATE_HOME ?? "";
42919
- const base = state !== "" ? state : join2(env.HOME ?? "", ".local", "state");
42920
- return join2(base, "agent-secrets", SIGNINS_DIR);
42419
+ const base = state !== "" ? state : join(env.HOME ?? "", ".local", "state");
42420
+ return join(base, "agent-secrets", SIGNINS_DIR);
42921
42421
  }
42922
42422
  async function readSignIn(path) {
42923
42423
  let text;
@@ -42962,7 +42462,7 @@ async function listSignIns(dir) {
42962
42462
  const names = entries.filter((entry) => !entry.isDirectory() && entry.name.endsWith(".json")).map((entry) => entry.name).sort();
42963
42463
  const records = [];
42964
42464
  for (const name of names)
42965
- records.push(await readSignIn(join2(dir, name)));
42465
+ records.push(await readSignIn(join(dir, name)));
42966
42466
  return records.sort((a, b) => a.person < b.person ? -1 : a.person > b.person ? 1 : 0);
42967
42467
  }
42968
42468
  function namesOf(records) {
@@ -43120,32 +42620,8 @@ function isFinalRefusal(error) {
43120
42620
  return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
43121
42621
  }
43122
42622
 
43123
- // ../cipher-client/src/token-client.ts
43124
- var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
42623
+ // ../cipher-client/src/broker-request.ts
43125
42624
  var BROKER_URL_SETTING = "the broker URL";
43126
- var RETRY_FIRST_WAIT_MS = 15000;
43127
- var RETRY_MAX_WAIT_MS = 5 * 60000;
43128
- var PENDING_FIRST_WAIT_MS = 2000;
43129
- var PENDING_MAX_WAIT_MS = 30000;
43130
- var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
43131
- var TRADE_ATTEMPT_MS = 30000;
43132
- function sleep2(ms, signal, holdsProcess = false) {
43133
- const { promise, resolve } = Promise.withResolvers();
43134
- if (signal?.aborted) {
43135
- resolve();
43136
- return promise;
43137
- }
43138
- const done = () => {
43139
- clearTimeout(timer);
43140
- signal?.removeEventListener("abort", done);
43141
- resolve();
43142
- };
43143
- const timer = setTimeout(done, ms);
43144
- if (!holdsProcess)
43145
- timer.unref();
43146
- signal?.addEventListener("abort", done, { once: true });
43147
- return promise;
43148
- }
43149
42625
  function statusOf(error) {
43150
42626
  let cause = error;
43151
42627
  for (let depth = 0;depth < 4; depth += 1) {
@@ -43182,7 +42658,11 @@ function requestInit(options, signal, headers) {
43182
42658
  async function sendWithProof(proved, url, options, signal) {
43183
42659
  const send = async () => {
43184
42660
  const headers = new Headers(options.headers);
43185
- headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
42661
+ const request = { method: options.method, url, nonce: proved.nonce.value };
42662
+ headers.set("DPoP", await proved.key.proof(request));
42663
+ if (proved.holderKey !== undefined) {
42664
+ headers.set(HEADER_DPOP_HOLDER, await proved.holderKey.proof(request));
42665
+ }
43186
42666
  return await proved.fetch(url, requestInit(options, signal, headers));
43187
42667
  };
43188
42668
  let answer = await send();
@@ -43198,14 +42678,82 @@ async function sendWithProof(proved, url, options, signal) {
43198
42678
  return answer;
43199
42679
  }
43200
42680
 
42681
+ // ../cipher-client/src/device-login-file.ts
42682
+ import { createPrivateKey, randomUUID as randomUUID2 } from "crypto";
42683
+ import { constants as constants2 } from "fs";
42684
+ import {
42685
+ access,
42686
+ lstat as lstat2,
42687
+ mkdir,
42688
+ open as open2,
42689
+ readFile as readFile2,
42690
+ readlink,
42691
+ rename as rename2,
42692
+ rm as rm2,
42693
+ stat as stat2
42694
+ } from "fs/promises";
42695
+ import { userInfo } from "os";
42696
+ import { dirname as dirname2, isAbsolute, join as join3 } from "path";
42697
+
42698
+ // ../cipher-client/src/device-login-lock.ts
42699
+ import { randomUUID } from "crypto";
42700
+ import { closeSync, constants, fstatSync, openSync, readSync } from "fs";
42701
+ import {
42702
+ link,
42703
+ lstat,
42704
+ open,
42705
+ readdir as readdir2,
42706
+ rename,
42707
+ rm,
42708
+ stat,
42709
+ utimes
42710
+ } from "fs/promises";
42711
+ import { basename, dirname, join as join2 } from "path";
42712
+
42713
+ // ../cipher-client/src/token-client.ts
42714
+ var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
42715
+ function renewalAt(expiresAt, now, renewBeforeMs) {
42716
+ const left = expiresAt - now;
42717
+ if (left <= 0)
42718
+ return now;
42719
+ return Math.max(expiresAt - renewBeforeMs, now + left / 2);
42720
+ }
42721
+ var EXPIRES_IN_STEP_MS = 1000;
42722
+ var RETRY_FIRST_WAIT_MS = 15000;
42723
+ var RETRY_MAX_WAIT_MS = 5 * 60000;
42724
+ var PENDING_FIRST_WAIT_MS = 2000;
42725
+ var PENDING_MAX_WAIT_MS = 30000;
42726
+ var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
42727
+ var TRADE_ATTEMPT_MS = 30000;
42728
+ function sleep2(ms, signal, holdsProcess = false) {
42729
+ const { promise, resolve } = Promise.withResolvers();
42730
+ if (signal?.aborted) {
42731
+ resolve();
42732
+ return promise;
42733
+ }
42734
+ const done = () => {
42735
+ clearTimeout(timer);
42736
+ signal?.removeEventListener("abort", done);
42737
+ resolve();
42738
+ };
42739
+ const timer = setTimeout(done, ms);
42740
+ if (!holdsProcess)
42741
+ timer.unref();
42742
+ signal?.addEventListener("abort", done, { once: true });
42743
+ return promise;
42744
+ }
42745
+
43201
42746
  class BrokerTokenClient {
43202
42747
  #brokerUrl;
43203
42748
  #key;
42749
+ #holderKey;
43204
42750
  #subject;
43205
42751
  #actor;
43206
42752
  #session;
43207
42753
  #projects;
43208
42754
  #launcherCredential;
42755
+ #scope;
42756
+ #asOf;
43209
42757
  #renewBeforeMs;
43210
42758
  #now;
43211
42759
  #attemptMs;
@@ -43234,11 +42782,14 @@ class BrokerTokenClient {
43234
42782
  throw new Error("broker client: the broker URL is not an http or https URL");
43235
42783
  this.#brokerUrl = holdUrlUserinfo(brokerUrl);
43236
42784
  this.#key = options.key;
42785
+ this.#holderKey = options.holderKey;
43237
42786
  this.#subject = options.subject;
43238
42787
  this.#actor = options.actor;
43239
42788
  this.#session = options.session ?? "";
43240
42789
  this.#projects = [...options.projects ?? []];
43241
42790
  this.#launcherCredential = options.launcherCredential ?? true;
42791
+ this.#scope = options.scope ?? "";
42792
+ this.#asOf = options.asOf ?? "";
43242
42793
  this.#renewBeforeMs = options.renewBeforeMs ?? DEFAULT_RENEW_BEFORE_MS;
43243
42794
  this.#now = options.now ?? Date.now;
43244
42795
  this.#attemptMs = options.attemptMs ?? TRADE_ATTEMPT_MS;
@@ -43248,7 +42799,7 @@ class BrokerTokenClient {
43248
42799
  this.#random = options.random ?? Math.random;
43249
42800
  }
43250
42801
  get key() {
43251
- return this.#key;
42802
+ return this.#holderKey ?? this.#key;
43252
42803
  }
43253
42804
  describe() {
43254
42805
  return this.#subject.describe();
@@ -43257,10 +42808,11 @@ class BrokerTokenClient {
43257
42808
  const waitForReady = options.waitForReady === true;
43258
42809
  const now = this.#now();
43259
42810
  const held = this.#held;
43260
- if (held !== null && now < held.expiresAt.getTime() - this.#renewBeforeMs)
43261
- return held;
43262
- if (held !== null && now < held.expiresAt.getTime() && this.#last !== null)
43263
- return held;
42811
+ if (held !== null && now < held.renewsAt)
42812
+ return held.token;
42813
+ if (held !== null && now < held.token.expiresAt.getTime() && this.#last !== null) {
42814
+ return held.token;
42815
+ }
43264
42816
  const closed = this.#closed.signal;
43265
42817
  if (closed.aborted)
43266
42818
  throw closed.reason;
@@ -43294,8 +42846,8 @@ class BrokerTokenClient {
43294
42846
  const stop = () => {
43295
42847
  this.#waiters.delete(waiter);
43296
42848
  const held = this.#held;
43297
- if (held !== null && this.#now() < held.expiresAt.getTime())
43298
- resolve(held);
42849
+ if (held !== null && this.#now() < held.token.expiresAt.getTime())
42850
+ resolve(held.token);
43299
42851
  else
43300
42852
  reject(this.#stopped(signal?.reason));
43301
42853
  };
@@ -43335,7 +42887,7 @@ class BrokerTokenClient {
43335
42887
  });
43336
42888
  }
43337
42889
  drop(accessToken) {
43338
- if (accessToken !== undefined && this.#held?.accessToken !== accessToken)
42890
+ if (accessToken !== undefined && this.#held?.token.accessToken !== accessToken)
43339
42891
  return;
43340
42892
  this.#held = null;
43341
42893
  }
@@ -43366,7 +42918,10 @@ class BrokerTokenClient {
43366
42918
  if (this.#pendingSaid !== null && this.#since !== null) {
43367
42919
  this.#log(`the secrets broker answered this pod's session ${this.#session} once it was registered, ${Math.round((this.#now() - this.#since) / 1000)} s and ${this.#failed} failed trades after the first`);
43368
42920
  }
43369
- this.#held = token;
42921
+ this.#held = {
42922
+ token,
42923
+ renewsAt: renewalAt(token.expiresAt.getTime(), this.#now(), this.#renewBeforeMs)
42924
+ };
43370
42925
  this.#last = null;
43371
42926
  this.#since = null;
43372
42927
  this.#failed = 0;
@@ -43406,8 +42961,8 @@ class BrokerTokenClient {
43406
42961
  this.#since ??= now;
43407
42962
  this.#failed += 1;
43408
42963
  const held = this.#held;
43409
- if (held !== null && now < held.expiresAt.getTime()) {
43410
- this.#tell((waiter) => waiter.resolve(held));
42964
+ if (held !== null && now < held.token.expiresAt.getTime()) {
42965
+ this.#tell((waiter) => waiter.resolve(held.token));
43411
42966
  } else {
43412
42967
  this.#held = null;
43413
42968
  if (failure.kind !== "pending") {
@@ -43459,7 +43014,8 @@ class BrokerTokenClient {
43459
43014
  async#trade(signal) {
43460
43015
  const source = this.#subject;
43461
43016
  if (source.spend !== undefined) {
43462
- return await source.spend((subject) => this.#exchange(subject, signal), signal);
43017
+ const leastLifeMs = this.#scope === SCOPE_READ ? this.#renewBeforeMs + EXPIRES_IN_STEP_MS : undefined;
43018
+ return await source.spend((subject) => this.#exchange(subject, signal), signal, leastLifeMs);
43463
43019
  }
43464
43020
  return await this.#exchange(await source.read(signal), signal);
43465
43021
  }
@@ -43473,6 +43029,10 @@ class BrokerTokenClient {
43473
43029
  form[FORM_SESSION] = this.#session;
43474
43030
  if (this.#projects.length > 0)
43475
43031
  form[FORM_PROJECTS] = this.#projects.join(" ");
43032
+ if (this.#scope !== "")
43033
+ form[FORM_SCOPE] = this.#scope;
43034
+ if (this.#asOf !== "")
43035
+ form[FORM_AS_OF] = this.#asOf;
43476
43036
  if (!this.#launcherCredential) {
43477
43037
  form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
43478
43038
  }
@@ -43505,7 +43065,7 @@ class BrokerTokenClient {
43505
43065
  return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
43506
43066
  }
43507
43067
  async#send(url, options, signal, raw) {
43508
- const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
43068
+ const answer = await sendWithProof({ key: this.#key, holderKey: this.#holderKey, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
43509
43069
  raw.body = await answer.clone().json().catch(() => {
43510
43070
  return;
43511
43071
  });
@@ -43713,7 +43273,7 @@ async function withLoginLock(path, named, work, options = {}) {
43713
43273
  function loginLockHeldBy(path, pid) {
43714
43274
  let fd;
43715
43275
  try {
43716
- fd = openSync2(`${path}.lock`, LOCK_READ);
43276
+ fd = openSync(`${path}.lock`, LOCK_READ);
43717
43277
  } catch {
43718
43278
  return false;
43719
43279
  }
@@ -43727,7 +43287,7 @@ function loginLockHeldBy(path, pid) {
43727
43287
  return false;
43728
43288
  } finally {
43729
43289
  try {
43730
- closeSync2(fd);
43290
+ closeSync(fd);
43731
43291
  } catch {}
43732
43292
  }
43733
43293
  }
@@ -43737,7 +43297,7 @@ function namedWithUuid(name, prefix) {
43737
43297
  async function removeUntouched(dir, left) {
43738
43298
  const names = await readdir2(dir).catch(() => []);
43739
43299
  for (const name of names.filter(left)) {
43740
- const path = join3(dir, name);
43300
+ const path = join2(dir, name);
43741
43301
  const info = await stat(path).catch(() => null);
43742
43302
  if (info !== null && Date.now() - info.mtimeMs > DEVICE_LOGIN_STALE_LOCK_MS) {
43743
43303
  await rm(path, { force: true }).catch(() => {});
@@ -43746,7 +43306,7 @@ async function removeUntouched(dir, left) {
43746
43306
  }
43747
43307
  async function removeLeftLocks(path) {
43748
43308
  const name = basename(path);
43749
- await removeUntouched(dirname2(path), (one) => namedWithUuid(one, `${name}.lock.stale-`) || namedWithUuid(one, `${name}.lock.steal.stale-`));
43309
+ await removeUntouched(dirname(path), (one) => namedWithUuid(one, `${name}.lock.stale-`) || namedWithUuid(one, `${name}.lock.steal.stale-`));
43750
43310
  }
43751
43311
  // ../cipher-client/src/device-login-file.ts
43752
43312
  var DEVICE_LOGIN_FILE_VAR = "AGENT_SECRETS_DEVICE_LOGIN_FILE";
@@ -43762,12 +43322,16 @@ function deviceLoginFile(env) {
43762
43322
  if (home === "") {
43763
43323
  throw new Error(`${DEVICE_LOGIN_FILE_VAR} names no file and HOME names no home directory, so this machine has nowhere to keep its device login`);
43764
43324
  }
43765
- return join4(home, ".config", "legion", "device-login.json");
43325
+ return join3(home, ".config", "legion", "device-login.json");
43766
43326
  }
43767
43327
  function member(json, name) {
43768
43328
  const value = json[name];
43769
43329
  return typeof value === "string" ? value : "";
43770
43330
  }
43331
+ function wholeMember(json, name) {
43332
+ const value = json[name];
43333
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
43334
+ }
43771
43335
  function checkPrivate(info, what, forbidden, opens, notOwned) {
43772
43336
  const mode = info.mode & 511;
43773
43337
  if ((mode & forbidden) !== 0) {
@@ -43889,7 +43453,7 @@ async function lstatOnTheWay(path, what) {
43889
43453
  }
43890
43454
  }
43891
43455
  async function walkTheWay(path, what, meet) {
43892
- const names = (isAbsolute2(path) ? path : `${process.cwd()}/${path}`).split("/");
43456
+ const names = (isAbsolute(path) ? path : `${process.cwd()}/${path}`).split("/");
43893
43457
  let reached = "/";
43894
43458
  let info = await lstatOnTheWay(reached, what);
43895
43459
  let followed = 0;
@@ -43899,7 +43463,7 @@ async function walkTheWay(path, what, meet) {
43899
43463
  if (name === "" || name === ".")
43900
43464
  continue;
43901
43465
  if (name === "..") {
43902
- reached = dirname3(reached);
43466
+ reached = dirname2(reached);
43903
43467
  info = await lstatOnTheWay(reached, what);
43904
43468
  continue;
43905
43469
  }
@@ -43927,7 +43491,7 @@ async function walkTheWay(path, what, meet) {
43927
43491
  continue;
43928
43492
  }
43929
43493
  names.unshift(...target.split("/"));
43930
- if (isAbsolute2(target)) {
43494
+ if (isAbsolute(target)) {
43931
43495
  reached = "/";
43932
43496
  info = await lstatOnTheWay(reached, what);
43933
43497
  }
@@ -43945,7 +43509,7 @@ async function homeReached() {
43945
43509
  return null;
43946
43510
  }
43947
43511
  }
43948
- if (!isAbsolute2(home))
43512
+ if (!isAbsolute(home))
43949
43513
  return null;
43950
43514
  return await walkTheWay(home, "the home directory").catch(() => null);
43951
43515
  }
@@ -43991,7 +43555,7 @@ function refusedBy(error, doing) {
43991
43555
  return new Error(`${doing}: ${code}`);
43992
43556
  }
43993
43557
  async function deviceLoginDirectory(path) {
43994
- const dir = dirname3(path);
43558
+ const dir = dirname2(path);
43995
43559
  try {
43996
43560
  await mkdir(dir, { recursive: true, mode: 448 });
43997
43561
  } catch (error) {
@@ -44001,7 +43565,7 @@ async function deviceLoginDirectory(path) {
44001
43565
  }
44002
43566
  async function deviceLoginPlace(path) {
44003
43567
  await deviceLoginDirectory(path);
44004
- const dir = dirname3(path);
43568
+ const dir = dirname2(path);
44005
43569
  try {
44006
43570
  await access(dir, constants2.W_OK | constants2.X_OK);
44007
43571
  } catch (error) {
@@ -44022,11 +43586,11 @@ async function deviceLoginPlace(path) {
44022
43586
  var LOGIN_READ = constants2.O_RDONLY | constants2.O_NONBLOCK | constants2.O_NOCTTY;
44023
43587
  var LINKS_FOLLOWED_AT_MOST = 40;
44024
43588
  async function checkLinkDirectories(path, absent) {
44025
- let checked = dirname3(path);
43589
+ let checked = dirname2(path);
44026
43590
  let at = path;
44027
43591
  for (let followed = 0;; followed += 1) {
44028
- if (dirname3(at) !== checked) {
44029
- checked = dirname3(at);
43592
+ if (dirname2(at) !== checked) {
43593
+ checked = dirname2(at);
44030
43594
  await checkLoginDirectory(checked, absent, `the directory of a file ${DEVICE_LOGIN_FILE_NAMED} links to`);
44031
43595
  }
44032
43596
  let info;
@@ -44050,13 +43614,13 @@ async function checkLinkDirectories(path, absent) {
44050
43614
  return;
44051
43615
  throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
44052
43616
  }
44053
- at = isAbsolute2(target) ? target : `${dirname3(at)}/${target}`;
43617
+ at = isAbsolute(target) ? target : `${dirname2(at)}/${target}`;
44054
43618
  }
44055
43619
  }
44056
43620
  async function readDeviceLogin(path) {
44057
43621
  const absent = () => new Error(`this machine has no device login: ${DEVICE_LOGIN_FILE_NAMED} is not there; log this machine in with: ${DEVICE_LOGIN_COMMAND}`);
44058
43622
  const failed = (error) => new Error(`read ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
44059
- await checkLoginDirectory(dirname3(path), absent);
43623
+ await checkLoginDirectory(dirname2(path), absent);
44060
43624
  await checkLinkDirectories(path, absent);
44061
43625
  let handle;
44062
43626
  try {
@@ -44125,7 +43689,8 @@ async function readDeviceLogin(path) {
44125
43689
  expiresAt,
44126
43690
  broker,
44127
43691
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
44128
- accessExpiresAt: accessUsable ? accessExpiresAt : null
43692
+ accessExpiresAt: accessUsable ? accessExpiresAt : null,
43693
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
44129
43694
  };
44130
43695
  }
44131
43696
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -44149,7 +43714,7 @@ async function keptCopy(temp, path, error) {
44149
43714
  return new KeptCopyError(suffix, error);
44150
43715
  }
44151
43716
  async function saveDeviceLogin(path, login, held, keep = false) {
44152
- const dir = dirname3(path);
43717
+ const dir = dirname2(path);
44153
43718
  const data = JSON.stringify({
44154
43719
  key: login.key.export({ format: "der", type: "pkcs8" }).toString("base64"),
44155
43720
  credential_id: login.credentialId,
@@ -44158,13 +43723,14 @@ async function saveDeviceLogin(path, login, held, keep = false) {
44158
43723
  broker: login.broker,
44159
43724
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
44160
43725
  access_token: login.accessToken,
44161
- access_expires_at: login.accessExpiresAt.toISOString()
43726
+ access_expires_at: login.accessExpiresAt.toISOString(),
43727
+ ...login.accessLifeSeconds === null ? {} : { access_life_seconds: login.accessLifeSeconds }
44162
43728
  }
44163
43729
  });
44164
43730
  await deviceLoginPlace(path);
44165
43731
  await removeUntouched(dir, isTemporaryCopy);
44166
43732
  await removeLeftLocks(path);
44167
- const temp = join4(dir, `.device-login-${randomUUID2()}.json.tmp`);
43733
+ const temp = join3(dir, `.device-login-${randomUUID2()}.json.tmp`);
44168
43734
  const saveFailed = (error) => new Error(`save ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
44169
43735
  let whole = false;
44170
43736
  try {
@@ -44280,6 +43846,11 @@ async function importDpopKey(pkcs8Pem, name) {
44280
43846
  // ../cipher-client/src/device-login.ts
44281
43847
  var BROKER_SETTING = "AGENT_SECRETS_URL";
44282
43848
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
43849
+ function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
43850
+ if (leastLifeMs === undefined || lifeSeconds === null)
43851
+ return ACCESS_MARGIN_MS;
43852
+ return Math.max(ACCESS_MARGIN_MS, Math.min(leastLifeMs, lifeSeconds * 1000 / 2));
43853
+ }
44283
43854
  var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
44284
43855
  var DEFAULT_POLL_SECONDS = 5;
44285
43856
  var LEAST_POLL_SECONDS = 1;
@@ -44355,7 +43926,8 @@ function loginOf(key, broker, answered, now) {
44355
43926
  expiresAt,
44356
43927
  broker,
44357
43928
  accessToken: holdSecret(answered.access_token, accessExpiresAt),
44358
- accessExpiresAt
43929
+ accessExpiresAt,
43930
+ accessLifeSeconds: seconds
44359
43931
  };
44360
43932
  }
44361
43933
  async function startDeviceLogin(options) {
@@ -44487,7 +44059,7 @@ class DeviceLoginIdentity {
44487
44059
  }
44488
44060
  return this.#key;
44489
44061
  }
44490
- async spend(trade, signal) {
44062
+ async spend(trade, signal, leastLifeMs) {
44491
44063
  const { thumbprint } = await this.#loaded();
44492
44064
  return await withDeviceLoginLock(this.#path, async (held) => {
44493
44065
  let login = await readDeviceLogin(this.#path);
@@ -44499,7 +44071,8 @@ class DeviceLoginIdentity {
44499
44071
  }
44500
44072
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
44501
44073
  const expires = login.accessExpiresAt?.getTime() ?? 0;
44502
- let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
44074
+ const least = leastAccessLifeMs(leastLifeMs, login.accessLifeSeconds);
44075
+ let refreshed = login.accessToken === "" || expires - Date.now() < least;
44503
44076
  if (refreshed)
44504
44077
  login = await refresh();
44505
44078
  while (true) {
@@ -44756,241 +44329,805 @@ function poolIdentity(options) {
44756
44329
  let answer;
44757
44330
  let text;
44758
44331
  try {
44759
- answer = await send(endpoint, {
44760
- method: "POST",
44761
- headers: {
44762
- "Content-Type": "application/json",
44763
- ...bearer === "" ? {} : { Authorization: `Bearer ${bearer}` }
44764
- },
44765
- body: JSON.stringify(body),
44766
- signal: AbortSignal.any(signals),
44767
- redirect: "manual"
44332
+ answer = await send(endpoint, {
44333
+ method: "POST",
44334
+ headers: {
44335
+ "Content-Type": "application/json",
44336
+ ...bearer === "" ? {} : { Authorization: `Bearer ${bearer}` }
44337
+ },
44338
+ body: JSON.stringify(body),
44339
+ signal: AbortSignal.any(signals),
44340
+ redirect: "manual"
44341
+ });
44342
+ text = await answerText(answer);
44343
+ } catch (error) {
44344
+ throw new Error(`no answer: ${errorClass(error)}`);
44345
+ }
44346
+ if (answer.status < 200 || answer.status > 299) {
44347
+ throw new Error(`HTTP ${answer.status}${googleErrorCode(text)}`);
44348
+ }
44349
+ let parsed;
44350
+ try {
44351
+ parsed = JSON.parse(text);
44352
+ } catch {
44353
+ throw new Error(`HTTP ${answer.status}: the answer is not JSON`);
44354
+ }
44355
+ const value = typeof parsed === "object" && parsed !== null ? parsed[member] : undefined;
44356
+ return typeof value === "string" ? value : "";
44357
+ };
44358
+ const federate = async (subject, signal) => {
44359
+ let federated;
44360
+ try {
44361
+ federated = await call(securityTokenService, "", {
44362
+ audience: options.audience,
44363
+ grantType: GRANT_TYPE_TOKEN_EXCHANGE,
44364
+ requestedTokenType: REQUESTED_TOKEN_TYPE,
44365
+ scope: SCOPE,
44366
+ subjectTokenType: poolSubjectTokenType(subject.tokenType),
44367
+ subjectToken: subject.token
44368
+ }, "access_token", signal);
44369
+ } catch (error) {
44370
+ throw new Error(`trade this machine's credential at the security token service ${securityTokenServiceShown}: ${messageOf(error)}`);
44371
+ }
44372
+ if (federated === "") {
44373
+ throw new Error(`the security token service ${securityTokenServiceShown} answered no access_token`);
44374
+ }
44375
+ return federated;
44376
+ };
44377
+ const generateIdToken = async (federated, signal) => {
44378
+ let token;
44379
+ try {
44380
+ token = await call(mintEndpoint, federated, { audience: options.tokenAudience, includeEmail: true }, "token", signal);
44381
+ } catch (error) {
44382
+ throw new Error(`mint this machine's identity token at ${mintEndpointShown}: ${messageOf(error)}`);
44383
+ }
44384
+ if (token === "")
44385
+ throw new Error(`generateIdToken at ${mintEndpointShown} answered no token`);
44386
+ return token;
44387
+ };
44388
+ return {
44389
+ async read(signal) {
44390
+ let subject;
44391
+ try {
44392
+ subject = await options.subject.read(signal);
44393
+ } catch (error) {
44394
+ throw new Error(`read the credential the workload identity pool federates: ${messageOf(error)}`, { cause: error });
44395
+ }
44396
+ const federated = await federate(subject, signal);
44397
+ return {
44398
+ token: await generateIdToken(federated, signal),
44399
+ tokenType: SUBJECT_TOKEN_TYPE_GOOGLE
44400
+ };
44401
+ },
44402
+ describe: () => `a Google identity token for ${options.tokenAudience} minted through the workload identity pool ${options.audience} as ${options.serviceAccount}`
44403
+ };
44404
+ }
44405
+
44406
+ // ../cipher-client/src/projected-token.ts
44407
+ import { readFile as readFile3 } from "fs/promises";
44408
+ function projectedToken(path, variable) {
44409
+ const named = `the projected service-account token ${variable} names`;
44410
+ return {
44411
+ async read(signal) {
44412
+ let contents;
44413
+ try {
44414
+ contents = await readFile3(path, {
44415
+ encoding: "utf8",
44416
+ ...signal === undefined ? {} : { signal }
44417
+ });
44418
+ } catch (error) {
44419
+ throw new Error(`read ${named}: ${readErrorCode(error)}`);
44420
+ }
44421
+ const token = contents.trim();
44422
+ if (token === "")
44423
+ throw new Error(`${named} is empty`);
44424
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
44425
+ },
44426
+ describe: () => named
44427
+ };
44428
+ }
44429
+
44430
+ // ../cipher-client/src/environment.ts
44431
+ var BROKER_URL_VAR = "AGENT_SECRETS_URL";
44432
+ var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
44433
+ var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
44434
+ var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
44435
+ var SESSION_VAR = "AGENT_SECRETS_SESSION";
44436
+ var PROJECTS_VAR = "AGENT_SECRETS_PROJECTS";
44437
+ var MAX_PROJECTS = 16;
44438
+ var POOL_AUDIENCE_VAR = "AGENT_SECRETS_POOL_AUDIENCE";
44439
+ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
44440
+ var IDENTITY_KUBERNETES = "kubernetes";
44441
+ var IDENTITY_METADATA = "metadata";
44442
+ var IDENTITY_POOL = "pool";
44443
+ var IDENTITY_DEVICE_LOGIN = "device-login";
44444
+ var BROKER_VARIABLES = [
44445
+ BROKER_URL_VAR,
44446
+ IDENTITY_VAR,
44447
+ MACHINE_TOKEN_FILE_VAR,
44448
+ MACHINE_AUDIENCE_VAR,
44449
+ SESSION_VAR,
44450
+ PROJECTS_VAR,
44451
+ POOL_AUDIENCE_VAR,
44452
+ POOL_ACCOUNT_VAR,
44453
+ DEVICE_LOGIN_FILE_VAR,
44454
+ SIGNIN_DIR_VAR,
44455
+ "XDG_STATE_HOME",
44456
+ "HOME",
44457
+ PERSON_VAR,
44458
+ PERSON_TRADE_VAR,
44459
+ SIGNIN_ISSUER_VAR,
44460
+ SIGNIN_CLIENT_ID_VAR,
44461
+ SIGNIN_CLIENT_SECRET_FILE_VAR
44462
+ ];
44463
+ function value(env, name) {
44464
+ return (env[name] ?? "").trim();
44465
+ }
44466
+ function required2(env, name, kind) {
44467
+ const named = value(env, name);
44468
+ if (named === "")
44469
+ throw new Error(`${name} is required by ${IDENTITY_VAR}=${kind}`);
44470
+ return named;
44471
+ }
44472
+ function machineIdentity(env) {
44473
+ const kind = value(env, IDENTITY_VAR);
44474
+ switch (kind) {
44475
+ case "":
44476
+ return;
44477
+ case IDENTITY_KUBERNETES:
44478
+ return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind), MACHINE_TOKEN_FILE_VAR);
44479
+ case IDENTITY_METADATA:
44480
+ return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
44481
+ case IDENTITY_POOL: {
44482
+ const subject = required2(env, MACHINE_TOKEN_FILE_VAR, kind);
44483
+ const tokenAudience = required2(env, MACHINE_AUDIENCE_VAR, kind);
44484
+ const audience = required2(env, POOL_AUDIENCE_VAR, kind);
44485
+ const serviceAccount = required2(env, POOL_ACCOUNT_VAR, kind);
44486
+ return poolIdentity({
44487
+ subject: projectedToken(subject, MACHINE_TOKEN_FILE_VAR),
44488
+ audience,
44489
+ serviceAccount,
44490
+ tokenAudience
44491
+ });
44492
+ }
44493
+ case IDENTITY_DEVICE_LOGIN: {
44494
+ const brokerUrl = required2(env, BROKER_URL_VAR, kind);
44495
+ return new DeviceLoginIdentity({ path: deviceLoginFile(env), brokerUrl });
44496
+ }
44497
+ default:
44498
+ throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA}, ${IDENTITY_POOL} or ${IDENTITY_DEVICE_LOGIN}`);
44499
+ }
44500
+ }
44501
+ function tradeSession(env, own = "") {
44502
+ const acting = own.trim();
44503
+ return acting !== "" ? acting : value(env, SESSION_VAR);
44504
+ }
44505
+ function tradeProjects(env) {
44506
+ const keys = value(env, PROJECTS_VAR).split(/\s+/).filter((key) => key !== "");
44507
+ if (keys.length > MAX_PROJECTS) {
44508
+ throw new Error(`${PROJECTS_VAR}: ${keys.length} projects are named, and a token names at most ${MAX_PROJECTS}`);
44509
+ }
44510
+ for (const key of keys) {
44511
+ if (!PROJECT_KEY_PATTERN.test(key)) {
44512
+ throw new Error(`${PROJECTS_VAR}: "${key}" is not a project key: ${PROJECT_KEY_RULE}`);
44513
+ }
44514
+ }
44515
+ const sorted = keys.sort();
44516
+ for (let at = 1;at < sorted.length; at += 1) {
44517
+ if (sorted[at] === sorted[at - 1]) {
44518
+ throw new Error(`${PROJECTS_VAR}: ${sorted[at]} is named twice, and a list names each project once`);
44519
+ }
44520
+ }
44521
+ return sorted;
44522
+ }
44523
+ async function brokerTokenClient(env, own = "", read) {
44524
+ const brokerUrl = value(env, BROKER_URL_VAR);
44525
+ const machine = machineIdentity(env);
44526
+ if (brokerUrl === "" || machine === undefined)
44527
+ return;
44528
+ if (!isHttpUrl(brokerUrl))
44529
+ throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
44530
+ const narrowed = read === undefined ? {} : { scope: SCOPE_READ, asOf: read.asOf };
44531
+ const heldApart = async () => read === undefined ? {} : { ...narrowed, holderKey: await newDpopKey() };
44532
+ if (machine instanceof DeviceLoginIdentity) {
44533
+ if (personTradeOff(env)) {
44534
+ throw new Error(`${PERSON_TRADE_VAR}=off turns off every trade made as a person, and ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} trades this machine's device login as the person who approved it; unset one of them`);
44535
+ }
44536
+ const client = new BrokerTokenClient({
44537
+ brokerUrl,
44538
+ key: await machine.key(),
44539
+ subject: machine,
44540
+ session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
44541
+ projects: tradeProjects(env),
44542
+ ...await heldApart()
44543
+ });
44544
+ return { client, signIn: undefined };
44545
+ }
44546
+ const record = await chooseSignIn(env);
44547
+ if (record === undefined) {
44548
+ const client = new BrokerTokenClient({
44549
+ brokerUrl,
44550
+ key: await newDpopKey(),
44551
+ subject: machine,
44552
+ session: tradeSession(env, own),
44553
+ launcherCredential: false,
44554
+ ...narrowed
44555
+ });
44556
+ return { client, signIn: undefined };
44557
+ }
44558
+ const flow = await signInFlow(env);
44559
+ if (flow === undefined) {
44560
+ throw new Error(`${record.person} is signed in on this machine, and this machine configures no sign-in client to renew that sign-in with: set ${SIGNIN_CLIENT_ID_VAR} and ${SIGNIN_CLIENT_SECRET_FILE_VAR}`);
44561
+ }
44562
+ const client = new BrokerTokenClient({
44563
+ brokerUrl,
44564
+ key: await importDpopKey(record.box_key, `${record.person}'s box key`),
44565
+ subject: personIdentity(record, flow),
44566
+ actor: machine,
44567
+ session: own.trim() || signInSessionName(record),
44568
+ projects: tradeProjects(env),
44569
+ ...await heldApart()
44570
+ });
44571
+ return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
44572
+ }
44573
+
44574
+ // ../envoy-client/src/envoy-config.ts
44575
+ import {
44576
+ chmodSync,
44577
+ closeSync as closeSync2,
44578
+ existsSync,
44579
+ lstatSync,
44580
+ mkdtempSync,
44581
+ openSync as openSync2,
44582
+ readFileSync as readFileSync2,
44583
+ readlinkSync,
44584
+ rmSync,
44585
+ statSync
44586
+ } from "fs";
44587
+ import { homedir, tmpdir } from "os";
44588
+ import * as path from "path";
44589
+
44590
+ // ../envoy-client/src/errors.ts
44591
+ function dispatchCode(error) {
44592
+ if (!("fromDispatch" in error) || !("code" in error))
44593
+ return;
44594
+ const code = error.code;
44595
+ return typeof code === "string" && code !== "" ? code : undefined;
44596
+ }
44597
+ function messageFor(error) {
44598
+ if (!(error instanceof Error))
44599
+ return scrub(String(error));
44600
+ const code = dispatchCode(error);
44601
+ return scrub(code === undefined || error.message.startsWith(code) ? error.message : `${code}: ${error.message}`);
44602
+ }
44603
+ function hasErrnoCode(error, code) {
44604
+ return error instanceof Error && "code" in error && error.code === code;
44605
+ }
44606
+ var NOT_CONNECTED = new Set(["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH"]);
44607
+ function reachedNothing(error) {
44608
+ if (!(error instanceof Error))
44609
+ return false;
44610
+ const { code, syscall } = error;
44611
+ return syscall === "getaddrinfo" || typeof code === "string" && NOT_CONNECTED.has(code);
44612
+ }
44613
+
44614
+ class LoggableError extends Error {
44615
+ constructor(message) {
44616
+ super(message);
44617
+ }
44618
+ }
44619
+ var SERVER_REFUSALS = [
44620
+ "Authorization Violation",
44621
+ "User Authentication Expired",
44622
+ "Account Authentication Expired",
44623
+ "Authentication Timeout"
44624
+ ];
44625
+ var SERVER_ERROR_CODES = {
44626
+ AUTHORIZATION_VIOLATION: true,
44627
+ AUTHENTICATION_EXPIRED: true,
44628
+ AUTHENTICATION_TIMEOUT: true,
44629
+ ACCOUNT_EXPIRED: true,
44630
+ PERMISSIONS_VIOLATION: true,
44631
+ NATS_PROTOCOL_ERR: true
44632
+ };
44633
+ function serverText(code, text) {
44634
+ const said = text.trim().replace(/^'(.*)'$/s, "$1").trim().toLowerCase();
44635
+ const refusal = SERVER_REFUSALS.find((fixed) => fixed.toLowerCase() === said);
44636
+ if (refusal !== undefined)
44637
+ return refusal;
44638
+ return code === "PERMISSIONS_VIOLATION" ? "the server refused a permission (its text is withheld)" : "the server refused the connection (its text is withheld)";
44639
+ }
44640
+ function natsFailureReason(error) {
44641
+ if (error instanceof LoggableError)
44642
+ return scrub(error.message);
44643
+ if (error instanceof Error && error.name === "NatsError") {
44644
+ const { code } = error;
44645
+ if (typeof code === "string" && code !== "")
44646
+ return SERVER_ERROR_CODES[code] === true ? serverText(code, error.message) : code;
44647
+ }
44648
+ return errorClass(error);
44649
+ }
44650
+
44651
+ // ../envoy-client/src/json-position.ts
44652
+ function jsonErrorPosition(text) {
44653
+ let at = 0;
44654
+ const fail = () => {
44655
+ throw new RangeError("not JSON");
44656
+ };
44657
+ const space = () => {
44658
+ while (at < text.length && `
44659
+ \r`.includes(text.charAt(at)))
44660
+ at += 1;
44661
+ };
44662
+ const expect = (char) => {
44663
+ if (text.charAt(at) !== char)
44664
+ fail();
44665
+ at += 1;
44666
+ };
44667
+ const string = () => {
44668
+ expect('"');
44669
+ while (at < text.length) {
44670
+ const char = text.charAt(at);
44671
+ if (char === '"') {
44672
+ at += 1;
44673
+ return;
44674
+ }
44675
+ if (char < " ")
44676
+ fail();
44677
+ at += char === "\\" ? 2 : 1;
44678
+ }
44679
+ fail();
44680
+ };
44681
+ const value = () => {
44682
+ space();
44683
+ const char = text.charAt(at);
44684
+ if (char === "{" || char === "[") {
44685
+ const close = char === "{" ? "}" : "]";
44686
+ at += 1;
44687
+ space();
44688
+ if (text.charAt(at) === close) {
44689
+ at += 1;
44690
+ return;
44691
+ }
44692
+ for (;; ) {
44693
+ if (close === "}") {
44694
+ space();
44695
+ string();
44696
+ space();
44697
+ expect(":");
44698
+ }
44699
+ value();
44700
+ space();
44701
+ if (text.charAt(at) === ",") {
44702
+ at += 1;
44703
+ continue;
44704
+ }
44705
+ expect(close);
44706
+ return;
44707
+ }
44708
+ }
44709
+ if (char === '"') {
44710
+ string();
44711
+ return;
44712
+ }
44713
+ for (const word of ["true", "false", "null"]) {
44714
+ if (text.startsWith(word, at)) {
44715
+ at += word.length;
44716
+ return;
44717
+ }
44718
+ }
44719
+ const number = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(text.slice(at));
44720
+ if (number === null)
44721
+ fail();
44722
+ at += number?.[0].length ?? 0;
44723
+ };
44724
+ try {
44725
+ value();
44726
+ space();
44727
+ if (at < text.length)
44728
+ fail();
44729
+ return;
44730
+ } catch {
44731
+ const before = text.slice(0, at).split(`
44732
+ `);
44733
+ return `line ${before.length}, column ${(before.at(-1)?.length ?? 0) + 1}`;
44734
+ }
44735
+ }
44736
+
44737
+ // ../envoy-client/src/secret-file.ts
44738
+ import { readFileSync } from "fs";
44739
+ function sendable(value) {
44740
+ return !/[\s\p{Cc}]/u.test(value);
44741
+ }
44742
+ function readSecretFile(variable, filePath) {
44743
+ let contents;
44744
+ try {
44745
+ contents = readFileSync(filePath, "utf8");
44746
+ } catch (error) {
44747
+ throw new Error(`${variable} names a file that could not be read (${readErrorCode(error)})`);
44748
+ }
44749
+ const value = contents.trim();
44750
+ if (value.length === 0)
44751
+ throw new Error(`${variable} names a file that is empty`);
44752
+ if (!sendable(value)) {
44753
+ throw new Error(`${variable} names a file that holds whitespace or a control character`);
44754
+ }
44755
+ return holdSecret(value);
44756
+ }
44757
+
44758
+ // ../envoy-client/src/envoy-config.ts
44759
+ var COMMAND_TIMEOUT_MS = 1e4;
44760
+ var COMMAND_TIMEOUT_VARIABLE = "ENVOY_COMMAND_TIMEOUT_MS";
44761
+ var LONGEST_TIMEOUT_MS = 2147483647;
44762
+ function commandTimeoutMs(env) {
44763
+ const text = env[COMMAND_TIMEOUT_VARIABLE] ?? "";
44764
+ const ms = /^[1-9]\d*$/.test(text) ? Number(text) : Number.NaN;
44765
+ return ms <= LONGEST_TIMEOUT_MS ? ms : COMMAND_TIMEOUT_MS;
44766
+ }
44767
+ function nonEmpty(value) {
44768
+ return value === undefined || value === "" ? undefined : value;
44769
+ }
44770
+ function absolute(name, value) {
44771
+ if (value !== undefined && !path.isAbsolute(value)) {
44772
+ throw new Error(`${name} is ${value}, which is not an absolute path`);
44773
+ }
44774
+ return value;
44775
+ }
44776
+ function neutralConfig(env) {
44777
+ const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
44778
+ if (xdgConfigHome !== undefined && !path.isAbsolute(xdgConfigHome)) {
44779
+ return { error: `XDG_CONFIG_HOME is ${xdgConfigHome}, which is not an absolute path` };
44780
+ }
44781
+ const configHome = xdgConfigHome ?? path.join(nonEmpty(env.HOME) ?? homedir(), ".config");
44782
+ return { path: path.resolve(configHome, "legion", "envoy.json") };
44783
+ }
44784
+ var HARNESS_DIRECTORY_VARIABLE = {
44785
+ omp: "PI_CODING_AGENT_DIR",
44786
+ claude: "CLAUDE_CONFIG_DIR"
44787
+ };
44788
+ var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
44789
+ function namedDirectory(harness, env) {
44790
+ if (harness === "omp") {
44791
+ const profile = nonEmpty(env.OMP_PROFILE);
44792
+ if (profile === undefined || profile === "default")
44793
+ return;
44794
+ }
44795
+ return nonEmpty(env[HARNESS_DIRECTORY_VARIABLE[harness]]);
44796
+ }
44797
+ function harnessDirectory(harness, env) {
44798
+ if (harness === "codex")
44799
+ return;
44800
+ for (const plugin of harness === "command" ? PLUGIN_HARNESSES : [harness]) {
44801
+ if (harness === "command" && plugin === "claude" && env.CLAUDE_CODE_CHILD_SESSION !== "1") {
44802
+ continue;
44803
+ }
44804
+ const directory = namedDirectory(plugin, env);
44805
+ if (directory !== undefined)
44806
+ return absolute(HARNESS_DIRECTORY_VARIABLE[plugin], directory);
44807
+ }
44808
+ return;
44809
+ }
44810
+ function handedConfigPath(env) {
44811
+ const handed = nonEmpty(env.ENVOY_CONFIG_FILE);
44812
+ return handed === undefined ? undefined : path.resolve(absolute("ENVOY_CONFIG_FILE", handed));
44813
+ }
44814
+ function envoyConfigPath(harness, env) {
44815
+ const handedFirst = harness === "command" ? handedConfigPath(env) : undefined;
44816
+ if (handedFirst !== undefined)
44817
+ return handedFirst;
44818
+ const directory = harnessDirectory(harness, env);
44819
+ if (directory !== undefined)
44820
+ return path.resolve(directory, "envoy.json");
44821
+ const handed = handedConfigPath(env);
44822
+ if (handed !== undefined)
44823
+ return handed;
44824
+ const neutral = neutralConfig(env);
44825
+ if ("error" in neutral)
44826
+ throw new Error(neutral.error);
44827
+ return neutral.path;
44828
+ }
44829
+ var httpUrlSchema = url({ protocol: /^https?$/, error: "must be an http or https URL" });
44830
+ var DispatchSectionSchema = strictObject({
44831
+ enabled: boolean2().optional(),
44832
+ serverUrl: httpUrlSchema.optional(),
44833
+ token: string2().optional()
44834
+ });
44835
+ var EnvoySectionSchema = strictObject({
44836
+ enabled: boolean2().optional(),
44837
+ url: httpUrlSchema.optional(),
44838
+ natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
44839
+ token: string2().optional(),
44840
+ natsSeed: string2().optional(),
44841
+ natsAuth: string2().optional(),
44842
+ inbound: string2().optional()
44843
+ });
44844
+ var EnvoyFileSchema = looseObject({
44845
+ $schema: string2().optional(),
44846
+ dispatch: DispatchSectionSchema.optional(),
44847
+ envoy: EnvoySectionSchema.optional()
44848
+ });
44849
+ var CheckoutFileSchema = looseObject({
44850
+ $schema: string2().optional(),
44851
+ dispatch: DispatchSectionSchema.optional()
44852
+ });
44853
+ var AskgateSectionSchema = strictObject({ enabled: boolean2().optional() });
44854
+ function offWithNotice(notice) {
44855
+ return { enabled: false, notice, error: null };
44856
+ }
44857
+ function offWithError(error) {
44858
+ return { enabled: false, notice: null, error };
44859
+ }
44860
+ function httpUrl2(value) {
44861
+ let url2;
44862
+ try {
44863
+ url2 = new URL(value);
44864
+ } catch {
44865
+ return;
44866
+ }
44867
+ return url2.protocol === "http:" || url2.protocol === "https:" ? url2 : undefined;
44868
+ }
44869
+ function describeSchemaIssue(filePath, error) {
44870
+ const issue = error.issues[0];
44871
+ if (!issue)
44872
+ return `${filePath}: invalid envoy.json`;
44873
+ if (issue.code === "unrecognized_keys") {
44874
+ const section = issue.path.join(".");
44875
+ const keys = issue.keys.map((key) => `${section}.${key}`).join(", ");
44876
+ return `${filePath}: unrecognized ${section} key(s): ${keys}`;
44877
+ }
44878
+ return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
44879
+ }
44880
+ function danglingLink(filePath) {
44881
+ try {
44882
+ return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
44883
+ } catch {
44884
+ return null;
44885
+ }
44886
+ }
44887
+ function parseFile(filePath, schema, checkout) {
44888
+ let raw;
44889
+ try {
44890
+ raw = readFileSync2(filePath, "utf-8");
44891
+ } catch (error) {
44892
+ if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
44893
+ return { kind: "absent", link: danglingLink(filePath) };
44894
+ }
44895
+ return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
44896
+ }
44897
+ let parsedJson;
44898
+ try {
44899
+ parsedJson = JSON.parse(raw);
44900
+ } catch {
44901
+ const position = jsonErrorPosition(raw);
44902
+ return {
44903
+ kind: "invalid",
44904
+ reason: `${filePath}: invalid JSON${position === undefined ? "" : ` at ${position}`}`
44905
+ };
44906
+ }
44907
+ if (typeof parsedJson === "object" && parsedJson !== null && "natsUrls" in parsedJson) {
44908
+ return {
44909
+ kind: "invalid",
44910
+ reason: checkout ? `${filePath}: the top-level natsUrls is not read, and a checkout's envoy.json holds only a dispatch section` : `${filePath}: the top-level natsUrls is not read; move it to envoy.natsUrls`
44911
+ };
44912
+ }
44913
+ const parsed = schema.safeParse(parsedJson);
44914
+ if (!parsed.success) {
44915
+ return { kind: "invalid", reason: describeSchemaIssue(filePath, parsed.error) };
44916
+ }
44917
+ return { kind: "valid", settings: parsed.data };
44918
+ }
44919
+ var FAILURE_KEPT_MS = 60000;
44920
+ var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
44921
+ var processGlobal = globalThis;
44922
+ var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
44923
+ processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
44924
+ function runCommand(command, env, cwd) {
44925
+ const timeoutMs = commandTimeoutMs(env);
44926
+ const childEnv = {};
44927
+ for (const [name, variable] of Object.entries(env)) {
44928
+ if (variable !== undefined)
44929
+ childEnv[name] = variable;
44930
+ }
44931
+ const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
44932
+ try {
44933
+ chmodSync(directory, 448);
44934
+ const output = path.join(directory, "stdout");
44935
+ const fd = openSync2(output, "wx", 384);
44936
+ let result;
44937
+ try {
44938
+ result = Bun.spawnSync(["/bin/sh", "-c", command], {
44939
+ cwd,
44940
+ env: childEnv,
44941
+ stdin: "ignore",
44942
+ stdout: fd,
44943
+ stderr: "ignore",
44944
+ timeout: timeoutMs,
44945
+ detached: true
44768
44946
  });
44769
- text = await answerText(answer);
44770
44947
  } catch (error) {
44771
- throw new Error(`no answer: ${errorClass(error)}`);
44772
- }
44773
- if (answer.status < 200 || answer.status > 299) {
44774
- throw new Error(`HTTP ${answer.status}${googleErrorCode(text)}`);
44775
- }
44776
- let parsed;
44777
- try {
44778
- parsed = JSON.parse(text);
44779
- } catch {
44780
- throw new Error(`HTTP ${answer.status}: the answer is not JSON`);
44948
+ return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
44949
+ } finally {
44950
+ closeSync2(fd);
44781
44951
  }
44782
- const value = typeof parsed === "object" && parsed !== null ? parsed[member] : undefined;
44783
- return typeof value === "string" ? value : "";
44784
- };
44785
- const federate = async (subject, signal) => {
44786
- let federated;
44787
44952
  try {
44788
- federated = await call(securityTokenService, "", {
44789
- audience: options.audience,
44790
- grantType: GRANT_TYPE_TOKEN_EXCHANGE,
44791
- requestedTokenType: REQUESTED_TOKEN_TYPE,
44792
- scope: SCOPE,
44793
- subjectTokenType: poolSubjectTokenType(subject.tokenType),
44794
- subjectToken: subject.token
44795
- }, "access_token", signal);
44796
- } catch (error) {
44797
- throw new Error(`trade this machine's credential at the security token service ${securityTokenServiceShown}: ${messageOf(error)}`);
44798
- }
44799
- if (federated === "") {
44800
- throw new Error(`the security token service ${securityTokenServiceShown} answered no access_token`);
44953
+ process.kill(-result.pid, "SIGKILL");
44954
+ } catch {}
44955
+ if (result.exitedDueToTimeout) {
44956
+ return {
44957
+ failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
44958
+ timedOut: true
44959
+ };
44801
44960
  }
44802
- return federated;
44803
- };
44804
- const generateIdToken = async (federated, signal) => {
44805
- let token;
44806
- try {
44807
- token = await call(mintEndpoint, federated, { audience: options.tokenAudience, includeEmail: true }, "token", signal);
44808
- } catch (error) {
44809
- throw new Error(`mint this machine's identity token at ${mintEndpointShown}: ${messageOf(error)}`);
44961
+ if (!result.success) {
44962
+ return {
44963
+ failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
44964
+ timedOut: false
44965
+ };
44810
44966
  }
44811
- if (token === "")
44812
- throw new Error(`generateIdToken at ${mintEndpointShown} answered no token`);
44813
- return token;
44814
- };
44815
- return {
44816
- async read(signal) {
44817
- let subject;
44818
- try {
44819
- subject = await options.subject.read(signal);
44820
- } catch (error) {
44821
- throw new Error(`read the credential the workload identity pool federates: ${messageOf(error)}`, { cause: error });
44822
- }
44823
- const federated = await federate(subject, signal);
44967
+ const value = readFileSync2(output, "utf-8").trim();
44968
+ if (value.length === 0)
44969
+ return { failure: "printed nothing", timedOut: false };
44970
+ if (!sendable(value)) {
44824
44971
  return {
44825
- token: await generateIdToken(federated, signal),
44826
- tokenType: SUBJECT_TOKEN_TYPE_GOOGLE
44972
+ failure: "printed more than one line, or whitespace inside its value",
44973
+ timedOut: false
44827
44974
  };
44828
- },
44829
- describe: () => `a Google identity token for ${options.tokenAudience} minted through the workload identity pool ${options.audience} as ${options.serviceAccount}`
44830
- };
44975
+ }
44976
+ return { value };
44977
+ } finally {
44978
+ rmSync(directory, { recursive: true, force: true });
44979
+ }
44831
44980
  }
44832
-
44833
- // ../cipher-client/src/projected-token.ts
44834
- import { readFile as readFile3 } from "fs/promises";
44835
- function projectedToken(path, variable) {
44836
- const named = `the projected service-account token ${variable} names`;
44837
- return {
44838
- async read(signal) {
44839
- let contents;
44840
- try {
44841
- contents = await readFile3(path, {
44842
- encoding: "utf8",
44843
- ...signal === undefined ? {} : { signal }
44844
- });
44845
- } catch (error) {
44846
- throw new Error(`read ${named}: ${readErrorCode(error)}`);
44847
- }
44848
- const token = contents.trim();
44849
- if (token === "")
44850
- throw new Error(`${named} is empty`);
44851
- return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
44852
- },
44853
- describe: () => named
44854
- };
44981
+ function fileValue(value, field, filePath, env, commands = "run") {
44982
+ if (!value.startsWith("!")) {
44983
+ if (!sendable(value)) {
44984
+ throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
44985
+ }
44986
+ return value;
44987
+ }
44988
+ const command = value.slice(1);
44989
+ const cwd = path.dirname(path.resolve(filePath));
44990
+ const key = JSON.stringify([command, filePath, cwd]);
44991
+ let outcome = commandOutcomes.get(key);
44992
+ if (commands === "kept") {
44993
+ if (outcome === undefined) {
44994
+ throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
44995
+ }
44996
+ } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
44997
+ outcome = { ...runCommand(command, env, cwd), at: Date.now() };
44998
+ commandOutcomes.set(key, outcome);
44999
+ }
45000
+ if ("failure" in outcome)
45001
+ throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
45002
+ return outcome.value;
44855
45003
  }
44856
-
44857
- // ../cipher-client/src/environment.ts
44858
- var BROKER_URL_VAR = "AGENT_SECRETS_URL";
44859
- var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
44860
- var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
44861
- var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
44862
- var SESSION_VAR = "AGENT_SECRETS_SESSION";
44863
- var PROJECTS_VAR = "AGENT_SECRETS_PROJECTS";
44864
- var MAX_PROJECTS = 16;
44865
- var POOL_AUDIENCE_VAR = "AGENT_SECRETS_POOL_AUDIENCE";
44866
- var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
44867
- var IDENTITY_KUBERNETES = "kubernetes";
44868
- var IDENTITY_METADATA = "metadata";
44869
- var IDENTITY_POOL = "pool";
44870
- var IDENTITY_DEVICE_LOGIN = "device-login";
44871
- var BROKER_VARIABLES = [
44872
- BROKER_URL_VAR,
44873
- IDENTITY_VAR,
44874
- MACHINE_TOKEN_FILE_VAR,
44875
- MACHINE_AUDIENCE_VAR,
44876
- SESSION_VAR,
44877
- PROJECTS_VAR,
44878
- POOL_AUDIENCE_VAR,
44879
- POOL_ACCOUNT_VAR,
44880
- DEVICE_LOGIN_FILE_VAR,
44881
- SIGNIN_DIR_VAR,
44882
- "XDG_STATE_HOME",
44883
- "HOME",
44884
- PERSON_VAR,
44885
- PERSON_TRADE_VAR,
44886
- SIGNIN_ISSUER_VAR,
44887
- SIGNIN_CLIENT_ID_VAR,
44888
- SIGNIN_CLIENT_SECRET_FILE_VAR
44889
- ];
44890
- function value(env, name) {
44891
- return (env[name] ?? "").trim();
45004
+ function statDevice(directory) {
45005
+ try {
45006
+ return statSync(directory).dev;
45007
+ } catch {
45008
+ return;
45009
+ }
44892
45010
  }
44893
- function required2(env, name, kind) {
44894
- const named = value(env, name);
44895
- if (named === "")
44896
- throw new Error(`${name} is required by ${IDENTITY_VAR}=${kind}`);
44897
- return named;
45011
+ function moveNotice(oldFile, newFile, move, deviceOf) {
45012
+ const oldDevice = deviceOf(path.dirname(oldFile));
45013
+ let ancestor = path.dirname(newFile);
45014
+ let newDevice = deviceOf(ancestor);
45015
+ while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
45016
+ ancestor = path.dirname(ancestor);
45017
+ newDevice = deviceOf(ancestor);
45018
+ }
45019
+ if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
45020
+ return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
45021
+ }
45022
+ return `${oldFile} is not read: ${move}`;
44898
45023
  }
44899
- function machineIdentity(env) {
44900
- const kind = value(env, IDENTITY_VAR);
44901
- switch (kind) {
44902
- case "":
44903
- return;
44904
- case IDENTITY_KUBERNETES:
44905
- return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind), MACHINE_TOKEN_FILE_VAR);
44906
- case IDENTITY_METADATA:
44907
- return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
44908
- case IDENTITY_POOL: {
44909
- const subject = required2(env, MACHINE_TOKEN_FILE_VAR, kind);
44910
- const tokenAudience = required2(env, MACHINE_AUDIENCE_VAR, kind);
44911
- const audience = required2(env, POOL_AUDIENCE_VAR, kind);
44912
- const serviceAccount = required2(env, POOL_ACCOUNT_VAR, kind);
44913
- return poolIdentity({
44914
- subject: projectedToken(subject, MACHINE_TOKEN_FILE_VAR),
44915
- audience,
44916
- serviceAccount,
44917
- tokenAudience
44918
- });
44919
- }
44920
- case IDENTITY_DEVICE_LOGIN: {
44921
- const brokerUrl = required2(env, BROKER_URL_VAR, kind);
44922
- return new DeviceLoginIdentity({ path: deviceLoginFile(env), brokerUrl });
44923
- }
44924
- default:
44925
- throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA}, ${IDENTITY_POOL} or ${IDENTITY_DEVICE_LOGIN}`);
45024
+ function oldUserFileNotice(filePath, env, deviceOf) {
45025
+ const home = nonEmpty(env.HOME) ?? homedir();
45026
+ const old = path.join(home, ".config", "opencode", "envoy.json");
45027
+ if (!existsSync(old))
45028
+ return;
45029
+ const selected = path.resolve(filePath);
45030
+ const userFile = path.resolve(home, ".config", "legion", "envoy.json");
45031
+ if (selected === userFile) {
45032
+ return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
45033
+ }
45034
+ const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
45035
+ if (profileFile) {
45036
+ return `${old} is not read for this profile; copy or link it to ${filePath}, or write that file`;
45037
+ }
45038
+ const configHome = nonEmpty(env.XDG_CONFIG_HOME);
45039
+ const neutral = neutralConfig(env);
45040
+ if (configHome !== undefined && path.isAbsolute(configHome) && "path" in neutral && selected === neutral.path) {
45041
+ return `${old} is not read under XDG_CONFIG_HOME=${configHome}`;
44926
45042
  }
45043
+ return;
44927
45044
  }
44928
- function tradeSession(env, own = "") {
44929
- const acting = own.trim();
44930
- return acting !== "" ? acting : value(env, SESSION_VAR);
45045
+ function missingConfigNotice(filePath, missing, off) {
45046
+ const link = missing.link === null ? "" : ` (a link to ${missing.link}, which does not exist)`;
45047
+ const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
45048
+ return `no envoy.json at ${filePath}${link}: ${off}${old}`;
44931
45049
  }
44932
- function tradeProjects(env) {
44933
- const keys = value(env, PROJECTS_VAR).split(/\s+/).filter((key) => key !== "");
44934
- if (keys.length > MAX_PROJECTS) {
44935
- throw new Error(`${PROJECTS_VAR}: ${keys.length} projects are named, and a token names at most ${MAX_PROJECTS}`);
45050
+ function readEnvoyConfig(filePath, env, options) {
45051
+ const deviceOf = options.deviceOf ?? statDevice;
45052
+ const chosen = parseFile(filePath, EnvoyFileSchema, false);
45053
+ if (chosen.kind === "invalid")
45054
+ return { kind: "failed", path: filePath, error: chosen.reason };
45055
+ const resolvedChosen = path.resolve(filePath);
45056
+ const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
45057
+ const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
45058
+ const own = chosen.kind === "valid" ? chosen.settings : {};
45059
+ let checkout = null;
45060
+ if (checkoutFile.kind === "invalid") {
45061
+ checkout = { kind: "invalid", path: checkoutPath, error: checkoutFile.reason };
45062
+ } else if (checkoutFile.kind === "valid") {
45063
+ checkout = {
45064
+ kind: "valid",
45065
+ path: checkoutPath,
45066
+ dispatch: checkoutFile.settings.dispatch ?? {},
45067
+ envoyError: Object.hasOwn(checkoutFile.settings, "envoy") ? `${checkoutPath}: envoy is not read from a checkout's envoy.json; put it in ${filePath}` : null,
45068
+ askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
45069
+ };
44936
45070
  }
44937
- for (const key of keys) {
44938
- if (!PROJECT_KEY_PATTERN.test(key)) {
44939
- throw new Error(`${PROJECTS_VAR}: "${key}" is not a project key: ${PROJECT_KEY_RULE}`);
44940
- }
45071
+ const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
45072
+ const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
45073
+ moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
45074
+ ] : [];
45075
+ const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
45076
+ return {
45077
+ kind: "read",
45078
+ path: filePath,
45079
+ dispatch: own.dispatch ?? {},
45080
+ envoy: own.envoy ?? {},
45081
+ checkout,
45082
+ missing: chosen.kind === "absent" ? {
45083
+ link: chosen.link,
45084
+ ...unreadOldUserFile === undefined ? {} : { oldUserFileNotice: unreadOldUserFile }
45085
+ } : null,
45086
+ warnings
45087
+ };
45088
+ }
45089
+
45090
+ // ../envoy-client/src/bearer.ts
45091
+ function credentialDeadline(deadline, deadlineMs) {
45092
+ const reserveMs = Math.min(1000, deadlineMs / 2);
45093
+ return AbortSignal.any([deadline, AbortSignal.timeout(Math.ceil(deadlineMs - reserveMs))]);
45094
+ }
45095
+ function bearerCredential(token) {
45096
+ holdSecret(token);
45097
+ return {
45098
+ scheme: "Bearer",
45099
+ headers: () => ({ Authorization: `Bearer ${token}` }),
45100
+ secret: () => token
45101
+ };
45102
+ }
45103
+ function bearerSource(env, section, written) {
45104
+ const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
45105
+ if (pointer !== undefined) {
45106
+ return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
44941
45107
  }
44942
- const sorted = keys.sort();
44943
- for (let at = 1;at < sorted.length; at += 1) {
44944
- if (sorted[at] === sorted[at - 1]) {
44945
- throw new Error(`${PROJECTS_VAR}: ${sorted[at]} is named twice, and a list names each project once`);
45108
+ const plain = nonEmpty(env[`${section}_TOKEN`]);
45109
+ if (plain !== undefined) {
45110
+ if (!sendable(plain)) {
45111
+ throw new Error(`${section}_TOKEN holds whitespace or a control character`);
44946
45112
  }
45113
+ return { kind: "variable", token: plain };
44947
45114
  }
44948
- return sorted;
45115
+ const bearer = written();
45116
+ return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
44949
45117
  }
44950
- async function brokerTokenClient(env, own = "") {
44951
- const brokerUrl = value(env, BROKER_URL_VAR);
44952
- const machine = machineIdentity(env);
44953
- if (brokerUrl === "" || machine === undefined)
44954
- return;
44955
- if (!isHttpUrl(brokerUrl))
44956
- throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
44957
- if (machine instanceof DeviceLoginIdentity) {
44958
- if (personTradeOff(env)) {
44959
- throw new Error(`${PERSON_TRADE_VAR}=off turns off every trade made as a person, and ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} trades this machine's device login as the person who approved it; unset one of them`);
44960
- }
44961
- const client = new BrokerTokenClient({
44962
- brokerUrl,
44963
- key: await machine.key(),
44964
- subject: machine,
44965
- session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
44966
- projects: tradeProjects(env)
44967
- });
44968
- return { client, signIn: undefined };
45118
+ function fileBearer(bearer, url, section, env, commands = "run") {
45119
+ const named = httpUrl2(url)?.origin;
45120
+ const paired = httpUrl2(bearer.server)?.origin;
45121
+ if (named !== paired) {
45122
+ throw new Error(`${section}_URL names ${named}, but ${bearer.path}'s ${bearer.field} is for ${paired}; set ${section}_TOKEN or ${section}_TOKEN_FILE for it`);
44969
45123
  }
44970
- const record = await chooseSignIn(env);
44971
- if (record === undefined) {
44972
- const client = new BrokerTokenClient({
44973
- brokerUrl,
44974
- key: await newDpopKey(),
44975
- subject: machine,
44976
- session: tradeSession(env, own),
44977
- launcherCredential: false
44978
- });
44979
- return { client, signIn: undefined };
45124
+ if (bearer.checkout && bearer.token.startsWith("!")) {
45125
+ throw new Error(`${bearer.path}: ${bearer.field} is a command, which a checkout's envoy.json cannot run`);
44980
45126
  }
44981
- const flow = await signInFlow(env);
44982
- if (flow === undefined) {
44983
- throw new Error(`${record.person} is signed in on this machine, and this machine configures no sign-in client to renew that sign-in with: set ${SIGNIN_CLIENT_ID_VAR} and ${SIGNIN_CLIENT_SECRET_FILE_VAR}`);
45127
+ if (bearer.token === "") {
45128
+ throw new Error(`${bearer.field} in ${bearer.path} must be a non-empty bearer token`);
44984
45129
  }
44985
- const client = new BrokerTokenClient({
44986
- brokerUrl,
44987
- key: await importDpopKey(record.box_key, `${record.person}'s box key`),
44988
- subject: personIdentity(record, flow),
44989
- actor: machine,
44990
- session: own.trim() || signInSessionName(record),
44991
- projects: tradeProjects(env)
44992
- });
44993
- return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
45130
+ return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
44994
45131
  }
44995
45132
 
44996
45133
  // ../envoy-client/src/broker-credential.ts
@@ -45021,11 +45158,11 @@ function forgetBrokerSession(session) {
45021
45158
  function signInName(record) {
45022
45159
  return `${record.person}\x00${record.thumbprint}`;
45023
45160
  }
45024
- function keyOf(env, own) {
45025
- return {
45026
- session: own.trim(),
45027
- variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
45028
- };
45161
+ function keyOf(env, own, read) {
45162
+ const values = BROKER_VARIABLES.map((name) => env[name]);
45163
+ if (read !== undefined)
45164
+ values.push({ read: true, asOf: read.asOf ?? "" });
45165
+ return { session: own.trim(), variables: JSON.stringify(values) };
45029
45166
  }
45030
45167
  function entryFor(key) {
45031
45168
  let sessions = CLIENTS.get(key.session);
@@ -45040,13 +45177,13 @@ function entryFor(key) {
45040
45177
  }
45041
45178
  return entry;
45042
45179
  }
45043
- async function make(env, own) {
45044
- const made = await brokerTokenClient(env, own);
45180
+ async function make(env, own, read) {
45181
+ const made = await brokerTokenClient(env, own, read);
45045
45182
  const signIn = made?.signIn;
45046
45183
  return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
45047
45184
  }
45048
- async function clientFor(env, own) {
45049
- const key = keyOf(env, own);
45185
+ async function clientFor(env, own, read) {
45186
+ const key = keyOf(env, own, read);
45050
45187
  const entry = entryFor(key);
45051
45188
  if (entry.refused.size > 0) {
45052
45189
  const record = await chooseSignIn(env);
@@ -45061,7 +45198,7 @@ async function clientFor(env, own) {
45061
45198
  }
45062
45199
  let making = entry.making;
45063
45200
  if (making === undefined) {
45064
- const started = make(env, key.session);
45201
+ const started = make(env, key.session, read);
45065
45202
  making = started;
45066
45203
  entry.making = started;
45067
45204
  started.then((made) => {
@@ -45091,13 +45228,13 @@ function untilAborted(promise, signal) {
45091
45228
  });
45092
45229
  });
45093
45230
  }
45094
- async function tradedToken(env, own, signal, waitForReady = false) {
45095
- const { entry, made } = await untilAborted(clientFor(env, own), signal);
45231
+ async function tradedToken(env, own, { signal, waitForReady = false, read }) {
45232
+ const { entry, made } = await untilAborted(clientFor(env, own, read), signal);
45096
45233
  const { client } = made;
45097
45234
  if (client === undefined) {
45098
45235
  throw new LoggableError("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
45099
45236
  }
45100
- const { session, variables } = keyOf(env, own);
45237
+ const { session, variables } = keyOf(env, own, read);
45101
45238
  try {
45102
45239
  return {
45103
45240
  token: await client.token(signal, { waitForReady }),
@@ -45112,7 +45249,7 @@ async function tradedToken(env, own, signal, waitForReady = false) {
45112
45249
  }
45113
45250
  }
45114
45251
  function brokerTokenFor(env, session) {
45115
- return (signal, waitForReady) => tradedToken(env, sessionName(session), signal, waitForReady);
45252
+ return (signal, waitForReady) => tradedToken(env, sessionName(session), { signal, waitForReady });
45116
45253
  }
45117
45254
  function dropHeld(key, token) {
45118
45255
  CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop(token);
@@ -45120,14 +45257,14 @@ function dropHeld(key, token) {
45120
45257
  function dropTradedToken(env, traded) {
45121
45258
  dropHeld(keyOf(env, traded.session), traded.token.accessToken);
45122
45259
  }
45123
- function brokerCredential(env, session) {
45260
+ function brokerCredential(env, session, read) {
45124
45261
  let presented = "";
45125
45262
  const presentedAs = new WeakMap;
45126
45263
  const own = (acting) => (acting ?? "").trim() || sessionName(session);
45127
45264
  return {
45128
45265
  scheme: "DPoP",
45129
45266
  async headers(method, url, acting, signal) {
45130
- const traded = await tradedToken(env, own(acting), signal);
45267
+ const traded = await tradedToken(env, own(acting), { signal, read });
45131
45268
  const { token, key, identity } = traded;
45132
45269
  presented = token.accessToken;
45133
45270
  const headers = {
@@ -45136,7 +45273,7 @@ function brokerCredential(env, session) {
45136
45273
  };
45137
45274
  presentedAs.set(headers, {
45138
45275
  identity,
45139
- key: keyOf(env, traded.session),
45276
+ key: keyOf(env, traded.session, read),
45140
45277
  token: token.accessToken
45141
45278
  });
45142
45279
  return headers;
@@ -45144,8 +45281,61 @@ function brokerCredential(env, session) {
45144
45281
  identity: (headers) => presentedAs.get(headers)?.identity,
45145
45282
  stale(acting, headers) {
45146
45283
  const told = headers === undefined ? undefined : presentedAs.get(headers);
45147
- dropHeld(told?.key ?? keyOf(env, own(acting)), told?.token);
45284
+ dropHeld(told?.key ?? keyOf(env, own(acting), read), told?.token);
45285
+ },
45286
+ secret: () => presented
45287
+ };
45288
+ }
45289
+
45290
+ // ../envoy-client/src/file-token-credential.ts
45291
+ import { readFileSync as readFileSync3 } from "fs";
45292
+ var TOKEN_FILE_VAR = "DISPATCH_BROKER_TOKEN_FILE";
45293
+ var DPOP_KEY_FILE_VAR = "DISPATCH_BROKER_DPOP_KEY_FILE";
45294
+ var PKCS8_LABEL = "PRIVATE KEY";
45295
+ var PKCS8_PEM = new RegExp(`^-----BEGIN ${PKCS8_LABEL}-----\\r?\\n(?:[A-Za-z0-9+/=]+\\r?\\n)+-----END ${PKCS8_LABEL}-----$`);
45296
+ function readNamed(variable, filePath) {
45297
+ try {
45298
+ return readFileSync3(filePath, "utf8");
45299
+ } catch (error) {
45300
+ throw new Error(`${variable} names ${filePath}, which could not be read (${readErrorCode(error)})`);
45301
+ }
45302
+ }
45303
+ function tokenIn(filePath) {
45304
+ const token = readNamed(TOKEN_FILE_VAR, filePath).trim();
45305
+ if (token === "") {
45306
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds no token: it is empty or blank`);
45307
+ }
45308
+ if (!sendable(token)) {
45309
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds whitespace or a control character inside its token`);
45310
+ }
45311
+ return holdSecret(token);
45312
+ }
45313
+ async function keyIn(filePath) {
45314
+ const pem = readNamed(DPOP_KEY_FILE_VAR, filePath).trim();
45315
+ if (!PKCS8_PEM.test(pem)) {
45316
+ throw new Error(`${DPOP_KEY_FILE_VAR} names ${filePath}, which does not hold one P-256 private key in PKCS#8 PEM`);
45317
+ }
45318
+ return await importDpopKey(pem, `${DPOP_KEY_FILE_VAR}'s key ${filePath}`);
45319
+ }
45320
+ function fileTokenCredential(files, dispatchUrl) {
45321
+ const origin = httpUrl2(dispatchUrl)?.origin;
45322
+ let presented = "";
45323
+ return {
45324
+ scheme: "DPoP",
45325
+ async headers(method, url) {
45326
+ const target = httpUrl2(url)?.origin;
45327
+ if (origin === undefined || target !== origin) {
45328
+ throw new Error(`the token ${TOKEN_FILE_VAR} names goes to DISPATCH_URL's origin (${origin}) alone, and this request is for ${target ?? "a URL that is not http or https"}`);
45329
+ }
45330
+ const token = tokenIn(files.tokenFile);
45331
+ const key = await keyIn(files.keyFile);
45332
+ presented = token;
45333
+ return {
45334
+ Authorization: `DPoP ${token}`,
45335
+ DPoP: await key.proof({ method, url, accessToken: token })
45336
+ };
45148
45337
  },
45338
+ stale() {},
45149
45339
  secret: () => presented
45150
45340
  };
45151
45341
  }
@@ -45194,13 +45384,19 @@ function lostDispatchUrlNotice(env, config) {
45194
45384
  ].join("; ");
45195
45385
  }
45196
45386
  function dispatchSettings(env, config, options = {}) {
45197
- const target = dispatchTarget(env, config);
45387
+ const target = dispatchTarget(env, config, options.tokenFiles === true);
45198
45388
  if (!target.enabled)
45199
45389
  return target;
45200
45390
  const { url, urlSetting, source } = target;
45201
45391
  let credential;
45202
45392
  try {
45203
- credential = source.kind === "broker" ? brokerCredential(env, options.session) : bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
45393
+ if (source.kind === "broker")
45394
+ credential = brokerCredential(env, options.session, source.read);
45395
+ else if (source.kind === "files")
45396
+ credential = fileTokenCredential(source, url);
45397
+ else {
45398
+ credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
45399
+ }
45204
45400
  } catch (error) {
45205
45401
  return offWithError(messageFor(error));
45206
45402
  }
@@ -45223,6 +45419,63 @@ function dispatchUrl(env, config) {
45223
45419
  const target = dispatchTarget(env, config);
45224
45420
  return target.enabled ? target.url : undefined;
45225
45421
  }
45422
+ var BESIDE_TOKEN_FILES = [
45423
+ "DISPATCH_TOKEN_BROKER",
45424
+ "DISPATCH_TOKEN_BROKER_READ",
45425
+ "DISPATCH_TOKEN_BROKER_AS_OF",
45426
+ "DISPATCH_TOKEN",
45427
+ "DISPATCH_TOKEN_FILE",
45428
+ BROKER_URL_VAR,
45429
+ IDENTITY_VAR
45430
+ ];
45431
+ function tokenFilesSet(env) {
45432
+ const set = [
45433
+ ...nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE) === undefined ? [] : [TOKEN_FILE_VAR],
45434
+ ...nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE) === undefined ? [] : [DPOP_KEY_FILE_VAR]
45435
+ ];
45436
+ if (set.length === 0)
45437
+ return;
45438
+ return `${set.join(" and ")} ${set.length === 1 ? "is" : "are"} set`;
45439
+ }
45440
+ function settingsBesideTokenFiles(env) {
45441
+ return BESIDE_TOKEN_FILES.filter((name) => nonEmpty(env[name]) !== undefined).map((name) => `${name} is set`);
45442
+ }
45443
+ function tokenFilesTarget(env, config, taken) {
45444
+ const set = tokenFilesSet(env);
45445
+ if (set === undefined)
45446
+ return;
45447
+ if (!taken) {
45448
+ return offWithError(`${set}, and only the dispatch command reads the token files: Dispatch is off here rather than written with another credential beside them`);
45449
+ }
45450
+ const tokenFile = nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE);
45451
+ const keyFile = nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE);
45452
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
45453
+ const { checkout } = config;
45454
+ const problems = [
45455
+ ...tokenFile === undefined ? [`${TOKEN_FILE_VAR} is not set`] : [],
45456
+ ...keyFile === undefined ? [`${DPOP_KEY_FILE_VAR} is not set`] : [],
45457
+ ...explicitUrl === undefined ? ["DISPATCH_URL is not set"] : [],
45458
+ ...settingsBesideTokenFiles(env),
45459
+ ...config.dispatch.token === undefined ? [] : [`dispatch.token is set in ${config.path}`],
45460
+ ...checkout?.kind === "valid" && checkout.dispatch.token !== undefined ? [`dispatch.token is set in ${checkout.path}`] : [],
45461
+ ...checkout?.kind === "invalid" ? [`${checkout.error}, so whether it sets dispatch.token cannot be told`] : []
45462
+ ];
45463
+ if (problems.length > 0 || tokenFile === undefined || keyFile === undefined || explicitUrl === undefined) {
45464
+ return offWithError(`${TOKEN_FILE_VAR} and ${DPOP_KEY_FILE_VAR} go together, with DISPATCH_URL, as the dispatch command's only Dispatch credential: ${problems.join("; ")}`);
45465
+ }
45466
+ if (config.dispatch.enabled === false) {
45467
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
45468
+ }
45469
+ if (httpUrl2(explicitUrl) === undefined) {
45470
+ return offWithError("DISPATCH_URL must be an http or https URL");
45471
+ }
45472
+ return {
45473
+ enabled: true,
45474
+ url: withoutTrailingSlashes(explicitUrl),
45475
+ urlSetting: "DISPATCH_URL",
45476
+ source: { kind: "files", tokenFile, keyFile }
45477
+ };
45478
+ }
45226
45479
  function brokerRouteForced(env) {
45227
45480
  const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
45228
45481
  if (written === "")
@@ -45231,12 +45484,55 @@ function brokerRouteForced(env) {
45231
45484
  return true;
45232
45485
  return offWithError("DISPATCH_TOKEN_BROKER takes 1: set it to 1 where this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and leave it unset where a bearer is read as usual");
45233
45486
  }
45234
- function dispatchTarget(env, config) {
45487
+ var CUT_FORM = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
45488
+ var ZERO_TIME = Date.parse("0001-01-01T00:00:00.000Z");
45489
+ function isCut(text) {
45490
+ const parts = CUT_FORM.exec(text);
45491
+ if (parts === null)
45492
+ return false;
45493
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = parts.slice(1, 7).map((part) => Number(part ?? "0"));
45494
+ const [zoneHour = 0, zoneMinute = 0] = parts.slice(9, 11).map((part) => Number(part ?? "0"));
45495
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
45496
+ const exists = month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth && hour <= 23 && minute <= 59 && second <= 59 && zoneHour <= 23 && zoneMinute <= 59;
45497
+ if (!exists)
45498
+ return false;
45499
+ const offset = (parts[8] === "-" ? -1 : 1) * (zoneHour * 60 + zoneMinute);
45500
+ const instant = new Date(0);
45501
+ instant.setUTCFullYear(year, month - 1, day);
45502
+ instant.setUTCHours(hour, minute - offset, second, 0);
45503
+ return Number(parts[7] ?? "0") !== 0 || instant.getTime() !== ZERO_TIME;
45504
+ }
45505
+ function readTradeSetting(env) {
45506
+ const read = (env.DISPATCH_TOKEN_BROKER_READ ?? "").trim();
45507
+ const cut = (env.DISPATCH_TOKEN_BROKER_AS_OF ?? "").trim();
45508
+ if (read !== "" && read !== "1") {
45509
+ return offWithError("DISPATCH_TOKEN_BROKER_READ takes 1: set it to 1 where this session's Dispatch credential is a broker token that only reads, and leave it unset where it writes");
45510
+ }
45511
+ if (read === "") {
45512
+ if (cut === "")
45513
+ return;
45514
+ return offWithError("DISPATCH_TOKEN_BROKER_AS_OF names the cut a read-only token reads at, and goes only beside DISPATCH_TOKEN_BROKER_READ=1: set DISPATCH_TOKEN_BROKER_READ to 1 beside it, or unset DISPATCH_TOKEN_BROKER_AS_OF");
45515
+ }
45516
+ if (cut === "")
45517
+ return {};
45518
+ if (!isCut(cut)) {
45519
+ return offWithError("DISPATCH_TOKEN_BROKER_AS_OF is not an RFC 3339 time with at most six fractional digits and Z or a numeric offset, such as 1999-12-31T23:59:59Z");
45520
+ }
45521
+ return { asOf: cut };
45522
+ }
45523
+ function dispatchTarget(env, config, tokenFiles = false) {
45235
45524
  if (config.kind === "failed")
45236
45525
  return offWithError(config.error);
45237
- const forced = brokerRouteForced(env);
45238
- if (typeof forced !== "boolean")
45239
- return forced;
45526
+ const files = tokenFilesTarget(env, config, tokenFiles);
45527
+ if (files !== undefined)
45528
+ return files;
45529
+ const brokerOnly = brokerRouteForced(env);
45530
+ if (typeof brokerOnly !== "boolean")
45531
+ return brokerOnly;
45532
+ const read = readTradeSetting(env);
45533
+ if (read !== undefined && "enabled" in read)
45534
+ return read;
45535
+ const forced = brokerOnly || read !== undefined;
45240
45536
  const explicitUrl = nonEmpty(env.DISPATCH_URL);
45241
45537
  const checkoutFile = explicitUrl === undefined ? config.checkout : null;
45242
45538
  if (checkoutFile?.kind === "invalid")
@@ -45278,10 +45574,10 @@ function dispatchTarget(env, config) {
45278
45574
  if (route.traded) {
45279
45575
  const brokered = withoutTrailingSlashes(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
45280
45576
  const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
45281
- return { enabled: true, url: brokered, urlSetting, source: { kind: "broker" } };
45577
+ return { enabled: true, url: brokered, urlSetting, source: { kind: "broker", read } };
45282
45578
  }
45283
45579
  if (forced) {
45284
- return offWithError(`DISPATCH_TOKEN_BROKER is set, so this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
45580
+ return offWithError(`${read === undefined ? "DISPATCH_TOKEN_BROKER" : "DISPATCH_TOKEN_BROKER_READ"} is set, so this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
45285
45581
  }
45286
45582
  return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
45287
45583
  }
@@ -45461,18 +45757,22 @@ var DISPATCH_URL_SETTING = "the configured Dispatch URL";
45461
45757
  class DispatchServiceError extends Error {
45462
45758
  code;
45463
45759
  status;
45760
+ name = "DispatchServiceError";
45761
+ fromDispatch = true;
45464
45762
  candidates;
45465
45763
  current;
45466
45764
  mismatches;
45467
- name = "DispatchServiceError";
45468
- fromDispatch = true;
45469
- constructor(code, status, message, candidates, current, mismatches) {
45765
+ issues;
45766
+ changed;
45767
+ constructor(code, status, message, details = {}) {
45470
45768
  super(message);
45471
45769
  this.code = code;
45472
45770
  this.status = status;
45473
- this.candidates = candidates;
45474
- this.current = current;
45475
- this.mismatches = mismatches;
45771
+ this.candidates = details.candidates;
45772
+ this.current = details.current;
45773
+ this.mismatches = details.mismatches;
45774
+ this.issues = details.issues;
45775
+ this.changed = details.changed;
45476
45776
  }
45477
45777
  }
45478
45778
 
@@ -45573,6 +45873,9 @@ function reviewNoRouteRefusal(baseUrl, route, version) {
45573
45873
  function resultDryRunNoRouteRefusal(baseUrl, route) {
45574
45874
  return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${urlForText(baseUrl, DISPATCH_URL_SETTING)} answered no route for ${route} each ` + "time the dry run was sent: this build is older than a result's dry run, so it cannot show " + "the pull-request body line before the record. Nothing was recorded.");
45575
45875
  }
45876
+ function statusChangeNoRouteRefusal(baseUrl, route) {
45877
+ return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${urlForText(baseUrl, DISPATCH_URL_SETTING)} answered no route for ${route} each ` + "time the status change was sent. This build is older than that route, so it takes no " + "include_children, unlink_children or include_parent, and nothing changed. No PATCH was " + "sent in its place, since a PATCH would write the status without the option.");
45878
+ }
45576
45879
  var ISSUE_EVENTS_PAGE_MAX = 200;
45577
45880
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
45578
45881
  function requestSignal(signal, deadlineMs) {
@@ -45891,6 +46194,14 @@ class DispatchClient {
45891
46194
  async updateIssue(issue, input) {
45892
46195
  return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
45893
46196
  }
46197
+ async changeIssueStatus(issue, input) {
46198
+ const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "status-change"];
46199
+ try {
46200
+ return await this.#json("POST", path, input);
46201
+ } catch (error) {
46202
+ throw this.#refusalOfNoRoute(error, path, (route) => statusChangeNoRouteRefusal(this.#baseUrl, route));
46203
+ }
46204
+ }
45894
46205
  async claimIssue(issue, input = {}) {
45895
46206
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
45896
46207
  }
@@ -46045,10 +46356,7 @@ class DispatchClient {
46045
46356
  try {
46046
46357
  return await this.#json("POST", path, body);
46047
46358
  } catch (error) {
46048
- if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
46049
- throw error;
46050
- const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
46051
- throw reviewNoRouteRefusal(this.#baseUrl, route, version);
46359
+ throw this.#refusalOfNoRoute(error, path, (route) => reviewNoRouteRefusal(this.#baseUrl, route, version));
46052
46360
  }
46053
46361
  }
46054
46362
  async recordResult(issue, input) {
@@ -46059,10 +46367,7 @@ class DispatchClient {
46059
46367
  try {
46060
46368
  return await this.#writingNothing(path, input, { writes: false });
46061
46369
  } catch (error) {
46062
- if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
46063
- throw error;
46064
- const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
46065
- throw resultDryRunNoRouteRefusal(this.#baseUrl, route);
46370
+ throw this.#refusalOfNoRoute(error, path, (route) => resultDryRunNoRouteRefusal(this.#baseUrl, route));
46066
46371
  }
46067
46372
  }
46068
46373
  async issueResults(issue, at) {
@@ -46307,6 +46612,11 @@ class DispatchClient {
46307
46612
  sleep: this.#sleep
46308
46613
  });
46309
46614
  }
46615
+ #refusalOfNoRoute(error, path, refuse) {
46616
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
46617
+ return error;
46618
+ return refuse(`POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`);
46619
+ }
46310
46620
  #writeCall(method, url, key, writes = true) {
46311
46621
  if (method !== "POST" && method !== "PATCH")
46312
46622
  return;
@@ -46640,7 +46950,7 @@ class DispatchClient {
46640
46950
  if (response.status === 409 && error.code === IDEMPOTENCY_KEY_COMMITTED) {
46641
46951
  throw new DispatchWriteLandedError(IDEMPOTENCY_KEY_COMMITTED, response.status, method, requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING));
46642
46952
  }
46643
- throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error.candidates, error.current, error.mismatches);
46953
+ throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error);
46644
46954
  }
46645
46955
  throw this.#gatewayError(method, url, response, text, "Dispatch's error JSON");
46646
46956
  }
@@ -46711,7 +47021,7 @@ import {
46711
47021
  mkdirSync as mkdirSync3,
46712
47022
  openSync as openSync4,
46713
47023
  readdirSync as readdirSync2,
46714
- readFileSync as readFileSync5,
47024
+ readFileSync as readFileSync6,
46715
47025
  readSync as readSync2,
46716
47026
  rmSync as rmSync4,
46717
47027
  statSync as statSync3,
@@ -46727,7 +47037,7 @@ import {
46727
47037
  mkdirSync,
46728
47038
  openSync as openSync3,
46729
47039
  readdirSync,
46730
- readFileSync as readFileSync3,
47040
+ readFileSync as readFileSync4,
46731
47041
  readlinkSync as readlinkSync2,
46732
47042
  renameSync as renameSync2,
46733
47043
  rmSync as rmSync3,
@@ -46802,7 +47112,7 @@ function bytesDigest(bytes) {
46802
47112
  }
46803
47113
  function processStart(pid) {
46804
47114
  try {
46805
- const stat = readFileSync3(`/proc/${pid}/stat`, "utf-8");
47115
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf-8");
46806
47116
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null;
46807
47117
  } catch {
46808
47118
  return null;
@@ -46907,7 +47217,7 @@ function recordNamesStore(dir) {
46907
47217
  if (!name.endsWith(OWNER_FILE))
46908
47218
  continue;
46909
47219
  try {
46910
- const parsed = parseOwner(readFileSync3(join6(record, name), "utf-8"));
47220
+ const parsed = parseOwner(readFileSync4(join6(record, name), "utf-8"));
46911
47221
  if (parsed === undefined)
46912
47222
  return true;
46913
47223
  statSync2(parsed.owner.store);
@@ -46936,7 +47246,7 @@ function askgateState(dir, now = Date.now()) {
46936
47246
  const file = join6(record, name);
46937
47247
  let text;
46938
47248
  try {
46939
- text = readFileSync3(file, "utf-8");
47249
+ text = readFileSync4(file, "utf-8");
46940
47250
  } catch (error) {
46941
47251
  if (hasErrnoCode(error, "ENOENT"))
46942
47252
  continue;
@@ -46974,7 +47284,7 @@ function readMarker(file) {
46974
47284
  try {
46975
47285
  const fd = openSync3(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
46976
47286
  try {
46977
- text = readFileSync3(fd, "utf-8");
47287
+ text = readFileSync4(fd, "utf-8");
46978
47288
  } finally {
46979
47289
  closeSync3(fd);
46980
47290
  }
@@ -51391,6 +51701,7 @@ var pictureSendingTools = {
51391
51701
  };
51392
51702
  var refGrammarProblem = "ref must be a valid dispatch:// reference such as dispatch://KEY-1, " + "dispatch://KEY-1/ask/<uuid>, dispatch://KEY-1/comment/<uuid>, " + "dispatch://KEY-1/message/<uuid>, dispatch://KEY-1/artifact/<slug>, " + "dispatch://PROJECT/artifact/<document-ref> (an artifact id, slug, or filename), " + "dispatch://KEY-1/spec#b-<block id>, dispatch://KEY-1/artifact/<slug>#b-<block id> or " + "dispatch://PROJECT/artifact/<slug>#b-<block id> (one block of a document, its id " + "percent-encoded, optionally pinned to a version of the document with @v<N> after it; for " + "dispatch read), dispatch://KEY-1/ask/<uuid>#b-<part id> or " + "dispatch://PROJECT/artifact/<slug>/ask/<uuid>#b-<part id> (one part of an ask: its question, " + "one of its options or its answer, optionally pinned to a revision of the ask's parts with " + "@v<N> after it; for dispatch read), dispatch://KEY-1/comment/<uuid>#b-<block id>, " + "dispatch://PROJECT/artifact/<slug>/comment/<uuid>#b-<block id> or " + "dispatch://KEY-1/message/<uuid>#b-<block id> (one block of a comment or message, a " + "comment's optionally pinned to a revision of the comment with @v<N> after it; for dispatch " + "read), or " + "dispatch://agent/<session id>/artifact/<slug> (a picture in a conversation on the Agents page, " + "for dispatch doc-read); a dashboard URL on this Dispatch server is accepted too";
51393
51703
  var ownerRequiredProblem = "issue is required; supply issue or set LEGION_ISSUE";
51704
+ var ownerStandInIssue = "OWNER-1";
51394
51705
  function argumentProblems(tool, args) {
51395
51706
  const problems = [];
51396
51707
  switch (tool) {
@@ -51676,7 +51987,7 @@ async function resolveOwnerArguments(tool, input, cwd, env, exec, dashboardUrls,
51676
51987
  const legionIssue = env.LEGION_ISSUE;
51677
51988
  if (!legionIssue) {
51678
51989
  problems.push(ownerRequiredProblem);
51679
- return { args, ref, owner: null };
51990
+ return { args, ref, owner: null, ownerMissing: true };
51680
51991
  }
51681
51992
  if (nativeIssueKeyPattern.test(legionIssue) || externalIssueRefPattern.test(legionIssue)) {
51682
51993
  const issue = canonicalExternalIssueRef(legionIssue);
@@ -51684,18 +51995,24 @@ async function resolveOwnerArguments(tool, input, cwd, env, exec, dashboardUrls,
51684
51995
  }
51685
51996
  if (!bareIssueNumberPattern.test(legionIssue)) {
51686
51997
  problems.push("LEGION_ISSUE must be a native issue key (e.g. LEGION-3), an external owner/repo#n reference, or a bare positive issue number");
51687
- return { args, ref, owner: null };
51998
+ return { args, ref, owner: null, ownerMissing: true };
51688
51999
  }
51689
52000
  const repo = await resolveCwdRepo(cwd, exec);
51690
52001
  if (!repo) {
51691
52002
  problems.push("issue is required; LEGION_ISSUE needs a GitHub repository in cwd");
51692
- return { args, ref, owner: null };
52003
+ return { args, ref, owner: null, ownerMissing: true };
51693
52004
  }
51694
52005
  const issue = `${repo}#${legionIssue}`;
51695
52006
  return { args: { ...args, issue }, ref, owner: { kind: "issue", issue } };
51696
52007
  }
51697
- function restatesMissingOwner(issue) {
51698
- return issue.code === "invalid_type" && issue.path.length === 1 && issue.path[0] === "issue" && issue.input === undefined || issue.code === "custom" && issue.path.length === 0 && (issue.message.startsWith("Exactly one of issue and project is required") || issue.message.startsWith("issue is required unless in_reply_to"));
52008
+ function withoutMissingOwner(issue) {
52009
+ if (issue.code === "invalid_type" && issue.path.length === 1 && issue.path[0] === "issue" && issue.input === undefined) {
52010
+ return;
52011
+ }
52012
+ if (issue.code !== "custom" || issue.path.length !== 0)
52013
+ return issue;
52014
+ const message = withoutOwnerRule(issue.message);
52015
+ return message === undefined ? undefined : message === issue.message ? issue : { ...issue, message };
51699
52016
  }
51700
52017
  function dispatchServerUrls(config) {
51701
52018
  return config.publicUrl === undefined ? [config.url] : [config.url, config.publicUrl];
@@ -51706,11 +52023,12 @@ async function checkDispatchCall(input) {
51706
52023
  const owner = await resolveOwnerArguments(tool, args, cwd, input.env ?? process.env, input.exec ?? defaultExec, input.serverUrls, problems);
51707
52024
  const conflicts = issueFreeTools[tool] === true ? [] : ownerConflictProblems(tool, args, owner.ref, optionalString(owner.args, "ref"));
51708
52025
  problems.push(...conflicts);
51709
- const ownerMissing = issueFreeTools[tool] !== true && (owner.owner === null || conflicts.length > 0);
52026
+ const ownerAlreadySaid = issueFreeTools[tool] !== true && (owner.owner === null || conflicts.length > 0);
51710
52027
  const schema = toolSchema(tool);
51711
- const parsed = schema.safeParse(owner.args, { reportInput: true });
52028
+ const standIn = owner.ownerMissing === true;
52029
+ const parsed = schema.safeParse(standIn ? { ...owner.args, issue: ownerStandInIssue } : owner.args, { reportInput: true });
51712
52030
  if (!parsed.success) {
51713
- const issues = ownerMissing ? parsed.error.issues.filter((issue) => !restatesMissingOwner(issue)) : parsed.error.issues;
52031
+ const issues = standIn ? parsed.error.issues : ownerAlreadySaid ? parsed.error.issues.flatMap((issue) => withoutMissingOwner(issue) ?? []) : parsed.error.issues;
51714
52032
  problems.push(...formatZodIssues(issues, schema, tool));
51715
52033
  }
51716
52034
  problems.push(...argumentProblems(tool, owner.args));
@@ -51718,7 +52036,7 @@ async function checkDispatchCall(input) {
51718
52036
  return {
51719
52037
  problems,
51720
52038
  owner,
51721
- args: parsed.success ? parsed.data : owner.args,
52039
+ args: parsed.success && !standIn ? parsed.data : owner.args,
51722
52040
  pictures
51723
52041
  };
51724
52042
  }
@@ -51736,7 +52054,75 @@ function refusalWithCode(error, ...clauses) {
51736
52054
  }
51737
52055
  if (!(error instanceof DispatchServiceError))
51738
52056
  return error;
51739
- return new DispatchServiceError(error.code, error.status, `${error.code}: ${error.message}${joined}`, error.candidates, error.current, error.mismatches);
52057
+ const told = joined !== "" && /[.!?]$/.test(error.message) ? `${error.message} ${suffix.charAt(0).toUpperCase()}${suffix.slice(1)}` : `${error.message}${joined}`;
52058
+ return new DispatchServiceError(error.code, error.status, `${error.code}: ${told}`, error);
52059
+ }
52060
+ function parentStatusConflictLines(error, tool, args, legionIssue) {
52061
+ if (!dispatchAnswered(error, 409) || error.code !== "PARENT_STATUS_CONFLICT")
52062
+ return;
52063
+ const issues = error.issues ?? [];
52064
+ if (issues.length === 0)
52065
+ return;
52066
+ const parents = issues.filter((issue) => issue.relation === "parent").map(({ key }) => key);
52067
+ const children = issues.filter((issue) => issue.relation === "child").map(({ key }) => key);
52068
+ return [
52069
+ messageFor(error),
52070
+ ...issues.map((issue) => `${issue.key} [${issue.status}] ${issue.title}`),
52071
+ ...nextSteps(tool, args, parents, children, legionIssue)
52072
+ ];
52073
+ }
52074
+ var CHILD_FLAGS = "dispatch issue-update --status takes --unlink-children, which removes its open children from it, or, with a status other than done, --include-children, which moves the open issues under the issue with it. A person signed in at a browser closes them with it on the issue's page.";
52075
+ var PARENT_FLAG = "dispatch issue-update --status takes --include-parent, which moves each issue above the issue that is not in work to in_progress.";
52076
+ function otherProjectSentence(named, keys) {
52077
+ const project = named === undefined ? undefined : issueProject(named);
52078
+ if (project === undefined)
52079
+ return "";
52080
+ const others = keys.filter((key) => {
52081
+ const other = issueProject(key);
52082
+ return other !== undefined && other !== project;
52083
+ });
52084
+ if (others.length === 0)
52085
+ return "";
52086
+ const one = others.length === 1;
52087
+ return ` ${others.join(", ")} ${one ? "is" : "are"} not in the project of ${named}. A credential scoped to one project is refused a step that writes ${one ? "it" : "them"} (403 PROJECT_SCOPE), so a person, or a credential that names no project, must make that step.`;
52088
+ }
52089
+ function includeParentCall(key) {
52090
+ return `${commandLine("dispatch_issue_update", { issue: key, status: "in_progress", include_parent: true })}, which also moves each issue above ${key} that is not in work`;
52091
+ }
52092
+ function nextSteps(tool, args, parents, children, legionIssue) {
52093
+ if (tool === "dispatch_issue") {
52094
+ return parents.map((key) => `dispatch issue takes no flag that moves a done parent. Reopen ${key} first, with ${includeParentCall(key)}, then run dispatch issue again; or run it with --parent naming an open issue, or with no --parent.`);
52095
+ }
52096
+ const issueUpdate = tool === "dispatch_issue_update";
52097
+ const written = issueUpdate ? args : {};
52098
+ const fields = Object.keys(written).filter((field) => field !== "issue" && written[field] !== undefined);
52099
+ const issue = optionalString(written, "issue");
52100
+ const named = issueUpdate ? issue ?? legionIssue : undefined;
52101
+ const childHolds = children.length > 0;
52102
+ const childScope = otherProjectSentence(named, children);
52103
+ const status = optionalString(written, "status");
52104
+ const parent = optionalString(written, "parent");
52105
+ const alone = `--status${status === "done" ? " and --reason" : ""} alone`;
52106
+ if (parent !== undefined && parent !== "") {
52107
+ const issueFlag = issue === undefined ? "" : ` --issue ${issue}`;
52108
+ const statusFlag = status === undefined || childHolds ? "" : ` --status ${status}`;
52109
+ const kept = fields.filter((field) => field !== "parent" && field !== "status" && !(childHolds && field === "reason"));
52110
+ const otherFlags = kept.length > 0 ? ", with the call's other flags" : "";
52111
+ const reparent = `dispatch issue-update${issueFlag} --parent ${parent}${statusFlag}${otherFlags}`;
52112
+ const afterStatus = childHolds ? ", after the status change," : "";
52113
+ return [
52114
+ ...childHolds ? [
52115
+ `${CHILD_FLAGS} Each goes with ${alone}, so run the status change first, in a call of its own, and the reparent after it: ${reparent}.${childScope}`
52116
+ ] : [],
52117
+ ...parents.map((key) => `dispatch issue-update takes no flag that moves the parent a reparent names. Move ${key} into work first, with ${includeParentCall(key)}; then${afterStatus} run the reparent again: ${reparent}.`)
52118
+ ];
52119
+ }
52120
+ const others = ISSUE_UPDATE_PATCH_FIELDS.some((field) => written[field] !== undefined);
52121
+ const apart = (subject) => others ? ` ${subject} with ${alone}, so send the call's other changes in a call of their own.` : "";
52122
+ return [
52123
+ ...childHolds ? [`${CHILD_FLAGS}${apart("Each goes")}${childScope}`] : [],
52124
+ ...parents.length > 0 ? [`${PARENT_FLAG}${apart("It goes")}${otherProjectSentence(named, parents)}`] : []
52125
+ ];
51740
52126
  }
51741
52127
  function dispatchAnswered(error, status) {
51742
52128
  return error instanceof DispatchServiceError && error.fromDispatch && error.status === status;
@@ -51761,6 +52147,11 @@ function writeMayHaveLanded(error) {
51761
52147
  return error.mayHaveReachedDispatch;
51762
52148
  return !(error instanceof DispatchServiceError) || error.status >= 500;
51763
52149
  }
52150
+ function closeAccount(error, closingNote) {
52151
+ const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
52152
+ const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
52153
+ return writeMayHaveLanded(error) ? `${posted}, and the close may or may not have taken effect. Read the issue's status before retrying: done means it closed; otherwise retry with a reason that points at message ${closingNote.id}, since retrying this call posts its reason again` : `${posted} but the issue did not close. Retrying this call posts its reason again, so ${fix}retry with a reason that points at message ${closingNote.id}`;
52154
+ }
51764
52155
  function withAccount(error, account) {
51765
52156
  const message = messageFor(error);
51766
52157
  const told = /[.!?]$/.test(message) ? `${message} ${account.charAt(0).toUpperCase()}${account.slice(1)}` : `${message}; ${account}`;
@@ -53114,6 +53505,85 @@ async function followedAskDetails(client, ask, artifact) {
53114
53505
  return { ...await askOwnerDetails(client, ask, artifact), follows: { ask: ask.id } };
53115
53506
  }
53116
53507
 
53508
+ // ../envoy-client/src/dispatch-commands/status-change.ts
53509
+ async function issuesBeforeStatusChange(client, before, options) {
53510
+ const issues = new Map([
53511
+ [before.key, { status: before.status, parent: before.parent ?? null }]
53512
+ ]);
53513
+ for (const child of before.children ?? []) {
53514
+ issues.set(child.key, { status: child.status, parent: before.key });
53515
+ }
53516
+ try {
53517
+ if (options.includes("include_children")) {
53518
+ for (const row of await client.listAllIssues({ project: before.project })) {
53519
+ issues.set(row.key, { status: row.status, parent: row.parent ?? null });
53520
+ }
53521
+ } else if (options.includes("include_parent")) {
53522
+ let parent = before.parent ?? null;
53523
+ while (parent !== null && !issues.has(parent)) {
53524
+ const above = await client.getIssue(parent);
53525
+ issues.set(above.key, { status: above.status, parent: above.parent ?? null });
53526
+ parent = above.parent ?? null;
53527
+ }
53528
+ }
53529
+ } catch (error) {
53530
+ throw refusalWithCode(error);
53531
+ }
53532
+ return issues;
53533
+ }
53534
+ async function statusChangeCommand(context, before, options, issuesBefore, closingNote) {
53535
+ const { args, client, actor, input, issue } = context;
53536
+ const status = stringArg(args, "status");
53537
+ const change = (entry) => {
53538
+ const was = issuesBefore.get(entry.key);
53539
+ if (entry.key !== before.key && entry.parent === null && was?.parent === before.key) {
53540
+ return `unlinked from ${before.key}`;
53541
+ }
53542
+ return was === undefined ? `status -> ${entry.status}` : `status ${was.status} -> ${entry.status}`;
53543
+ };
53544
+ let answer;
53545
+ try {
53546
+ answer = await client.changeIssueStatus(issue(), {
53547
+ status,
53548
+ ...options.includes("include_children") ? { include_children: true } : {},
53549
+ ...options.includes("unlink_children") ? { unlink_children: true } : {},
53550
+ ...options.includes("include_parent") ? { include_parent: true } : {},
53551
+ actor
53552
+ });
53553
+ } catch (error) {
53554
+ if (error instanceof DispatchWriteLandedError)
53555
+ throw error;
53556
+ const committed = error instanceof DispatchServiceError ? error.changed ?? [] : [];
53557
+ const changed = committed.length === 0 ? "" : `the steps before the refusal changed ${committed.map((entry) => `${entry.key} (${change(entry)})`).join(", ")}`;
53558
+ if (closingNote === undefined)
53559
+ throw refusalWithCode(error, changed);
53560
+ const landed = closeAccount(error, closingNote);
53561
+ if (error instanceof DispatchServiceError)
53562
+ throw refusalWithCode(error, changed, landed);
53563
+ throw withAccount(error, landed);
53564
+ }
53565
+ const suffix = await notSubscribed(issueTopic(before.key), input.subscriptions);
53566
+ const namedLine = (after) => `${before.key}: ${[
53567
+ ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
53568
+ `status ${before.status} -> ${after}`
53569
+ ].join("; ")}${suffix}`;
53570
+ const changed = answer.changed ?? [];
53571
+ const lines = changed.map((entry) => entry.key === before.key ? namedLine(entry.status) : `${entry.key}: ${change(entry)}`);
53572
+ if (!changed.some((entry) => entry.key === before.key))
53573
+ lines.push(namedLine(answer.issue.status));
53574
+ return {
53575
+ text: lines.join(`
53576
+ `),
53577
+ details: {
53578
+ issue: before.key,
53579
+ status: answer.issue.status,
53580
+ external_links: (answer.issue.external_links ?? []).map((link) => link.url),
53581
+ changed: changed.map(({ key, status, parent }) => ({ key, status, parent })),
53582
+ ...closingNote === undefined ? {} : { message: closingNote.id }
53583
+ }
53584
+ };
53585
+ }
53586
+
53117
53587
  // ../envoy-client/src/dispatch-commands/issues.ts
53118
53588
  function componentsChange(input, after) {
53119
53589
  switch (input.mode) {
@@ -53265,6 +53735,7 @@ async function issueUpdateCommand(context) {
53265
53735
  const advances = optionalStringArray(args, "advances");
53266
53736
  const advancesRevision = optionalNumber(args, "advances_revision");
53267
53737
  const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
53738
+ const options = issueStatusOptionsOf(args);
53268
53739
  let before;
53269
53740
  try {
53270
53741
  before = await client.getIssue(issueKey);
@@ -53275,6 +53746,7 @@ async function issueUpdateCommand(context) {
53275
53746
  if (status === "done" && typeof before.closed_at === "string") {
53276
53747
  throw refusalWithCode(new DispatchServiceError("ISSUE_CLOSED", 409, "issue is closed"), `${issueKey} closed at ${before.closed_at}, so the reason was not posted and the close was not sent`);
53277
53748
  }
53749
+ const issuesBefore = options.length === 0 ? undefined : await issuesBeforeStatusChange(client, before, options);
53278
53750
  let closingNote;
53279
53751
  if (reason !== undefined) {
53280
53752
  try {
@@ -53293,6 +53765,9 @@ async function issueUpdateCommand(context) {
53293
53765
  throw withAccount(error, told);
53294
53766
  }
53295
53767
  }
53768
+ if (issuesBefore !== undefined) {
53769
+ return statusChangeCommand(context, before, options, issuesBefore, closingNote);
53770
+ }
53296
53771
  const existingLinks = before.external_links ?? [];
53297
53772
  const linked = existingLinks.map((link) => link.url);
53298
53773
  const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
@@ -53331,9 +53806,7 @@ async function issueUpdateCommand(context) {
53331
53806
  }
53332
53807
  throw refusalWithCode(error, taken);
53333
53808
  }
53334
- const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
53335
- const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
53336
- const landed = writeMayHaveLanded(error) ? `${posted}, and the close may or may not have taken effect. Read the issue's status before retrying: done means it closed; otherwise retry with a reason that points at message ${closingNote.id}, since retrying this call posts its reason again` : `${posted} but the issue did not close. Retrying this call posts its reason again, so ${fix}retry with a reason that points at message ${closingNote.id}`;
53809
+ const landed = closeAccount(error, closingNote);
53337
53810
  if (error instanceof DispatchServiceError)
53338
53811
  throw refusalWithCode(error, taken, landed);
53339
53812
  throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
@@ -53455,8 +53928,11 @@ async function relatedCommand(context) {
53455
53928
  details: { project, suggestions }
53456
53929
  };
53457
53930
  }
53931
+ function printsJson(tool, args) {
53932
+ return tool === "dispatch_issues" && args["json"] === true;
53933
+ }
53458
53934
  async function issuesCommand(context) {
53459
- const { args, client } = context;
53935
+ const { args, client, input } = context;
53460
53936
  const project = stringArg(args, "project");
53461
53937
  const status = optionalString(args, "status");
53462
53938
  const parent = optionalString(args, "parent");
@@ -53499,6 +53975,10 @@ async function issuesCommand(context) {
53499
53975
  updated_at: row.updated_at,
53500
53976
  progress: row.progress
53501
53977
  }));
53978
+ const listing = { issues: rows, total, offset, limit };
53979
+ if (printsJson(input.tool, args)) {
53980
+ return { text: JSON.stringify(listing), details: listing };
53981
+ }
53502
53982
  const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
53503
53983
  const isPartial = offset !== 0 || rows.length !== total;
53504
53984
  const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
@@ -53511,7 +53991,7 @@ async function issuesCommand(context) {
53511
53991
  })
53512
53992
  ].join(`
53513
53993
  `),
53514
- details: { issues: rows, total, offset, limit }
53994
+ details: listing
53515
53995
  };
53516
53996
  }
53517
53997
  function dryRunAsksDispatch(tool, args) {
@@ -55851,7 +56331,7 @@ async function reviewCommand(context) {
55851
56331
  }
55852
56332
 
55853
56333
  // ../envoy-client/src/session-answers.ts
55854
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "fs";
56334
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5 } from "fs";
55855
56335
  import { join as join7 } from "path";
55856
56336
 
55857
56337
  // ../envoy-client/src/json-line-record.ts
@@ -55992,7 +56472,7 @@ processGlobal2[STATE_KEY] = state;
55992
56472
  var CACHE_FILE = "answers.json";
55993
56473
  function readCacheFile(directory, url) {
55994
56474
  try {
55995
- const value = JSON.parse(readFileSync4(join7(directory, CACHE_FILE), "utf-8"));
56475
+ const value = JSON.parse(readFileSync5(join7(directory, CACHE_FILE), "utf-8"));
55996
56476
  if (typeof value === "object" && value !== null && "dispatch_url" in value && typeof value.dispatch_url === "string" && value.dispatch_url === url && "read_at" in value && typeof value.read_at === "string" && "total" in value && typeof value.total === "number" && "items" in value && Array.isArray(value.items)) {
55997
56477
  return {
55998
56478
  dispatch_url: value.dispatch_url,
@@ -56193,13 +56673,29 @@ async function whoamiCommand(context) {
56193
56673
  const service = identity.kind === "agent" ? identity.service ?? null : null;
56194
56674
  const proved = identity.kind === "agent" ? identity.session ?? null : null;
56195
56675
  const project = identity.kind === "agent" ? identity.project ?? null : null;
56676
+ const readOnly = identity.scopes?.includes("read") === true;
56677
+ const cut = identity.kind === "agent" ? identity.cut ?? null : null;
56196
56678
  const session = proved ?? sessionId;
56197
56679
  const unowned = "no owner, so an issue you create without an assignee takes its parent's assignee when the parent is in the same project, else the project's default assignee, which every project names, so the issue always has one.";
56198
56680
  const answered = identity.kind === "agent" ? identity.sign_in_required : undefined;
56199
56681
  const signInNeeded = answered ?? (owner === null && service !== null && proved !== null);
56200
- const acting = owner !== null ? `Session ${session} acts for ${owner}: issues you create without an assignee are assigned to ${owner}.` : service !== null ? signInNeeded ? `Session ${session} runs as service ${serviceSubjectLabel(service)} and no person, so it may read but Dispatch refuses every write it makes: run \`agent-secrets login\` on this machine to write as yourself.` : `Session ${session} runs as service ${serviceSubjectLabel(service)}: ${unowned}` : `Session ${session} runs under the shared token: ${unowned}`;
56201
- const elsewhere = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId}): Dispatch records every write you make as ${proved}.` : "";
56202
- const writable = project !== null ? ` It may write project ${project} and no other.` : "";
56682
+ const who = owner !== null ? `acts for ${owner}` : service !== null ? `runs as service ${serviceSubjectLabel(service)}` : "runs";
56683
+ const named = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId})` : "";
56684
+ let acting;
56685
+ let elsewhere = named === "" ? "" : `${named}: Dispatch records every write you make as ${proved}.`;
56686
+ if (readOnly) {
56687
+ acting = `Session ${session} ${who} with a read-only credential: it may read, and Dispatch refuses every write it makes.${cut === null ? "" : ` Its cut is ${cut}, the past time it reads Dispatch at.`}`;
56688
+ elsewhere = named === "" ? "" : `${named}.`;
56689
+ } else if (owner !== null) {
56690
+ acting = `Session ${session} ${who}: issues you create without an assignee are assigned to ${owner}.`;
56691
+ } else if (signInNeeded) {
56692
+ acting = `Session ${session} ${who} and no person, so it may read but Dispatch refuses every write it makes: run \`agent-secrets login\` on this machine to write as yourself.`;
56693
+ } else if (service !== null) {
56694
+ acting = `Session ${session} ${who}: ${unowned}`;
56695
+ } else {
56696
+ acting = `Session ${session} runs under the shared token: ${unowned}`;
56697
+ }
56698
+ const writable = project !== null && !readOnly ? ` It may write project ${project} and no other.` : "";
56203
56699
  return {
56204
56700
  text: acting + elsewhere + writable,
56205
56701
  details: { session, owner, service, project }
@@ -56485,7 +56981,7 @@ function ensureDirectory(dir) {
56485
56981
  }
56486
56982
  function readIfPresent(path) {
56487
56983
  try {
56488
- return readFileSync5(path, "utf-8");
56984
+ return readFileSync6(path, "utf-8");
56489
56985
  } catch (error) {
56490
56986
  if (hasErrnoCode(error, "ENOENT"))
56491
56987
  return;
@@ -56765,7 +57261,6 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
56765
57261
  admissions: () => admissions
56766
57262
  };
56767
57263
  }
56768
- var RENEW_FLOOR_MS = 1000;
56769
57264
  var RETRY_FIRST_MS = 2000;
56770
57265
  var RETRY_LAST_MS = 60000;
56771
57266
  var WARN_AGAIN_MS = 30 * 60000;
@@ -56822,11 +57317,7 @@ function warnedEvery(warn) {
56822
57317
  };
56823
57318
  }
56824
57319
  function renewDelay(expiry, now) {
56825
- const remaining = expiry - now;
56826
- if (remaining <= 0)
56827
- return 0;
56828
- const ahead = remaining - Math.min(DEFAULT_RENEW_BEFORE_MS, remaining / 2);
56829
- return Math.max(Math.min(RENEW_FLOOR_MS, remaining / 2), ahead);
57320
+ return renewalAt(expiry, now, DEFAULT_RENEW_BEFORE_MS) - now;
56830
57321
  }
56831
57322
  function keepNatsCredential(connection, credential, warn) {
56832
57323
  let stopped = false;
@@ -57265,7 +57756,8 @@ function sessionDispatchSettings(file, env, options) {
57265
57756
  return {
57266
57757
  dispatch: dispatchSettings(env, config, {
57267
57758
  commands: options.commands,
57268
- session: options.session
57759
+ session: options.session,
57760
+ tokenFiles: options.tokenFiles
57269
57761
  }),
57270
57762
  warnings: config.kind === "read" ? config.warnings : [],
57271
57763
  missing: config.kind === "read" ? config.missing : null
@@ -61006,7 +61498,7 @@ function inboundUnavailable(tell, restored) {
61006
61498
  var import_nats2 = __toESM(require_mod4(), 1);
61007
61499
  var import_nats3 = __toESM(require_nats(), 1);
61008
61500
  var import_servers = __toESM(require_servers(), 1);
61009
- import { readFileSync as readFileSync6 } from "fs";
61501
+ import { readFileSync as readFileSync7 } from "fs";
61010
61502
  import { setTimeout as delay } from "timers/promises";
61011
61503
 
61012
61504
  // ../envoy-client/src/nats-auth.ts
@@ -61044,7 +61536,7 @@ var RELEASE_VERSION = /^\d+\.\d+\.\d+$/;
61044
61536
  function clientBuild(stampFile, release) {
61045
61537
  let stamp = "";
61046
61538
  try {
61047
- stamp = readFileSync6(stampFile, "utf8").trim();
61539
+ stamp = readFileSync7(stampFile, "utf8").trim();
61048
61540
  } catch {}
61049
61541
  if (FULL_COMMIT.test(stamp))
61050
61542
  return `legion@${stamp}`;
@@ -62829,7 +63321,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
62829
63321
 
62830
63322
  // package.json
62831
63323
  var name2 = "@sjawhar/claude-envoy";
62832
- var version2 = "5.23.7";
63324
+ var version2 = "5.25.0";
62833
63325
  var legion = {
62834
63326
  daemonApiVersion: 256
62835
63327
  };
@@ -64033,7 +64525,7 @@ import { readFile as readFile4 } from "fs/promises";
64033
64525
  import { basename as basename3, join as join10 } from "path";
64034
64526
 
64035
64527
  // src/session-state.ts
64036
- import { readFileSync as readFileSync7 } from "fs";
64528
+ import { readFileSync as readFileSync8 } from "fs";
64037
64529
  import { mkdir as mkdir2, readdir as readdir3, rename as rename3, rm as rm3, stat as stat3, utimes as utimes2, writeFile } from "fs/promises";
64038
64530
  import { dirname as dirname4, join as join9 } from "path";
64039
64531
  async function writeAtomicStateFile(file, contents) {
@@ -64079,7 +64571,7 @@ async function removeChosenTitle(file) {
64079
64571
  }
64080
64572
  function readChosenTitleSync(file) {
64081
64573
  try {
64082
- return readFileSync7(file, "utf8");
64574
+ return readFileSync8(file, "utf8");
64083
64575
  } catch {
64084
64576
  return;
64085
64577
  }
@@ -65749,7 +66241,7 @@ function listenerAskedToClaimAgain(error) {
65749
66241
 
65750
66242
  // src/legion-phase-hook.ts
65751
66243
  import { randomUUID as randomUUID7 } from "crypto";
65752
- import { readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
66244
+ import { readFileSync as readFileSync9, renameSync as renameSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
65753
66245
  import { dirname as dirname6, join as join12 } from "path";
65754
66246
 
65755
66247
  // ../pi-shared/src/phase-reminder.ts
@@ -66225,7 +66717,7 @@ var NO_RECORD = { entry: undefined, recreatedNoticeSent: false };
66225
66717
  function readPhaseStallRecord(file, log) {
66226
66718
  let raw;
66227
66719
  try {
66228
- raw = readFileSync8(file, "utf8");
66720
+ raw = readFileSync9(file, "utf8");
66229
66721
  } catch (error) {
66230
66722
  const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
66231
66723
  if (!missing) {
@@ -67738,12 +68230,12 @@ import { basename as basename4 } from "path";
67738
68230
 
67739
68231
  // ../envoy-client/src/process-ancestry.ts
67740
68232
  import { execFileSync } from "child_process";
67741
- import { readFileSync as readFileSync9 } from "fs";
68233
+ import { readFileSync as readFileSync10 } from "fs";
67742
68234
  var MAX_ANCESTORS = 64;
67743
68235
  var PARENT_LOOKUP_MS = 1000;
67744
68236
  function procParentPid(pid) {
67745
68237
  try {
67746
- const stat = readFileSync9(`/proc/${pid}/stat`, "utf8");
68238
+ const stat = readFileSync10(`/proc/${pid}/stat`, "utf8");
67747
68239
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
67748
68240
  return Number.isInteger(parent) ? parent : undefined;
67749
68241
  } catch {
@@ -67785,7 +68277,7 @@ function isAncestor(candidate, pid = process.pid) {
67785
68277
  }
67786
68278
  function procCommand(pid) {
67787
68279
  try {
67788
- return readFileSync9(`/proc/${pid}/comm`, "utf8").trim();
68280
+ return readFileSync10(`/proc/${pid}/comm`, "utf8").trim();
67789
68281
  } catch {
67790
68282
  return;
67791
68283
  }
@@ -70034,10 +70526,10 @@ function startCodexAgentStream(options) {
70034
70526
  // src/codex/codex-cli.ts
70035
70527
  import { spawn } from "child_process";
70036
70528
  import { randomBytes as randomBytes2 } from "crypto";
70037
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
70529
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "fs";
70038
70530
  import { join as join16 } from "path";
70039
70531
  var QUEUE_TIMEOUT_MS = 30000;
70040
- function codexProcessEnv(pid, fallback, read = (path) => readFileSync10(path, "utf8")) {
70532
+ function codexProcessEnv(pid, fallback, read = (path) => readFileSync11(path, "utf8")) {
70041
70533
  let raw;
70042
70534
  try {
70043
70535
  raw = read(`/proc/${pid}/environ`);
@@ -70481,7 +70973,7 @@ import { join as join19 } from "path";
70481
70973
 
70482
70974
  // src/codex/codex-session-record.ts
70483
70975
  import { spawnSync } from "child_process";
70484
- import { readFileSync as readFileSync11, readlinkSync as readlinkSync3, unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
70976
+ import { readFileSync as readFileSync12, readlinkSync as readlinkSync3, unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
70485
70977
  import { mkdir as mkdir5, readFile as readFile7, rename as rename5, utimes as utimes3, writeFile as writeFile3 } from "fs/promises";
70486
70978
  import { homedir as homedir3 } from "os";
70487
70979
  import { basename as basename5, dirname as dirname8, join as join18 } from "path";
@@ -70567,14 +71059,14 @@ function codexProcessId(readComm = procComm, readParent = procParent) {
70567
71059
  }
70568
71060
  function procComm(pid) {
70569
71061
  try {
70570
- return readFileSync11(`/proc/${pid}/comm`, "utf8").trim();
71062
+ return readFileSync12(`/proc/${pid}/comm`, "utf8").trim();
70571
71063
  } catch {
70572
71064
  return;
70573
71065
  }
70574
71066
  }
70575
71067
  function procParent(pid) {
70576
71068
  try {
70577
- const stat = readFileSync11(`/proc/${pid}/stat`, "utf8");
71069
+ const stat = readFileSync12(`/proc/${pid}/stat`, "utf8");
70578
71070
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
70579
71071
  return Number.isInteger(parent) ? parent : undefined;
70580
71072
  } catch {
@@ -70588,7 +71080,7 @@ var PS_OPTIONS = {
70588
71080
  };
70589
71081
  function procStarted(pid) {
70590
71082
  try {
70591
- const stat = readFileSync11(`/proc/${pid}/stat`, "utf8");
71083
+ const stat = readFileSync12(`/proc/${pid}/stat`, "utf8");
70592
71084
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
70593
71085
  } catch {
70594
71086
  return;
@@ -70609,7 +71101,7 @@ function recordOfProcess(record, pid) {
70609
71101
  function sharedAppServer(pid) {
70610
71102
  let argv;
70611
71103
  try {
70612
- argv = readFileSync11(`/proc/${pid}/cmdline`, "utf8").split("\x00");
71104
+ argv = readFileSync12(`/proc/${pid}/cmdline`, "utf8").split("\x00");
70613
71105
  } catch {
70614
71106
  const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS);
70615
71107
  if (ps.status !== 0)