@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.
@@ -14072,6 +14072,8 @@ var ASK_OPTIONS_CONTRACT = "Options carry the genuinely different approaches. Ea
14072
14072
  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.";
14073
14073
  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.";
14074
14074
  var HUMAN_AGREED_TO_DOCUMENT = "the human has agreed to every point in the document";
14075
+ var DOCUMENT_OWNER_RULE = "Exactly one of issue and project is required; with project, artifact names the document.";
14076
+ var NAMED_DOCUMENT_OWNER_RULE = "Exactly one of issue and project is required; artifact or ref must name the document.";
14075
14077
  function documentOwnerValidation(requireArtifact, alwaysRequireArtifact = false) {
14076
14078
  return {
14077
14079
  check: (value) => {
@@ -14082,15 +14084,21 @@ function documentOwnerValidation(requireArtifact, alwaysRequireArtifact = false)
14082
14084
  const hasRef = typeof input.ref === "string";
14083
14085
  return (hasIssue !== hasProject || !hasIssue && !hasProject && hasRef) && (!hasProject || !requireArtifact || hasArtifact) && (!alwaysRequireArtifact || hasArtifact || hasRef);
14084
14086
  },
14085
- 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."
14087
+ message: alwaysRequireArtifact ? NAMED_DOCUMENT_OWNER_RULE : DOCUMENT_OWNER_RULE
14086
14088
  };
14087
14089
  }
14088
14090
  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.";
14089
- var ARTIFACT_OWNER_AND_SOURCE_RULE = `${ARTIFACT_SOURCE_RULE} Exactly one of issue and project is required; with project, artifact names the document.`;
14091
+ var ARTIFACT_OWNER_AND_SOURCE_RULE = `${ARTIFACT_SOURCE_RULE} ${DOCUMENT_OWNER_RULE}`;
14090
14092
  function brokenParts(parts) {
14091
14093
  const broken = parts.filter(([kept]) => !kept).map(([, message]) => message);
14092
14094
  return broken.length === 0 ? undefined : broken.join(" ");
14093
14095
  }
14096
+ function withoutOwnerRule(refusal) {
14097
+ const rule = DISPATCH_OWNER_RULES.find((owner) => refusal === owner || refusal.startsWith(`${owner} `));
14098
+ if (rule === undefined)
14099
+ return refusal;
14100
+ return refusal === rule ? undefined : refusal.slice(rule.length + 1);
14101
+ }
14094
14102
  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)";
14095
14103
  var DOCUMENT_IS_MARKDOWN = "a document holds Markdown, which rewrites other text (a JSONL file's lines come back joined into one paragraph)";
14096
14104
  var PATH_KEEPS_BYTES = "path (--path <file>), which stores a file whose path does not end in .md or .markdown as its bytes, unchanged";
@@ -14134,18 +14142,13 @@ function pathKeepsBytesOf(name) {
14134
14142
  var artifactOwner = documentOwnerValidation(false);
14135
14143
  function artifactProblem(value) {
14136
14144
  const input = value;
14137
- const ownerOrSourceProblem = brokenParts([
14145
+ const extension = typeof input.path === "string" || typeof input.name !== "string" ? undefined : NAME_EXTENSION.exec(input.name.trim())?.[1];
14146
+ 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.`;
14147
+ return brokenParts([
14138
14148
  [artifactOwner.check(value), artifactOwner.message],
14139
- [typeof input.path !== "string" || typeof input.content !== "string", ARTIFACT_SOURCE_RULE]
14149
+ [typeof input.path !== "string" || typeof input.content !== "string", ARTIFACT_SOURCE_RULE],
14150
+ [nameProblem === undefined, nameProblem ?? ""]
14140
14151
  ]);
14141
- if (ownerOrSourceProblem !== undefined)
14142
- return ownerOrSourceProblem;
14143
- if (typeof input.path === "string" || typeof input.name !== "string")
14144
- return;
14145
- const extension = NAME_EXTENSION.exec(input.name.trim())?.[1];
14146
- if (extension === undefined || MARKDOWN_EXTENSION.test(extension))
14147
- return;
14148
- 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.`;
14149
14152
  }
14150
14153
  var documentEditOwner = documentOwnerValidation(true);
14151
14154
  var PRECONDITION_RULE = "A precondition selects exactly one of document or blocks.";
@@ -14240,34 +14243,100 @@ var ISSUE_UPDATE_FIELDS_RULE = "Issue update requires at least one field besides
14240
14243
  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";
14241
14244
  var ISSUE_UPDATE_REASON_RULE = "reason goes only with status done";
14242
14245
  var ISSUE_UPDATE_LABELS_RULE = "labels_add goes without labels";
14243
- var ISSUE_UPDATE_RULE = `${ISSUE_UPDATE_FIELDS_RULE} ${ISSUE_UPDATE_DONE_RULE}; ${ISSUE_UPDATE_REASON_RULE}; ${ISSUE_UPDATE_LABELS_RULE}.`;
14244
- function issueUpdateProblem(value) {
14245
- const input = value;
14246
+ 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.`;
14247
+ var ISSUE_STATUS_OPTIONS = [
14248
+ "include_children",
14249
+ "unlink_children",
14250
+ "include_parent"
14251
+ ];
14252
+ function issueStatusOptionsOf(input) {
14253
+ return ISSUE_STATUS_OPTIONS.filter((option) => input[option] === true);
14254
+ }
14255
+ var ISSUE_UPDATE_PATCH_FIELDS = [
14256
+ "title",
14257
+ "labels",
14258
+ "labels_add",
14259
+ "priority",
14260
+ "assignee",
14261
+ "external_links",
14262
+ "route",
14263
+ "parent",
14264
+ "blocked_by",
14265
+ "advances",
14266
+ "advances_revision",
14267
+ "components",
14268
+ "repo",
14269
+ "before",
14270
+ "after"
14271
+ ];
14272
+ 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.";
14273
+ var ISSUE_UPDATE_RULE = `${ISSUE_UPDATE_FIELDS_RULE} ${ISSUE_UPDATE_DONE_RULE}; ${ISSUE_UPDATE_REASON_RULE}; ${ISSUE_UPDATE_LABELS_RULE}. ${ISSUE_UPDATE_OPTIONS_RULE}`;
14274
+ function issueStatusOptionsProblem(input) {
14275
+ const options = issueStatusOptionsOf(input);
14276
+ if (options.length === 0)
14277
+ return;
14278
+ const named = options.join(", ").replace(/, ([^,]*)$/, " and $1");
14279
+ const others = ISSUE_UPDATE_PATCH_FIELDS.filter((field) => input[field] !== undefined);
14280
+ return brokenParts([
14281
+ [
14282
+ !(input["include_children"] === true && input["unlink_children"] === true),
14283
+ "include_children does not go with unlink_children. The open children move with the issue or leave it, so name one of the two."
14284
+ ],
14285
+ [
14286
+ !(input["include_children"] === true && input["status"] === "done"),
14287
+ "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."
14288
+ ],
14289
+ [
14290
+ typeof input["status"] === "string",
14291
+ `status is required with ${named}. Add status, or drop ${named}.`
14292
+ ],
14293
+ [
14294
+ others.length === 0,
14295
+ `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.`
14296
+ ]
14297
+ ]);
14298
+ }
14299
+ function issueReasonProblem(input) {
14246
14300
  if (input.status === "done") {
14247
- if (typeof input.reason !== "string" || input.reason.trim() === "") {
14248
- return `${ISSUE_UPDATE_DONE_RULE}.`;
14249
- }
14250
- } else if (input.reason !== undefined) {
14251
- const status = typeof input.status === "string" ? `status ${input.status}` : "an update without status done";
14252
- 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.`;
14253
- }
14254
- if (input.labels !== undefined && input.labels_add !== undefined) {
14255
- 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.`;
14301
+ return typeof input.reason !== "string" || input.reason.trim() === "" ? `${ISSUE_UPDATE_DONE_RULE}.` : undefined;
14256
14302
  }
14303
+ if (input.reason === undefined)
14304
+ return;
14305
+ const status = typeof input.status === "string" ? `status ${input.status}` : "an update without status done";
14306
+ 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.`;
14307
+ }
14308
+ function issueUpdateProblem(value) {
14309
+ const input = value;
14310
+ const reasonProblem = issueReasonProblem(input);
14311
+ const optionsProblem = issueStatusOptionsProblem(value);
14312
+ const broken = brokenParts([
14313
+ [reasonProblem === undefined, reasonProblem ?? ""],
14314
+ [input.labels === undefined || input.labels_add === undefined, ISSUE_UPDATE_LABELS_REFUSAL],
14315
+ [optionsProblem === undefined, optionsProblem ?? ""]
14316
+ ]);
14317
+ if (broken !== undefined)
14318
+ return broken;
14257
14319
  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";
14258
14320
  return changesAField ? undefined : ISSUE_UPDATE_FIELDS_RULE;
14259
14321
  }
14322
+ 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.";
14260
14323
  var messageValidation = {
14261
14324
  check: (value) => {
14262
14325
  const input = value;
14263
14326
  return typeof input.issue === "string" || typeof input.in_reply_to === "string";
14264
14327
  },
14265
- message: "issue is required unless in_reply_to names a message delivered to this session, which is the one message with no issue."
14328
+ message: MESSAGE_OWNER_RULE
14266
14329
  };
14267
14330
  var readOwner = documentOwnerValidation(false);
14268
14331
  var READ_OWNER_RULE = "Exactly one of issue and project is required; project alone lists its documents, and with artifact names one.";
14269
14332
  var READ_MESSAGE_RULE = "message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it.";
14270
14333
  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.";
14334
+ var DISPATCH_OWNER_RULES = [
14335
+ DOCUMENT_OWNER_RULE,
14336
+ NAMED_DOCUMENT_OWNER_RULE,
14337
+ READ_OWNER_RULE,
14338
+ MESSAGE_OWNER_RULE
14339
+ ];
14271
14340
  function readProblem(value) {
14272
14341
  const input = value;
14273
14342
  const historyKept = input.history !== true || typeof input.ref === "string";
@@ -14458,11 +14527,14 @@ var dispatchToolSpecs = [
14458
14527
  priority: 1,
14459
14528
  before: "DSP-2"
14460
14529
  },
14461
- 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}`,
14530
+ 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}`,
14462
14531
  arguments: (z) => ({
14463
14532
  issue: z.string().describe(ISSUE_REFERENCE),
14464
14533
  status: z.enum(ISSUE_STATUSES).describe("New lifecycle status.").optional(),
14465
14534
  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(),
14535
+ 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(),
14536
+ 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(),
14537
+ 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(),
14466
14538
  title: z.string({ min: 1, max: ISSUE_TITLE_MAX }).describe("Replacement title, at most 1,000 characters.").optional(),
14467
14539
  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(),
14468
14540
  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(),
@@ -14916,7 +14988,7 @@ var dispatchToolSpecs = [
14916
14988
  {
14917
14989
  name: "dispatch_issues",
14918
14990
  example: { project: "PROJ", limit: 250, offset: 250 },
14919
- 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.",
14991
+ 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.",
14920
14992
  arguments: (z) => ({
14921
14993
  project: z.string().describe("Project key to list issues from."),
14922
14994
  status: z.enum(ISSUE_STATUSES).describe("Optional lifecycle status filter.").optional(),
@@ -14927,7 +14999,8 @@ var dispatchToolSpecs = [
14927
14999
  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(),
14928
15000
  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(),
14929
15001
  offset: z.number({ int: true, min: 0 }).describe("Rows to skip before the page; nonnegative integer; default 0.").optional(),
14930
- 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()
15002
+ 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(),
15003
+ 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()
14931
15004
  })
14932
15005
  },
14933
15006
  {
@@ -20088,6 +20161,10 @@ var FORM_SESSION = "session";
20088
20161
  var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
20089
20162
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
20090
20163
  var FORM_PROJECTS = "projects";
20164
+ var FORM_SCOPE = "scope";
20165
+ var SCOPE_READ = "read";
20166
+ var FORM_AS_OF = "as_of";
20167
+ var HEADER_DPOP_HOLDER = "DPoP-Holder";
20091
20168
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
20092
20169
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
20093
20170
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
@@ -20200,6 +20277,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
20200
20277
  "The machine login the subject token belongs to has ended\\.",
20201
20278
  "The machine login has ended\\.",
20202
20279
  "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)\\.",
20280
+ "A live read token is bound to the key this proof was signed with\\. Make a new key\\.",
20203
20281
  `${PERSON_SLOT} is a restricted member, whose token names its projects: set AGENT_SECRETS_PROJECTS to the projects this session works on\\.`,
20204
20282
  `The token names a project its person cannot see: ${PROJECT_SLOT}\\.`,
20205
20283
  `The subject token was refused: its entry names the project ${PROJECT_SLOT}, which its person ${PERSON_SLOT} cannot see\\.`,
@@ -20212,6 +20290,19 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
20212
20290
  `The session name '${SESSION_SLOT}' belongs to another daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
20213
20291
  `The session name '${SESSION_SLOT}' is bound to no daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
20214
20292
  `${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`,
20293
+ "The 'as_of' parameter names a cut, and only a trade that asks for the scope read may name one\\.",
20294
+ "The 'as_of' parameter is not an RFC 3339 time with at most six fractional digits\\.",
20295
+ "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
20296
+ "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
20297
+ "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
20298
+ `${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\\.`,
20299
+ `${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\\.`,
20300
+ "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\\.",
20301
+ "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\\.",
20302
+ "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\\.",
20303
+ "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\\.",
20304
+ "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\\.",
20305
+ "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\\.",
20215
20306
  ...POLICY_REFUSAL_PATTERNS
20216
20307
  ].map((source) => new RegExp(`^${source}$`));
20217
20308
  var LIBRARY_DESCRIPTIONS = [
@@ -21158,18 +21249,22 @@ var DISPATCH_URL_SETTING = "the configured Dispatch URL";
21158
21249
  class DispatchServiceError extends Error {
21159
21250
  code;
21160
21251
  status;
21252
+ name = "DispatchServiceError";
21253
+ fromDispatch = true;
21161
21254
  candidates;
21162
21255
  current;
21163
21256
  mismatches;
21164
- name = "DispatchServiceError";
21165
- fromDispatch = true;
21166
- constructor(code, status, message, candidates, current, mismatches) {
21257
+ issues;
21258
+ changed;
21259
+ constructor(code, status, message, details = {}) {
21167
21260
  super(message);
21168
21261
  this.code = code;
21169
21262
  this.status = status;
21170
- this.candidates = candidates;
21171
- this.current = current;
21172
- this.mismatches = mismatches;
21263
+ this.candidates = details.candidates;
21264
+ this.current = details.current;
21265
+ this.mismatches = details.mismatches;
21266
+ this.issues = details.issues;
21267
+ this.changed = details.changed;
21173
21268
  }
21174
21269
  }
21175
21270
 
@@ -21270,6 +21365,9 @@ function reviewNoRouteRefusal(baseUrl, route, version) {
21270
21365
  function resultDryRunNoRouteRefusal(baseUrl, route) {
21271
21366
  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.");
21272
21367
  }
21368
+ function statusChangeNoRouteRefusal(baseUrl, route) {
21369
+ 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.");
21370
+ }
21273
21371
  var ISSUE_EVENTS_PAGE_MAX = 200;
21274
21372
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
21275
21373
  function requestSignal(signal, deadlineMs) {
@@ -21588,6 +21686,14 @@ class DispatchClient {
21588
21686
  async updateIssue(issue, input) {
21589
21687
  return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
21590
21688
  }
21689
+ async changeIssueStatus(issue, input) {
21690
+ const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "status-change"];
21691
+ try {
21692
+ return await this.#json("POST", path, input);
21693
+ } catch (error) {
21694
+ throw this.#refusalOfNoRoute(error, path, (route) => statusChangeNoRouteRefusal(this.#baseUrl, route));
21695
+ }
21696
+ }
21591
21697
  async claimIssue(issue, input = {}) {
21592
21698
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
21593
21699
  }
@@ -21742,10 +21848,7 @@ class DispatchClient {
21742
21848
  try {
21743
21849
  return await this.#json("POST", path, body);
21744
21850
  } catch (error) {
21745
- if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
21746
- throw error;
21747
- const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
21748
- throw reviewNoRouteRefusal(this.#baseUrl, route, version);
21851
+ throw this.#refusalOfNoRoute(error, path, (route) => reviewNoRouteRefusal(this.#baseUrl, route, version));
21749
21852
  }
21750
21853
  }
21751
21854
  async recordResult(issue, input) {
@@ -21756,10 +21859,7 @@ class DispatchClient {
21756
21859
  try {
21757
21860
  return await this.#writingNothing(path, input, { writes: false });
21758
21861
  } catch (error) {
21759
- if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
21760
- throw error;
21761
- const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
21762
- throw resultDryRunNoRouteRefusal(this.#baseUrl, route);
21862
+ throw this.#refusalOfNoRoute(error, path, (route) => resultDryRunNoRouteRefusal(this.#baseUrl, route));
21763
21863
  }
21764
21864
  }
21765
21865
  async issueResults(issue, at) {
@@ -22004,6 +22104,11 @@ class DispatchClient {
22004
22104
  sleep: this.#sleep
22005
22105
  });
22006
22106
  }
22107
+ #refusalOfNoRoute(error, path, refuse) {
22108
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
22109
+ return error;
22110
+ return refuse(`POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`);
22111
+ }
22007
22112
  #writeCall(method, url, key, writes = true) {
22008
22113
  if (method !== "POST" && method !== "PATCH")
22009
22114
  return;
@@ -22337,7 +22442,7 @@ class DispatchClient {
22337
22442
  if (response.status === 409 && error.code === IDEMPOTENCY_KEY_COMMITTED) {
22338
22443
  throw new DispatchWriteLandedError(IDEMPOTENCY_KEY_COMMITTED, response.status, method, requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING));
22339
22444
  }
22340
- throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error.candidates, error.current, error.mismatches);
22445
+ throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error);
22341
22446
  }
22342
22447
  throw this.#gatewayError(method, url, response, text, "Dispatch's error JSON");
22343
22448
  }
@@ -24133,6 +24238,7 @@ var pictureSendingTools = {
24133
24238
  };
24134
24239
  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";
24135
24240
  var ownerRequiredProblem = "issue is required; supply issue or set LEGION_ISSUE";
24241
+ var ownerStandInIssue = "OWNER-1";
24136
24242
  function argumentProblems(tool, args) {
24137
24243
  const problems = [];
24138
24244
  switch (tool) {
@@ -24418,7 +24524,7 @@ async function resolveOwnerArguments(tool, input, cwd, env, exec, dashboardUrls,
24418
24524
  const legionIssue = env.LEGION_ISSUE;
24419
24525
  if (!legionIssue) {
24420
24526
  problems.push(ownerRequiredProblem);
24421
- return { args, ref, owner: null };
24527
+ return { args, ref, owner: null, ownerMissing: true };
24422
24528
  }
24423
24529
  if (nativeIssueKeyPattern.test(legionIssue) || externalIssueRefPattern.test(legionIssue)) {
24424
24530
  const issue = canonicalExternalIssueRef(legionIssue);
@@ -24426,18 +24532,24 @@ async function resolveOwnerArguments(tool, input, cwd, env, exec, dashboardUrls,
24426
24532
  }
24427
24533
  if (!bareIssueNumberPattern.test(legionIssue)) {
24428
24534
  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");
24429
- return { args, ref, owner: null };
24535
+ return { args, ref, owner: null, ownerMissing: true };
24430
24536
  }
24431
24537
  const repo = await resolveCwdRepo(cwd, exec);
24432
24538
  if (!repo) {
24433
24539
  problems.push("issue is required; LEGION_ISSUE needs a GitHub repository in cwd");
24434
- return { args, ref, owner: null };
24540
+ return { args, ref, owner: null, ownerMissing: true };
24435
24541
  }
24436
24542
  const issue = `${repo}#${legionIssue}`;
24437
24543
  return { args: { ...args, issue }, ref, owner: { kind: "issue", issue } };
24438
24544
  }
24439
- function restatesMissingOwner(issue) {
24440
- 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"));
24545
+ function withoutMissingOwner(issue) {
24546
+ if (issue.code === "invalid_type" && issue.path.length === 1 && issue.path[0] === "issue" && issue.input === undefined) {
24547
+ return;
24548
+ }
24549
+ if (issue.code !== "custom" || issue.path.length !== 0)
24550
+ return issue;
24551
+ const message = withoutOwnerRule(issue.message);
24552
+ return message === undefined ? undefined : message === issue.message ? issue : { ...issue, message };
24441
24553
  }
24442
24554
  function dispatchServerUrls(config) {
24443
24555
  return config.publicUrl === undefined ? [config.url] : [config.url, config.publicUrl];
@@ -24448,11 +24560,12 @@ async function checkDispatchCall(input) {
24448
24560
  const owner = await resolveOwnerArguments(tool, args, cwd, input.env ?? process.env, input.exec ?? defaultExec, input.serverUrls, problems);
24449
24561
  const conflicts = issueFreeTools[tool] === true ? [] : ownerConflictProblems(tool, args, owner.ref, optionalString(owner.args, "ref"));
24450
24562
  problems.push(...conflicts);
24451
- const ownerMissing = issueFreeTools[tool] !== true && (owner.owner === null || conflicts.length > 0);
24563
+ const ownerAlreadySaid = issueFreeTools[tool] !== true && (owner.owner === null || conflicts.length > 0);
24452
24564
  const schema = toolSchema(tool);
24453
- const parsed = schema.safeParse(owner.args, { reportInput: true });
24565
+ const standIn = owner.ownerMissing === true;
24566
+ const parsed = schema.safeParse(standIn ? { ...owner.args, issue: ownerStandInIssue } : owner.args, { reportInput: true });
24454
24567
  if (!parsed.success) {
24455
- const issues = ownerMissing ? parsed.error.issues.filter((issue) => !restatesMissingOwner(issue)) : parsed.error.issues;
24568
+ const issues = standIn ? parsed.error.issues : ownerAlreadySaid ? parsed.error.issues.flatMap((issue) => withoutMissingOwner(issue) ?? []) : parsed.error.issues;
24456
24569
  problems.push(...formatZodIssues(issues, schema, tool));
24457
24570
  }
24458
24571
  problems.push(...argumentProblems(tool, owner.args));
@@ -24460,7 +24573,7 @@ async function checkDispatchCall(input) {
24460
24573
  return {
24461
24574
  problems,
24462
24575
  owner,
24463
- args: parsed.success ? parsed.data : owner.args,
24576
+ args: parsed.success && !standIn ? parsed.data : owner.args,
24464
24577
  pictures
24465
24578
  };
24466
24579
  }
@@ -24478,7 +24591,75 @@ function refusalWithCode(error, ...clauses) {
24478
24591
  }
24479
24592
  if (!(error instanceof DispatchServiceError))
24480
24593
  return error;
24481
- return new DispatchServiceError(error.code, error.status, `${error.code}: ${error.message}${joined}`, error.candidates, error.current, error.mismatches);
24594
+ const told = joined !== "" && /[.!?]$/.test(error.message) ? `${error.message} ${suffix.charAt(0).toUpperCase()}${suffix.slice(1)}` : `${error.message}${joined}`;
24595
+ return new DispatchServiceError(error.code, error.status, `${error.code}: ${told}`, error);
24596
+ }
24597
+ function parentStatusConflictLines(error, tool, args, legionIssue) {
24598
+ if (!dispatchAnswered(error, 409) || error.code !== "PARENT_STATUS_CONFLICT")
24599
+ return;
24600
+ const issues = error.issues ?? [];
24601
+ if (issues.length === 0)
24602
+ return;
24603
+ const parents = issues.filter((issue) => issue.relation === "parent").map(({ key }) => key);
24604
+ const children = issues.filter((issue) => issue.relation === "child").map(({ key }) => key);
24605
+ return [
24606
+ messageFor(error),
24607
+ ...issues.map((issue) => `${issue.key} [${issue.status}] ${issue.title}`),
24608
+ ...nextSteps(tool, args, parents, children, legionIssue)
24609
+ ];
24610
+ }
24611
+ 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.";
24612
+ 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.";
24613
+ function otherProjectSentence(named, keys) {
24614
+ const project = named === undefined ? undefined : issueProject(named);
24615
+ if (project === undefined)
24616
+ return "";
24617
+ const others = keys.filter((key) => {
24618
+ const other = issueProject(key);
24619
+ return other !== undefined && other !== project;
24620
+ });
24621
+ if (others.length === 0)
24622
+ return "";
24623
+ const one = others.length === 1;
24624
+ 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.`;
24625
+ }
24626
+ function includeParentCall(key) {
24627
+ 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`;
24628
+ }
24629
+ function nextSteps(tool, args, parents, children, legionIssue) {
24630
+ if (tool === "dispatch_issue") {
24631
+ 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.`);
24632
+ }
24633
+ const issueUpdate = tool === "dispatch_issue_update";
24634
+ const written = issueUpdate ? args : {};
24635
+ const fields = Object.keys(written).filter((field) => field !== "issue" && written[field] !== undefined);
24636
+ const issue = optionalString(written, "issue");
24637
+ const named = issueUpdate ? issue ?? legionIssue : undefined;
24638
+ const childHolds = children.length > 0;
24639
+ const childScope = otherProjectSentence(named, children);
24640
+ const status = optionalString(written, "status");
24641
+ const parent = optionalString(written, "parent");
24642
+ const alone = `--status${status === "done" ? " and --reason" : ""} alone`;
24643
+ if (parent !== undefined && parent !== "") {
24644
+ const issueFlag = issue === undefined ? "" : ` --issue ${issue}`;
24645
+ const statusFlag = status === undefined || childHolds ? "" : ` --status ${status}`;
24646
+ const kept = fields.filter((field) => field !== "parent" && field !== "status" && !(childHolds && field === "reason"));
24647
+ const otherFlags = kept.length > 0 ? ", with the call's other flags" : "";
24648
+ const reparent = `dispatch issue-update${issueFlag} --parent ${parent}${statusFlag}${otherFlags}`;
24649
+ const afterStatus = childHolds ? ", after the status change," : "";
24650
+ return [
24651
+ ...childHolds ? [
24652
+ `${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}`
24653
+ ] : [],
24654
+ ...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}.`)
24655
+ ];
24656
+ }
24657
+ const others = ISSUE_UPDATE_PATCH_FIELDS.some((field) => written[field] !== undefined);
24658
+ const apart = (subject) => others ? ` ${subject} with ${alone}, so send the call's other changes in a call of their own.` : "";
24659
+ return [
24660
+ ...childHolds ? [`${CHILD_FLAGS}${apart("Each goes")}${childScope}`] : [],
24661
+ ...parents.length > 0 ? [`${PARENT_FLAG}${apart("It goes")}${otherProjectSentence(named, parents)}`] : []
24662
+ ];
24482
24663
  }
24483
24664
  function dispatchAnswered(error, status) {
24484
24665
  return error instanceof DispatchServiceError && error.fromDispatch && error.status === status;
@@ -24503,6 +24684,11 @@ function writeMayHaveLanded(error) {
24503
24684
  return error.mayHaveReachedDispatch;
24504
24685
  return !(error instanceof DispatchServiceError) || error.status >= 500;
24505
24686
  }
24687
+ function closeAccount(error, closingNote) {
24688
+ const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
24689
+ const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
24690
+ 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}`;
24691
+ }
24506
24692
  function withAccount(error, account) {
24507
24693
  const message = messageFor(error);
24508
24694
  const told = /[.!?]$/.test(message) ? `${message} ${account.charAt(0).toUpperCase()}${account.slice(1)}` : `${message}; ${account}`;
@@ -25856,6 +26042,85 @@ async function followedAskDetails(client, ask, artifact) {
25856
26042
  return { ...await askOwnerDetails(client, ask, artifact), follows: { ask: ask.id } };
25857
26043
  }
25858
26044
 
26045
+ // ../envoy-client/src/dispatch-commands/status-change.ts
26046
+ async function issuesBeforeStatusChange(client, before, options) {
26047
+ const issues = new Map([
26048
+ [before.key, { status: before.status, parent: before.parent ?? null }]
26049
+ ]);
26050
+ for (const child of before.children ?? []) {
26051
+ issues.set(child.key, { status: child.status, parent: before.key });
26052
+ }
26053
+ try {
26054
+ if (options.includes("include_children")) {
26055
+ for (const row of await client.listAllIssues({ project: before.project })) {
26056
+ issues.set(row.key, { status: row.status, parent: row.parent ?? null });
26057
+ }
26058
+ } else if (options.includes("include_parent")) {
26059
+ let parent = before.parent ?? null;
26060
+ while (parent !== null && !issues.has(parent)) {
26061
+ const above = await client.getIssue(parent);
26062
+ issues.set(above.key, { status: above.status, parent: above.parent ?? null });
26063
+ parent = above.parent ?? null;
26064
+ }
26065
+ }
26066
+ } catch (error) {
26067
+ throw refusalWithCode(error);
26068
+ }
26069
+ return issues;
26070
+ }
26071
+ async function statusChangeCommand(context, before, options, issuesBefore, closingNote) {
26072
+ const { args, client, actor, input, issue } = context;
26073
+ const status = stringArg(args, "status");
26074
+ const change = (entry) => {
26075
+ const was = issuesBefore.get(entry.key);
26076
+ if (entry.key !== before.key && entry.parent === null && was?.parent === before.key) {
26077
+ return `unlinked from ${before.key}`;
26078
+ }
26079
+ return was === undefined ? `status -> ${entry.status}` : `status ${was.status} -> ${entry.status}`;
26080
+ };
26081
+ let answer;
26082
+ try {
26083
+ answer = await client.changeIssueStatus(issue(), {
26084
+ status,
26085
+ ...options.includes("include_children") ? { include_children: true } : {},
26086
+ ...options.includes("unlink_children") ? { unlink_children: true } : {},
26087
+ ...options.includes("include_parent") ? { include_parent: true } : {},
26088
+ actor
26089
+ });
26090
+ } catch (error) {
26091
+ if (error instanceof DispatchWriteLandedError)
26092
+ throw error;
26093
+ const committed = error instanceof DispatchServiceError ? error.changed ?? [] : [];
26094
+ const changed = committed.length === 0 ? "" : `the steps before the refusal changed ${committed.map((entry) => `${entry.key} (${change(entry)})`).join(", ")}`;
26095
+ if (closingNote === undefined)
26096
+ throw refusalWithCode(error, changed);
26097
+ const landed = closeAccount(error, closingNote);
26098
+ if (error instanceof DispatchServiceError)
26099
+ throw refusalWithCode(error, changed, landed);
26100
+ throw withAccount(error, landed);
26101
+ }
26102
+ const suffix = await notSubscribed(issueTopic(before.key), input.subscriptions);
26103
+ const namedLine = (after) => `${before.key}: ${[
26104
+ ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
26105
+ `status ${before.status} -> ${after}`
26106
+ ].join("; ")}${suffix}`;
26107
+ const changed = answer.changed ?? [];
26108
+ const lines = changed.map((entry) => entry.key === before.key ? namedLine(entry.status) : `${entry.key}: ${change(entry)}`);
26109
+ if (!changed.some((entry) => entry.key === before.key))
26110
+ lines.push(namedLine(answer.issue.status));
26111
+ return {
26112
+ text: lines.join(`
26113
+ `),
26114
+ details: {
26115
+ issue: before.key,
26116
+ status: answer.issue.status,
26117
+ external_links: (answer.issue.external_links ?? []).map((link) => link.url),
26118
+ changed: changed.map(({ key, status, parent }) => ({ key, status, parent })),
26119
+ ...closingNote === undefined ? {} : { message: closingNote.id }
26120
+ }
26121
+ };
26122
+ }
26123
+
25859
26124
  // ../envoy-client/src/dispatch-commands/issues.ts
25860
26125
  function componentsChange(input, after) {
25861
26126
  switch (input.mode) {
@@ -26007,6 +26272,7 @@ async function issueUpdateCommand(context) {
26007
26272
  const advances = optionalStringArray(args, "advances");
26008
26273
  const advancesRevision = optionalNumber(args, "advances_revision");
26009
26274
  const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
26275
+ const options = issueStatusOptionsOf(args);
26010
26276
  let before;
26011
26277
  try {
26012
26278
  before = await client.getIssue(issueKey);
@@ -26017,6 +26283,7 @@ async function issueUpdateCommand(context) {
26017
26283
  if (status === "done" && typeof before.closed_at === "string") {
26018
26284
  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`);
26019
26285
  }
26286
+ const issuesBefore = options.length === 0 ? undefined : await issuesBeforeStatusChange(client, before, options);
26020
26287
  let closingNote;
26021
26288
  if (reason !== undefined) {
26022
26289
  try {
@@ -26035,6 +26302,9 @@ async function issueUpdateCommand(context) {
26035
26302
  throw withAccount(error, told);
26036
26303
  }
26037
26304
  }
26305
+ if (issuesBefore !== undefined) {
26306
+ return statusChangeCommand(context, before, options, issuesBefore, closingNote);
26307
+ }
26038
26308
  const existingLinks = before.external_links ?? [];
26039
26309
  const linked = existingLinks.map((link) => link.url);
26040
26310
  const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
@@ -26073,9 +26343,7 @@ async function issueUpdateCommand(context) {
26073
26343
  }
26074
26344
  throw refusalWithCode(error, taken);
26075
26345
  }
26076
- const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
26077
- const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
26078
- 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}`;
26346
+ const landed = closeAccount(error, closingNote);
26079
26347
  if (error instanceof DispatchServiceError)
26080
26348
  throw refusalWithCode(error, taken, landed);
26081
26349
  throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
@@ -26197,8 +26465,11 @@ async function relatedCommand(context) {
26197
26465
  details: { project, suggestions }
26198
26466
  };
26199
26467
  }
26468
+ function printsJson(tool, args) {
26469
+ return tool === "dispatch_issues" && args["json"] === true;
26470
+ }
26200
26471
  async function issuesCommand(context) {
26201
- const { args, client } = context;
26472
+ const { args, client, input } = context;
26202
26473
  const project = stringArg(args, "project");
26203
26474
  const status = optionalString(args, "status");
26204
26475
  const parent = optionalString(args, "parent");
@@ -26241,6 +26512,10 @@ async function issuesCommand(context) {
26241
26512
  updated_at: row.updated_at,
26242
26513
  progress: row.progress
26243
26514
  }));
26515
+ const listing = { issues: rows, total, offset, limit };
26516
+ if (printsJson(input.tool, args)) {
26517
+ return { text: JSON.stringify(listing), details: listing };
26518
+ }
26244
26519
  const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
26245
26520
  const isPartial = offset !== 0 || rows.length !== total;
26246
26521
  const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
@@ -26253,7 +26528,7 @@ async function issuesCommand(context) {
26253
26528
  })
26254
26529
  ].join(`
26255
26530
  `),
26256
- details: { issues: rows, total, offset, limit }
26531
+ details: listing
26257
26532
  };
26258
26533
  }
26259
26534
  function dryRunAsksDispatch(tool, args) {
@@ -28965,13 +29240,29 @@ async function whoamiCommand(context) {
28965
29240
  const service = identity.kind === "agent" ? identity.service ?? null : null;
28966
29241
  const proved = identity.kind === "agent" ? identity.session ?? null : null;
28967
29242
  const project = identity.kind === "agent" ? identity.project ?? null : null;
29243
+ const readOnly = identity.scopes?.includes("read") === true;
29244
+ const cut = identity.kind === "agent" ? identity.cut ?? null : null;
28968
29245
  const session = proved ?? sessionId;
28969
29246
  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.";
28970
29247
  const answered = identity.kind === "agent" ? identity.sign_in_required : undefined;
28971
29248
  const signInNeeded = answered ?? (owner === null && service !== null && proved !== null);
28972
- 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}`;
28973
- 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}.` : "";
28974
- const writable = project !== null ? ` It may write project ${project} and no other.` : "";
29249
+ const who = owner !== null ? `acts for ${owner}` : service !== null ? `runs as service ${serviceSubjectLabel(service)}` : "runs";
29250
+ const named = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId})` : "";
29251
+ let acting;
29252
+ let elsewhere = named === "" ? "" : `${named}: Dispatch records every write you make as ${proved}.`;
29253
+ if (readOnly) {
29254
+ 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.`}`;
29255
+ elsewhere = named === "" ? "" : `${named}.`;
29256
+ } else if (owner !== null) {
29257
+ acting = `Session ${session} ${who}: issues you create without an assignee are assigned to ${owner}.`;
29258
+ } else if (signInNeeded) {
29259
+ 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.`;
29260
+ } else if (service !== null) {
29261
+ acting = `Session ${session} ${who}: ${unowned}`;
29262
+ } else {
29263
+ acting = `Session ${session} runs under the shared token: ${unowned}`;
29264
+ }
29265
+ const writable = project !== null && !readOnly ? ` It may write project ${project} and no other.` : "";
28975
29266
  return {
28976
29267
  text: acting + elsewhere + writable,
28977
29268
  details: { session, owner, service, project }
@@ -31224,6 +31515,64 @@ async function genericGrantRequest(config, grantType, parameters, options) {
31224
31515
  return result;
31225
31516
  }
31226
31517
 
31518
+ // ../cipher-client/src/broker-request.ts
31519
+ var BROKER_URL_SETTING = "the broker URL";
31520
+ function statusOf(error) {
31521
+ let cause = error;
31522
+ for (let depth = 0;depth < 4; depth += 1) {
31523
+ if (cause instanceof Response)
31524
+ return cause.status;
31525
+ if (cause instanceof ResponseBodyError || cause instanceof WWWAuthenticateChallengeError) {
31526
+ return cause.status;
31527
+ }
31528
+ if (typeof cause !== "object" || cause === null || !("cause" in cause))
31529
+ return 0;
31530
+ cause = cause.cause;
31531
+ }
31532
+ return 0;
31533
+ }
31534
+ function brokerRefusal(doing, refused, endpoint, error, context = {}) {
31535
+ if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
31536
+ const description = error.error_description;
31537
+ return new BrokerRefusedError(error.status, error.error, typeof description === "string" ? description : "", refused, context);
31538
+ }
31539
+ const status = statusOf(error);
31540
+ const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
31541
+ return new BrokerTradeFailedError(`${doing} ${refused} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
31542
+ }
31543
+ function requestInit(options, signal, headers) {
31544
+ const signals = [options.signal, signal].filter((one) => one !== undefined);
31545
+ return {
31546
+ method: options.method,
31547
+ headers,
31548
+ body: options.body,
31549
+ redirect: options.redirect,
31550
+ ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
31551
+ };
31552
+ }
31553
+ async function sendWithProof(proved, url, options, signal) {
31554
+ const send = async () => {
31555
+ const headers = new Headers(options.headers);
31556
+ const request = { method: options.method, url, nonce: proved.nonce.value };
31557
+ headers.set("DPoP", await proved.key.proof(request));
31558
+ if (proved.holderKey !== undefined) {
31559
+ headers.set(HEADER_DPOP_HOLDER, await proved.holderKey.proof(request));
31560
+ }
31561
+ return await proved.fetch(url, requestInit(options, signal, headers));
31562
+ };
31563
+ let answer = await send();
31564
+ const given = answer.headers.get("DPoP-Nonce") ?? "";
31565
+ if (given !== "")
31566
+ proved.nonce.value = given;
31567
+ if (answer.status === 400 && given !== "") {
31568
+ const body = await answer.clone().json().catch(() => null);
31569
+ const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
31570
+ if (asked)
31571
+ answer = await send();
31572
+ }
31573
+ return answer;
31574
+ }
31575
+
31227
31576
  // ../cipher-client/src/device-login-file.ts
31228
31577
  import { createPrivateKey, randomUUID as randomUUID3 } from "crypto";
31229
31578
  import { constants as constants2 } from "fs";
@@ -31258,7 +31607,13 @@ import { basename as basename2, dirname as dirname2, join as join5 } from "path"
31258
31607
 
31259
31608
  // ../cipher-client/src/token-client.ts
31260
31609
  var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
31261
- var BROKER_URL_SETTING = "the broker URL";
31610
+ function renewalAt(expiresAt, now, renewBeforeMs) {
31611
+ const left = expiresAt - now;
31612
+ if (left <= 0)
31613
+ return now;
31614
+ return Math.max(expiresAt - renewBeforeMs, now + left / 2);
31615
+ }
31616
+ var EXPIRES_IN_STEP_MS = 1000;
31262
31617
  var RETRY_FIRST_WAIT_MS = 15000;
31263
31618
  var RETRY_MAX_WAIT_MS = 5 * 60000;
31264
31619
  var PENDING_FIRST_WAIT_MS = 2000;
@@ -31282,66 +31637,18 @@ function sleep2(ms, signal, holdsProcess = false) {
31282
31637
  signal?.addEventListener("abort", done, { once: true });
31283
31638
  return promise;
31284
31639
  }
31285
- function statusOf(error) {
31286
- let cause = error;
31287
- for (let depth = 0;depth < 4; depth += 1) {
31288
- if (cause instanceof Response)
31289
- return cause.status;
31290
- if (cause instanceof ResponseBodyError || cause instanceof WWWAuthenticateChallengeError) {
31291
- return cause.status;
31292
- }
31293
- if (typeof cause !== "object" || cause === null || !("cause" in cause))
31294
- return 0;
31295
- cause = cause.cause;
31296
- }
31297
- return 0;
31298
- }
31299
- function brokerRefusal(doing, refused, endpoint, error, context = {}) {
31300
- if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
31301
- const description = error.error_description;
31302
- return new BrokerRefusedError(error.status, error.error, typeof description === "string" ? description : "", refused, context);
31303
- }
31304
- const status = statusOf(error);
31305
- const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
31306
- return new BrokerTradeFailedError(`${doing} ${refused} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
31307
- }
31308
- function requestInit(options, signal, headers) {
31309
- const signals = [options.signal, signal].filter((one) => one !== undefined);
31310
- return {
31311
- method: options.method,
31312
- headers,
31313
- body: options.body,
31314
- redirect: options.redirect,
31315
- ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
31316
- };
31317
- }
31318
- async function sendWithProof(proved, url, options, signal) {
31319
- const send = async () => {
31320
- const headers = new Headers(options.headers);
31321
- headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
31322
- return await proved.fetch(url, requestInit(options, signal, headers));
31323
- };
31324
- let answer = await send();
31325
- const given = answer.headers.get("DPoP-Nonce") ?? "";
31326
- if (given !== "")
31327
- proved.nonce.value = given;
31328
- if (answer.status === 400 && given !== "") {
31329
- const body = await answer.clone().json().catch(() => null);
31330
- const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
31331
- if (asked)
31332
- answer = await send();
31333
- }
31334
- return answer;
31335
- }
31336
31640
 
31337
31641
  class BrokerTokenClient {
31338
31642
  #brokerUrl;
31339
31643
  #key;
31644
+ #holderKey;
31340
31645
  #subject;
31341
31646
  #actor;
31342
31647
  #session;
31343
31648
  #projects;
31344
31649
  #launcherCredential;
31650
+ #scope;
31651
+ #asOf;
31345
31652
  #renewBeforeMs;
31346
31653
  #now;
31347
31654
  #attemptMs;
@@ -31370,11 +31677,14 @@ class BrokerTokenClient {
31370
31677
  throw new Error("broker client: the broker URL is not an http or https URL");
31371
31678
  this.#brokerUrl = holdUrlUserinfo(brokerUrl);
31372
31679
  this.#key = options.key;
31680
+ this.#holderKey = options.holderKey;
31373
31681
  this.#subject = options.subject;
31374
31682
  this.#actor = options.actor;
31375
31683
  this.#session = options.session ?? "";
31376
31684
  this.#projects = [...options.projects ?? []];
31377
31685
  this.#launcherCredential = options.launcherCredential ?? true;
31686
+ this.#scope = options.scope ?? "";
31687
+ this.#asOf = options.asOf ?? "";
31378
31688
  this.#renewBeforeMs = options.renewBeforeMs ?? DEFAULT_RENEW_BEFORE_MS;
31379
31689
  this.#now = options.now ?? Date.now;
31380
31690
  this.#attemptMs = options.attemptMs ?? TRADE_ATTEMPT_MS;
@@ -31384,7 +31694,7 @@ class BrokerTokenClient {
31384
31694
  this.#random = options.random ?? Math.random;
31385
31695
  }
31386
31696
  get key() {
31387
- return this.#key;
31697
+ return this.#holderKey ?? this.#key;
31388
31698
  }
31389
31699
  describe() {
31390
31700
  return this.#subject.describe();
@@ -31393,10 +31703,11 @@ class BrokerTokenClient {
31393
31703
  const waitForReady = options.waitForReady === true;
31394
31704
  const now = this.#now();
31395
31705
  const held = this.#held;
31396
- if (held !== null && now < held.expiresAt.getTime() - this.#renewBeforeMs)
31397
- return held;
31398
- if (held !== null && now < held.expiresAt.getTime() && this.#last !== null)
31399
- return held;
31706
+ if (held !== null && now < held.renewsAt)
31707
+ return held.token;
31708
+ if (held !== null && now < held.token.expiresAt.getTime() && this.#last !== null) {
31709
+ return held.token;
31710
+ }
31400
31711
  const closed = this.#closed.signal;
31401
31712
  if (closed.aborted)
31402
31713
  throw closed.reason;
@@ -31430,8 +31741,8 @@ class BrokerTokenClient {
31430
31741
  const stop = () => {
31431
31742
  this.#waiters.delete(waiter);
31432
31743
  const held = this.#held;
31433
- if (held !== null && this.#now() < held.expiresAt.getTime())
31434
- resolve(held);
31744
+ if (held !== null && this.#now() < held.token.expiresAt.getTime())
31745
+ resolve(held.token);
31435
31746
  else
31436
31747
  reject(this.#stopped(signal?.reason));
31437
31748
  };
@@ -31471,7 +31782,7 @@ class BrokerTokenClient {
31471
31782
  });
31472
31783
  }
31473
31784
  drop(accessToken) {
31474
- if (accessToken !== undefined && this.#held?.accessToken !== accessToken)
31785
+ if (accessToken !== undefined && this.#held?.token.accessToken !== accessToken)
31475
31786
  return;
31476
31787
  this.#held = null;
31477
31788
  }
@@ -31502,7 +31813,10 @@ class BrokerTokenClient {
31502
31813
  if (this.#pendingSaid !== null && this.#since !== null) {
31503
31814
  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`);
31504
31815
  }
31505
- this.#held = token;
31816
+ this.#held = {
31817
+ token,
31818
+ renewsAt: renewalAt(token.expiresAt.getTime(), this.#now(), this.#renewBeforeMs)
31819
+ };
31506
31820
  this.#last = null;
31507
31821
  this.#since = null;
31508
31822
  this.#failed = 0;
@@ -31542,8 +31856,8 @@ class BrokerTokenClient {
31542
31856
  this.#since ??= now;
31543
31857
  this.#failed += 1;
31544
31858
  const held = this.#held;
31545
- if (held !== null && now < held.expiresAt.getTime()) {
31546
- this.#tell((waiter) => waiter.resolve(held));
31859
+ if (held !== null && now < held.token.expiresAt.getTime()) {
31860
+ this.#tell((waiter) => waiter.resolve(held.token));
31547
31861
  } else {
31548
31862
  this.#held = null;
31549
31863
  if (failure.kind !== "pending") {
@@ -31595,7 +31909,8 @@ class BrokerTokenClient {
31595
31909
  async#trade(signal) {
31596
31910
  const source = this.#subject;
31597
31911
  if (source.spend !== undefined) {
31598
- return await source.spend((subject) => this.#exchange(subject, signal), signal);
31912
+ const leastLifeMs = this.#scope === SCOPE_READ ? this.#renewBeforeMs + EXPIRES_IN_STEP_MS : undefined;
31913
+ return await source.spend((subject) => this.#exchange(subject, signal), signal, leastLifeMs);
31599
31914
  }
31600
31915
  return await this.#exchange(await source.read(signal), signal);
31601
31916
  }
@@ -31609,6 +31924,10 @@ class BrokerTokenClient {
31609
31924
  form[FORM_SESSION] = this.#session;
31610
31925
  if (this.#projects.length > 0)
31611
31926
  form[FORM_PROJECTS] = this.#projects.join(" ");
31927
+ if (this.#scope !== "")
31928
+ form[FORM_SCOPE] = this.#scope;
31929
+ if (this.#asOf !== "")
31930
+ form[FORM_AS_OF] = this.#asOf;
31612
31931
  if (!this.#launcherCredential) {
31613
31932
  form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
31614
31933
  }
@@ -31641,7 +31960,7 @@ class BrokerTokenClient {
31641
31960
  return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
31642
31961
  }
31643
31962
  async#send(url, options, signal, raw) {
31644
- const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
31963
+ const answer = await sendWithProof({ key: this.#key, holderKey: this.#holderKey, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
31645
31964
  raw.body = await answer.clone().json().catch(() => {
31646
31965
  return;
31647
31966
  });
@@ -31904,6 +32223,10 @@ function member(json, name) {
31904
32223
  const value = json[name];
31905
32224
  return typeof value === "string" ? value : "";
31906
32225
  }
32226
+ function wholeMember(json, name) {
32227
+ const value = json[name];
32228
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
32229
+ }
31907
32230
  function checkPrivate(info, what, forbidden, opens, notOwned) {
31908
32231
  const mode = info.mode & 511;
31909
32232
  if ((mode & forbidden) !== 0) {
@@ -32261,7 +32584,8 @@ async function readDeviceLogin(path) {
32261
32584
  expiresAt,
32262
32585
  broker,
32263
32586
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
32264
- accessExpiresAt: accessUsable ? accessExpiresAt : null
32587
+ accessExpiresAt: accessUsable ? accessExpiresAt : null,
32588
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
32265
32589
  };
32266
32590
  }
32267
32591
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -32294,7 +32618,8 @@ async function saveDeviceLogin(path, login, held, keep = false) {
32294
32618
  broker: login.broker,
32295
32619
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
32296
32620
  access_token: login.accessToken,
32297
- access_expires_at: login.accessExpiresAt.toISOString()
32621
+ access_expires_at: login.accessExpiresAt.toISOString(),
32622
+ ...login.accessLifeSeconds === null ? {} : { access_life_seconds: login.accessLifeSeconds }
32298
32623
  }
32299
32624
  });
32300
32625
  await deviceLoginPlace(path);
@@ -32416,6 +32741,11 @@ async function importDpopKey(pkcs8Pem, name) {
32416
32741
  // ../cipher-client/src/device-login.ts
32417
32742
  var BROKER_SETTING = "AGENT_SECRETS_URL";
32418
32743
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
32744
+ function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
32745
+ if (leastLifeMs === undefined || lifeSeconds === null)
32746
+ return ACCESS_MARGIN_MS;
32747
+ return Math.max(ACCESS_MARGIN_MS, Math.min(leastLifeMs, lifeSeconds * 1000 / 2));
32748
+ }
32419
32749
  var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
32420
32750
  var DEFAULT_POLL_SECONDS = 5;
32421
32751
  var LEAST_POLL_SECONDS = 1;
@@ -32491,7 +32821,8 @@ function loginOf(key, broker, answered, now) {
32491
32821
  expiresAt,
32492
32822
  broker,
32493
32823
  accessToken: holdSecret(answered.access_token, accessExpiresAt),
32494
- accessExpiresAt
32824
+ accessExpiresAt,
32825
+ accessLifeSeconds: seconds
32495
32826
  };
32496
32827
  }
32497
32828
  async function startDeviceLogin(options) {
@@ -32623,7 +32954,7 @@ class DeviceLoginIdentity {
32623
32954
  }
32624
32955
  return this.#key;
32625
32956
  }
32626
- async spend(trade, signal) {
32957
+ async spend(trade, signal, leastLifeMs) {
32627
32958
  const { thumbprint } = await this.#loaded();
32628
32959
  return await withDeviceLoginLock(this.#path, async (held) => {
32629
32960
  let login = await readDeviceLogin(this.#path);
@@ -32635,7 +32966,8 @@ class DeviceLoginIdentity {
32635
32966
  }
32636
32967
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
32637
32968
  const expires = login.accessExpiresAt?.getTime() ?? 0;
32638
- let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
32969
+ const least = leastAccessLifeMs(leastLifeMs, login.accessLifeSeconds);
32970
+ let refreshed = login.accessToken === "" || expires - Date.now() < least;
32639
32971
  if (refreshed)
32640
32972
  login = await refresh();
32641
32973
  while (true) {
@@ -33083,13 +33415,15 @@ function tradeProjects(env) {
33083
33415
  }
33084
33416
  return sorted;
33085
33417
  }
33086
- async function brokerTokenClient(env, own = "") {
33418
+ async function brokerTokenClient(env, own = "", read) {
33087
33419
  const brokerUrl = value(env, BROKER_URL_VAR);
33088
33420
  const machine = machineIdentity(env);
33089
33421
  if (brokerUrl === "" || machine === undefined)
33090
33422
  return;
33091
33423
  if (!isHttpUrl(brokerUrl))
33092
33424
  throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
33425
+ const narrowed = read === undefined ? {} : { scope: SCOPE_READ, asOf: read.asOf };
33426
+ const heldApart = async () => read === undefined ? {} : { ...narrowed, holderKey: await newDpopKey() };
33093
33427
  if (machine instanceof DeviceLoginIdentity) {
33094
33428
  if (personTradeOff(env)) {
33095
33429
  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`);
@@ -33099,7 +33433,8 @@ async function brokerTokenClient(env, own = "") {
33099
33433
  key: await machine.key(),
33100
33434
  subject: machine,
33101
33435
  session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
33102
- projects: tradeProjects(env)
33436
+ projects: tradeProjects(env),
33437
+ ...await heldApart()
33103
33438
  });
33104
33439
  return { client, signIn: undefined };
33105
33440
  }
@@ -33110,7 +33445,8 @@ async function brokerTokenClient(env, own = "") {
33110
33445
  key: await newDpopKey(),
33111
33446
  subject: machine,
33112
33447
  session: tradeSession(env, own),
33113
- launcherCredential: false
33448
+ launcherCredential: false,
33449
+ ...narrowed
33114
33450
  });
33115
33451
  return { client, signIn: undefined };
33116
33452
  }
@@ -33124,7 +33460,8 @@ async function brokerTokenClient(env, own = "") {
33124
33460
  subject: personIdentity(record, flow),
33125
33461
  actor: machine,
33126
33462
  session: own.trim() || signInSessionName(record),
33127
- projects: tradeProjects(env)
33463
+ projects: tradeProjects(env),
33464
+ ...await heldApart()
33128
33465
  });
33129
33466
  return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
33130
33467
  }
@@ -33157,11 +33494,11 @@ function forgetBrokerSession(session) {
33157
33494
  function signInName(record) {
33158
33495
  return `${record.person}\x00${record.thumbprint}`;
33159
33496
  }
33160
- function keyOf(env, own) {
33161
- return {
33162
- session: own.trim(),
33163
- variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
33164
- };
33497
+ function keyOf(env, own, read) {
33498
+ const values = BROKER_VARIABLES.map((name) => env[name]);
33499
+ if (read !== undefined)
33500
+ values.push({ read: true, asOf: read.asOf ?? "" });
33501
+ return { session: own.trim(), variables: JSON.stringify(values) };
33165
33502
  }
33166
33503
  function entryFor(key) {
33167
33504
  let sessions = CLIENTS.get(key.session);
@@ -33176,13 +33513,13 @@ function entryFor(key) {
33176
33513
  }
33177
33514
  return entry;
33178
33515
  }
33179
- async function make(env, own) {
33180
- const made = await brokerTokenClient(env, own);
33516
+ async function make(env, own, read) {
33517
+ const made = await brokerTokenClient(env, own, read);
33181
33518
  const signIn = made?.signIn;
33182
33519
  return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
33183
33520
  }
33184
- async function clientFor(env, own) {
33185
- const key = keyOf(env, own);
33521
+ async function clientFor(env, own, read) {
33522
+ const key = keyOf(env, own, read);
33186
33523
  const entry = entryFor(key);
33187
33524
  if (entry.refused.size > 0) {
33188
33525
  const record = await chooseSignIn(env);
@@ -33197,7 +33534,7 @@ async function clientFor(env, own) {
33197
33534
  }
33198
33535
  let making = entry.making;
33199
33536
  if (making === undefined) {
33200
- const started = make(env, key.session);
33537
+ const started = make(env, key.session, read);
33201
33538
  making = started;
33202
33539
  entry.making = started;
33203
33540
  started.then((made) => {
@@ -33227,13 +33564,13 @@ function untilAborted(promise, signal) {
33227
33564
  });
33228
33565
  });
33229
33566
  }
33230
- async function tradedToken(env, own, signal, waitForReady = false) {
33231
- const { entry, made } = await untilAborted(clientFor(env, own), signal);
33567
+ async function tradedToken(env, own, { signal, waitForReady = false, read }) {
33568
+ const { entry, made } = await untilAborted(clientFor(env, own, read), signal);
33232
33569
  const { client } = made;
33233
33570
  if (client === undefined) {
33234
33571
  throw new LoggableError("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
33235
33572
  }
33236
- const { session, variables } = keyOf(env, own);
33573
+ const { session, variables } = keyOf(env, own, read);
33237
33574
  try {
33238
33575
  return {
33239
33576
  token: await client.token(signal, { waitForReady }),
@@ -33248,7 +33585,7 @@ async function tradedToken(env, own, signal, waitForReady = false) {
33248
33585
  }
33249
33586
  }
33250
33587
  function brokerTokenFor(env, session) {
33251
- return (signal, waitForReady) => tradedToken(env, sessionName(session), signal, waitForReady);
33588
+ return (signal, waitForReady) => tradedToken(env, sessionName(session), { signal, waitForReady });
33252
33589
  }
33253
33590
  function dropHeld(key, token) {
33254
33591
  CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop(token);
@@ -33256,14 +33593,14 @@ function dropHeld(key, token) {
33256
33593
  function dropTradedToken(env, traded) {
33257
33594
  dropHeld(keyOf(env, traded.session), traded.token.accessToken);
33258
33595
  }
33259
- function brokerCredential(env, session) {
33596
+ function brokerCredential(env, session, read) {
33260
33597
  let presented = "";
33261
33598
  const presentedAs = new WeakMap;
33262
33599
  const own = (acting) => (acting ?? "").trim() || sessionName(session);
33263
33600
  return {
33264
33601
  scheme: "DPoP",
33265
33602
  async headers(method, url, acting, signal) {
33266
- const traded = await tradedToken(env, own(acting), signal);
33603
+ const traded = await tradedToken(env, own(acting), { signal, read });
33267
33604
  const { token, key, identity } = traded;
33268
33605
  presented = token.accessToken;
33269
33606
  const headers = {
@@ -33272,7 +33609,7 @@ function brokerCredential(env, session) {
33272
33609
  };
33273
33610
  presentedAs.set(headers, {
33274
33611
  identity,
33275
- key: keyOf(env, traded.session),
33612
+ key: keyOf(env, traded.session, read),
33276
33613
  token: token.accessToken
33277
33614
  });
33278
33615
  return headers;
@@ -33280,8 +33617,61 @@ function brokerCredential(env, session) {
33280
33617
  identity: (headers) => presentedAs.get(headers)?.identity,
33281
33618
  stale(acting, headers) {
33282
33619
  const told = headers === undefined ? undefined : presentedAs.get(headers);
33283
- dropHeld(told?.key ?? keyOf(env, own(acting)), told?.token);
33620
+ dropHeld(told?.key ?? keyOf(env, own(acting), read), told?.token);
33621
+ },
33622
+ secret: () => presented
33623
+ };
33624
+ }
33625
+
33626
+ // ../envoy-client/src/file-token-credential.ts
33627
+ import { readFileSync as readFileSync4 } from "fs";
33628
+ var TOKEN_FILE_VAR = "DISPATCH_BROKER_TOKEN_FILE";
33629
+ var DPOP_KEY_FILE_VAR = "DISPATCH_BROKER_DPOP_KEY_FILE";
33630
+ var PKCS8_LABEL = "PRIVATE KEY";
33631
+ var PKCS8_PEM = new RegExp(`^-----BEGIN ${PKCS8_LABEL}-----\\r?\\n(?:[A-Za-z0-9+/=]+\\r?\\n)+-----END ${PKCS8_LABEL}-----$`);
33632
+ function readNamed(variable, filePath) {
33633
+ try {
33634
+ return readFileSync4(filePath, "utf8");
33635
+ } catch (error) {
33636
+ throw new Error(`${variable} names ${filePath}, which could not be read (${readErrorCode(error)})`);
33637
+ }
33638
+ }
33639
+ function tokenIn(filePath) {
33640
+ const token = readNamed(TOKEN_FILE_VAR, filePath).trim();
33641
+ if (token === "") {
33642
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds no token: it is empty or blank`);
33643
+ }
33644
+ if (!sendable(token)) {
33645
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds whitespace or a control character inside its token`);
33646
+ }
33647
+ return holdSecret(token);
33648
+ }
33649
+ async function keyIn(filePath) {
33650
+ const pem = readNamed(DPOP_KEY_FILE_VAR, filePath).trim();
33651
+ if (!PKCS8_PEM.test(pem)) {
33652
+ throw new Error(`${DPOP_KEY_FILE_VAR} names ${filePath}, which does not hold one P-256 private key in PKCS#8 PEM`);
33653
+ }
33654
+ return await importDpopKey(pem, `${DPOP_KEY_FILE_VAR}'s key ${filePath}`);
33655
+ }
33656
+ function fileTokenCredential(files, dispatchUrl) {
33657
+ const origin = httpUrl2(dispatchUrl)?.origin;
33658
+ let presented = "";
33659
+ return {
33660
+ scheme: "DPoP",
33661
+ async headers(method, url) {
33662
+ const target = httpUrl2(url)?.origin;
33663
+ if (origin === undefined || target !== origin) {
33664
+ 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"}`);
33665
+ }
33666
+ const token = tokenIn(files.tokenFile);
33667
+ const key = await keyIn(files.keyFile);
33668
+ presented = token;
33669
+ return {
33670
+ Authorization: `DPoP ${token}`,
33671
+ DPoP: await key.proof({ method, url, accessToken: token })
33672
+ };
33284
33673
  },
33674
+ stale() {},
33285
33675
  secret: () => presented
33286
33676
  };
33287
33677
  }
@@ -33330,13 +33720,19 @@ function lostDispatchUrlNotice(env, config) {
33330
33720
  ].join("; ");
33331
33721
  }
33332
33722
  function dispatchSettings(env, config, options = {}) {
33333
- const target = dispatchTarget(env, config);
33723
+ const target = dispatchTarget(env, config, options.tokenFiles === true);
33334
33724
  if (!target.enabled)
33335
33725
  return target;
33336
33726
  const { url, urlSetting, source } = target;
33337
33727
  let credential;
33338
33728
  try {
33339
- credential = source.kind === "broker" ? brokerCredential(env, options.session) : bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
33729
+ if (source.kind === "broker")
33730
+ credential = brokerCredential(env, options.session, source.read);
33731
+ else if (source.kind === "files")
33732
+ credential = fileTokenCredential(source, url);
33733
+ else {
33734
+ credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
33735
+ }
33340
33736
  } catch (error) {
33341
33737
  return offWithError(messageFor(error));
33342
33738
  }
@@ -33359,6 +33755,63 @@ function dispatchUrl(env, config) {
33359
33755
  const target = dispatchTarget(env, config);
33360
33756
  return target.enabled ? target.url : undefined;
33361
33757
  }
33758
+ var BESIDE_TOKEN_FILES = [
33759
+ "DISPATCH_TOKEN_BROKER",
33760
+ "DISPATCH_TOKEN_BROKER_READ",
33761
+ "DISPATCH_TOKEN_BROKER_AS_OF",
33762
+ "DISPATCH_TOKEN",
33763
+ "DISPATCH_TOKEN_FILE",
33764
+ BROKER_URL_VAR,
33765
+ IDENTITY_VAR
33766
+ ];
33767
+ function tokenFilesSet(env) {
33768
+ const set = [
33769
+ ...nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE) === undefined ? [] : [TOKEN_FILE_VAR],
33770
+ ...nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE) === undefined ? [] : [DPOP_KEY_FILE_VAR]
33771
+ ];
33772
+ if (set.length === 0)
33773
+ return;
33774
+ return `${set.join(" and ")} ${set.length === 1 ? "is" : "are"} set`;
33775
+ }
33776
+ function settingsBesideTokenFiles(env) {
33777
+ return BESIDE_TOKEN_FILES.filter((name) => nonEmpty(env[name]) !== undefined).map((name) => `${name} is set`);
33778
+ }
33779
+ function tokenFilesTarget(env, config, taken) {
33780
+ const set = tokenFilesSet(env);
33781
+ if (set === undefined)
33782
+ return;
33783
+ if (!taken) {
33784
+ return offWithError(`${set}, and only the dispatch command reads the token files: Dispatch is off here rather than written with another credential beside them`);
33785
+ }
33786
+ const tokenFile = nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE);
33787
+ const keyFile = nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE);
33788
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
33789
+ const { checkout } = config;
33790
+ const problems = [
33791
+ ...tokenFile === undefined ? [`${TOKEN_FILE_VAR} is not set`] : [],
33792
+ ...keyFile === undefined ? [`${DPOP_KEY_FILE_VAR} is not set`] : [],
33793
+ ...explicitUrl === undefined ? ["DISPATCH_URL is not set"] : [],
33794
+ ...settingsBesideTokenFiles(env),
33795
+ ...config.dispatch.token === undefined ? [] : [`dispatch.token is set in ${config.path}`],
33796
+ ...checkout?.kind === "valid" && checkout.dispatch.token !== undefined ? [`dispatch.token is set in ${checkout.path}`] : [],
33797
+ ...checkout?.kind === "invalid" ? [`${checkout.error}, so whether it sets dispatch.token cannot be told`] : []
33798
+ ];
33799
+ if (problems.length > 0 || tokenFile === undefined || keyFile === undefined || explicitUrl === undefined) {
33800
+ 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("; ")}`);
33801
+ }
33802
+ if (config.dispatch.enabled === false) {
33803
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
33804
+ }
33805
+ if (httpUrl2(explicitUrl) === undefined) {
33806
+ return offWithError("DISPATCH_URL must be an http or https URL");
33807
+ }
33808
+ return {
33809
+ enabled: true,
33810
+ url: withoutTrailingSlashes(explicitUrl),
33811
+ urlSetting: "DISPATCH_URL",
33812
+ source: { kind: "files", tokenFile, keyFile }
33813
+ };
33814
+ }
33362
33815
  function brokerRouteForced(env) {
33363
33816
  const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
33364
33817
  if (written === "")
@@ -33367,12 +33820,55 @@ function brokerRouteForced(env) {
33367
33820
  return true;
33368
33821
  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");
33369
33822
  }
33370
- function dispatchTarget(env, config) {
33823
+ var CUT_FORM = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
33824
+ var ZERO_TIME = Date.parse("0001-01-01T00:00:00.000Z");
33825
+ function isCut(text) {
33826
+ const parts = CUT_FORM.exec(text);
33827
+ if (parts === null)
33828
+ return false;
33829
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = parts.slice(1, 7).map((part) => Number(part ?? "0"));
33830
+ const [zoneHour = 0, zoneMinute = 0] = parts.slice(9, 11).map((part) => Number(part ?? "0"));
33831
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
33832
+ const exists = month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth && hour <= 23 && minute <= 59 && second <= 59 && zoneHour <= 23 && zoneMinute <= 59;
33833
+ if (!exists)
33834
+ return false;
33835
+ const offset = (parts[8] === "-" ? -1 : 1) * (zoneHour * 60 + zoneMinute);
33836
+ const instant = new Date(0);
33837
+ instant.setUTCFullYear(year, month - 1, day);
33838
+ instant.setUTCHours(hour, minute - offset, second, 0);
33839
+ return Number(parts[7] ?? "0") !== 0 || instant.getTime() !== ZERO_TIME;
33840
+ }
33841
+ function readTradeSetting(env) {
33842
+ const read = (env.DISPATCH_TOKEN_BROKER_READ ?? "").trim();
33843
+ const cut = (env.DISPATCH_TOKEN_BROKER_AS_OF ?? "").trim();
33844
+ if (read !== "" && read !== "1") {
33845
+ 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");
33846
+ }
33847
+ if (read === "") {
33848
+ if (cut === "")
33849
+ return;
33850
+ 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");
33851
+ }
33852
+ if (cut === "")
33853
+ return {};
33854
+ if (!isCut(cut)) {
33855
+ 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");
33856
+ }
33857
+ return { asOf: cut };
33858
+ }
33859
+ function dispatchTarget(env, config, tokenFiles = false) {
33371
33860
  if (config.kind === "failed")
33372
33861
  return offWithError(config.error);
33373
- const forced = brokerRouteForced(env);
33374
- if (typeof forced !== "boolean")
33375
- return forced;
33862
+ const files = tokenFilesTarget(env, config, tokenFiles);
33863
+ if (files !== undefined)
33864
+ return files;
33865
+ const brokerOnly = brokerRouteForced(env);
33866
+ if (typeof brokerOnly !== "boolean")
33867
+ return brokerOnly;
33868
+ const read = readTradeSetting(env);
33869
+ if (read !== undefined && "enabled" in read)
33870
+ return read;
33871
+ const forced = brokerOnly || read !== undefined;
33376
33872
  const explicitUrl = nonEmpty(env.DISPATCH_URL);
33377
33873
  const checkoutFile = explicitUrl === undefined ? config.checkout : null;
33378
33874
  if (checkoutFile?.kind === "invalid")
@@ -33414,10 +33910,10 @@ function dispatchTarget(env, config) {
33414
33910
  if (route.traded) {
33415
33911
  const brokered = withoutTrailingSlashes(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
33416
33912
  const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
33417
- return { enabled: true, url: brokered, urlSetting, source: { kind: "broker" } };
33913
+ return { enabled: true, url: brokered, urlSetting, source: { kind: "broker", read } };
33418
33914
  }
33419
33915
  if (forced) {
33420
- 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`);
33916
+ 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`);
33421
33917
  }
33422
33918
  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}`);
33423
33919
  }
@@ -33603,7 +34099,6 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
33603
34099
  admissions: () => admissions
33604
34100
  };
33605
34101
  }
33606
- var RENEW_FLOOR_MS = 1000;
33607
34102
  var RETRY_FIRST_MS = 2000;
33608
34103
  var RETRY_LAST_MS = 60000;
33609
34104
  var WARN_AGAIN_MS = 30 * 60000;
@@ -33660,11 +34155,7 @@ function warnedEvery(warn) {
33660
34155
  };
33661
34156
  }
33662
34157
  function renewDelay(expiry, now) {
33663
- const remaining = expiry - now;
33664
- if (remaining <= 0)
33665
- return 0;
33666
- const ahead = remaining - Math.min(DEFAULT_RENEW_BEFORE_MS, remaining / 2);
33667
- return Math.max(Math.min(RENEW_FLOOR_MS, remaining / 2), ahead);
34158
+ return renewalAt(expiry, now, DEFAULT_RENEW_BEFORE_MS) - now;
33668
34159
  }
33669
34160
  function keepNatsCredential(connection, credential, warn) {
33670
34161
  let stopped = false;
@@ -34103,7 +34594,8 @@ function sessionDispatchSettings(file, env, options) {
34103
34594
  return {
34104
34595
  dispatch: dispatchSettings(env, config, {
34105
34596
  commands: options.commands,
34106
- session: options.session
34597
+ session: options.session,
34598
+ tokenFiles: options.tokenFiles
34107
34599
  }),
34108
34600
  warnings: config.kind === "read" ? config.warnings : [],
34109
34601
  missing: config.kind === "read" ? config.missing : null
@@ -34142,7 +34634,7 @@ function claudeProjectDirectory(environment, fallback) {
34142
34634
 
34143
34635
  // src/codex/codex-session-record.ts
34144
34636
  import { spawnSync } from "child_process";
34145
- import { readFileSync as readFileSync5, readlinkSync as readlinkSync2, unwatchFile, watchFile } from "fs";
34637
+ import { readFileSync as readFileSync6, readlinkSync as readlinkSync2, unwatchFile, watchFile } from "fs";
34146
34638
  import { mkdir as mkdir3, readFile as readFile5, rename as rename4, utimes as utimes3, writeFile as writeFile2 } from "fs/promises";
34147
34639
  import { homedir as homedir3 } from "os";
34148
34640
  import { basename as basename4, dirname as dirname5, join as join9 } from "path";
@@ -34152,7 +34644,7 @@ import { readFile as readFile4 } from "fs/promises";
34152
34644
  import { basename as basename3, join as join8 } from "path";
34153
34645
 
34154
34646
  // src/session-state.ts
34155
- import { readFileSync as readFileSync4 } from "fs";
34647
+ import { readFileSync as readFileSync5 } from "fs";
34156
34648
  import { mkdir as mkdir2, readdir as readdir3, rename as rename3, rm as rm3, stat as stat3, utimes as utimes2, writeFile } from "fs/promises";
34157
34649
  import { dirname as dirname4, join as join7 } from "path";
34158
34650
  async function writeAtomicStateFile(file, contents) {
@@ -34198,7 +34690,7 @@ async function removeChosenTitle(file) {
34198
34690
  }
34199
34691
  function readChosenTitleSync(file) {
34200
34692
  try {
34201
- return readFileSync4(file, "utf8");
34693
+ return readFileSync5(file, "utf8");
34202
34694
  } catch {
34203
34695
  return;
34204
34696
  }
@@ -34391,14 +34883,14 @@ function codexProcessId(readComm = procComm, readParent = procParent) {
34391
34883
  }
34392
34884
  function procComm(pid) {
34393
34885
  try {
34394
- return readFileSync5(`/proc/${pid}/comm`, "utf8").trim();
34886
+ return readFileSync6(`/proc/${pid}/comm`, "utf8").trim();
34395
34887
  } catch {
34396
34888
  return;
34397
34889
  }
34398
34890
  }
34399
34891
  function procParent(pid) {
34400
34892
  try {
34401
- const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
34893
+ const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
34402
34894
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
34403
34895
  return Number.isInteger(parent) ? parent : undefined;
34404
34896
  } catch {
@@ -34412,7 +34904,7 @@ var PS_OPTIONS = {
34412
34904
  };
34413
34905
  function procStarted(pid) {
34414
34906
  try {
34415
- const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
34907
+ const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
34416
34908
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
34417
34909
  } catch {
34418
34910
  return;
@@ -34433,7 +34925,7 @@ function recordOfProcess(record, pid) {
34433
34925
  function sharedAppServer(pid) {
34434
34926
  let argv;
34435
34927
  try {
34436
- argv = readFileSync5(`/proc/${pid}/cmdline`, "utf8").split("\x00");
34928
+ argv = readFileSync6(`/proc/${pid}/cmdline`, "utf8").split("\x00");
34437
34929
  } catch {
34438
34930
  const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS);
34439
34931
  if (ps.status !== 0)