@sjawhar/claude-envoy 6.19.0 → 6.20.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.
@@ -3038,7 +3038,7 @@ var POLICY_REFUSAL_PATTERNS = [
3038
3038
  policy("sessionFixed", "%s's tokens all name the session %s, which every pod of it may use, so its pods are registered for no name", K8S_ACCOUNT, FIXED_SESSION),
3039
3039
  policy("sessionInvalid", "the registration of %s names a session of %d bytes; %s", K8S_ACCOUNT, NUMBER, SESSION_RULE),
3040
3040
  policy("noEntry", "%s ran %s, whose job is written in %s; an entry lists the workflow a job runs in", REPOSITORY, WORKFLOW_REF, WORKFLOW_REF),
3041
- policy("claimMissing", "the subject token's workflow_ref is not <owner>/<name>/<path>@<ref> under its repository %s", REPOSITORY),
3041
+ policy("claimMissing", "the subject token's workflow_ref %s is not %s/<path>@%s: its repository, the path of its workflow file and its ref", WORKFLOW_REF, REPOSITORY, GIT_REF),
3042
3042
  policy("noEntry", "no entry lists the workflow %s of %s on %s", WORKFLOW_PATH, REPOSITORY, GIT_REF),
3043
3043
  policy("claimMissing", "the subject token carries no email claim, so it names no account (ask for it with format=full)"),
3044
3044
  policy("noEntry", "no entry lists the Google account %s", EMAIL),
@@ -17477,6 +17477,12 @@ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
17477
17477
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
17478
17478
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
17479
17479
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
17480
+ var SPEC_CHECK_OBSERVED_MAX = 2000;
17481
+ var SPEC_CHECK_OBSERVED_CUT_NOTE = `
17482
+ [The middle of the text is cut here. A result keeps ${SPEC_CHECK_OBSERVED_MAX} characters of what the job observed: its start and its end.]
17483
+ `;
17484
+ var SPEC_CHECK_OBSERVED_START = 500;
17485
+ var SPEC_CHECK_OBSERVED_END = SPEC_CHECK_OBSERVED_MAX - SPEC_CHECK_OBSERVED_START - [...SPEC_CHECK_OBSERVED_CUT_NOTE].length;
17480
17486
  function retriesUnderKey(status, code) {
17481
17487
  return outage(status) || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
17482
17488
  }
@@ -18078,8 +18084,16 @@ var RESULT_RECORD_FIELDS = [
18078
18084
  "excluded",
18079
18085
  "screenshots"
18080
18086
  ];
18087
+ var RESULT_PROJECT_FIELDS = ["check", "verdict", "commit", "observed"];
18088
+ var RESULT_PROJECT_REQUIRED = ["check", "verdict", "commit"];
18081
18089
  var RESULT_RETRACT_RULE = "Pass retract with the id of a result recorded before, and reason with why that result is " + "wrong, to retract it.";
18082
- var RESULT_SHAPE_RULE = `${RESULT_RETRACT_RULE} A call with retract takes reason and no other argument. A call ` + "without retract records a result, and it takes issue, check, role, verdict and commit.";
18090
+ var RESULT_PROJECT_RULE = "With project, the call records a CI job's result of a check of the spec files. It takes " + "project, check, verdict, commit and observed, and no other argument.";
18091
+ var RESULT_NOT_PROJECT_FIELDS = [
18092
+ ...RESULT_RECORD_FIELDS.filter((field) => !RESULT_PROJECT_FIELDS.includes(field)),
18093
+ "retract",
18094
+ "reason"
18095
+ ];
18096
+ var RESULT_SHAPE_RULE = `${RESULT_RETRACT_RULE} A call with retract takes reason and no other argument. A call ` + "without retract records a result, and it takes issue, check, role, verdict and commit. " + RESULT_PROJECT_RULE;
18083
18097
  var DEPLOY_REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
18084
18098
  var DEPLOY_PROGRAM = /^[a-z0-9-]{1,64}$/;
18085
18099
  var DEPLOY_COMMIT = /^[0-9a-f]{40}$/;
@@ -18115,6 +18129,20 @@ function deployProblem(value) {
18115
18129
  }
18116
18130
  function resultProblem(value) {
18117
18131
  const input = value;
18132
+ if (input["project"] !== undefined) {
18133
+ const others = RESULT_NOT_PROJECT_FIELDS.filter((field) => input[field] !== undefined);
18134
+ if (others.length > 0) {
18135
+ return `${RESULT_PROJECT_RULE} This call also carries ${others.join(", ")}.`;
18136
+ }
18137
+ const missing = RESULT_PROJECT_REQUIRED.filter((field) => input[field] === undefined);
18138
+ if (missing.length > 0) {
18139
+ return `a CI job's result needs ${missing.join(", ")}. ${RESULT_PROJECT_RULE}`;
18140
+ }
18141
+ return;
18142
+ }
18143
+ if (input["verdict"] === "could_not_run") {
18144
+ return "verdict could_not_run goes with project alone: a role's result of a check of a Verification document is pass or fail.";
18145
+ }
18118
18146
  const carried = RESULT_RECORD_FIELDS.filter((field) => input[field] !== undefined);
18119
18147
  if (typeof input.retract === "string") {
18120
18148
  const reason = input.reason;
@@ -18135,6 +18163,25 @@ function resultProblem(value) {
18135
18163
  }
18136
18164
  return;
18137
18165
  }
18166
+ var RESULTS_OWNER_RULE = "Exactly one of issue and project is required. With issue, the read prints the checks of the " + "issue's Verification document. With project, it prints the results that CI jobs stored for " + "checks of the spec files at commit.";
18167
+ function resultsProblem(value) {
18168
+ const input = value;
18169
+ if (input["issue"] === undefined === (input["project"] === undefined)) {
18170
+ return RESULTS_OWNER_RULE;
18171
+ }
18172
+ if (input["project"] !== undefined) {
18173
+ const issueOnly = ["at", "brief"].filter((field) => input[field] !== undefined);
18174
+ if (issueOnly.length > 0) {
18175
+ return `With project, the read takes commit, check and json alone, and this call also carries ${issueOnly.join(", ")}.`;
18176
+ }
18177
+ if (input["commit"] === undefined) {
18178
+ return "With project, the read needs commit, the 40-character lowercase hex commit whose results it prints.";
18179
+ }
18180
+ return;
18181
+ }
18182
+ const projectOnly = ["commit", "check", "json"].filter((field) => input[field] !== undefined);
18183
+ return projectOnly.length === 0 ? undefined : `With issue, the read takes at and brief alone, and this call also carries ${projectOnly.join(", ")}.`;
18184
+ }
18138
18185
  var SEARCH_QUERY_MAX = 1000;
18139
18186
  var SEARCH_QUERY_HINT = "search with a short phrase of a few words, not a passage";
18140
18187
  var SEARCH_KIND_DEPTH = 100;
@@ -18590,12 +18637,13 @@ var dispatchToolSpecs = [
18590
18637
  verdict: "pass",
18591
18638
  commit: "1111111111111111111111111111111111111111"
18592
18639
  },
18593
- description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch, no private host and no issue key: Dispatch keeps only words " + "of letters, digits and plain punctuation, and of those leaves out every word that holds " + "`://`, a private or Dispatch host, or an issue key of one of its projects; the record keeps " + "the whole reading. --dry-run prints the line the record would print, and records nothing. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. If " + "GitHub does not say that it does, Dispatch reads the external links of the check's issue: " + "a link to a GitHub pull request (https://github.com/<owner>/<repo>/pull/<n>) that is open " + "or merged, in a repository that Dispatch's GitHub App is installed on and can read, adds " + "the repository of that pull request. One record reads at most 10 linked pull requests. A " + "commit that none of these repositories holds is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and each owner/repo that Dispatch asked. It also names, with its reason " + "(owner/repo#n (repository_unreadable)), each linked pull request that Dispatch could not " + "read, at most 10 and a count of the rest, and every linked pull request in whose " + "repository it could not read the commit, since each of those spent one of the record's 10 " + "reads, and says to grant Dispatch's GitHub App that repository or to link a readable pull " + "request. It says how many linked pull requests it left unread past that bound. Record the " + "result after the commit is pushed. A linked repository that the App is not installed on " + "or cannot read does " + "not count. Where a read of " + "a linked pull request or of a linked repository does not answer, and no repository is shown " + "to hold the commit, the record is 502 GITHUB_UNREADABLE and nothing is recorded: record the " + "result again, after the wait the refusal names for a rate limit. Where the issue has no " + "repository, the result is recorded as before. Where Dispatch cannot read the repository " + "of the check's issue, the result is recorded as before only when every linked read " + "answers and no linked repository holds the commit: a linked read that does not answer " + "is 502 GITHUB_UNREADABLE and nothing is recorded. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED. " + "A check a document version rewords while the result is being written is 409 " + "CHECK_CONTENDED, with nothing recorded: run the same command again. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + ISSUE_REFERENCE,
18640
+ description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch, no private host and no issue key: Dispatch keeps only words " + "of letters, digits and plain punctuation, and of those leaves out every word that holds " + "`://`, a private or Dispatch host, or an issue key of one of its projects; the record keeps " + "the whole reading. --dry-run prints the line the record would print, and records nothing. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. If " + "GitHub does not say that it does, Dispatch reads the external links of the check's issue: " + "a link to a GitHub pull request (https://github.com/<owner>/<repo>/pull/<n>) that is open " + "or merged, in a repository that Dispatch's GitHub App is installed on and can read, adds " + "the repository of that pull request. One record reads at most 10 linked pull requests. A " + "commit that none of these repositories holds is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and each owner/repo that Dispatch asked. It also names, with its reason " + "(owner/repo#n (repository_unreadable)), each linked pull request that Dispatch could not " + "read, at most 10 and a count of the rest, and every linked pull request in whose " + "repository it could not read the commit, since each of those spent one of the record's 10 " + "reads, and says to grant Dispatch's GitHub App that repository or to link a readable pull " + "request. It says how many linked pull requests it left unread past that bound. Record the " + "result after the commit is pushed. A linked repository that the App is not installed on " + "or cannot read does " + "not count. Where a read of " + "a linked pull request or of a linked repository does not answer, and no repository is shown " + "to hold the commit, the record is 502 GITHUB_UNREADABLE and nothing is recorded: record the " + "result again, after the wait the refusal names for a rate limit. Where the issue has no " + "repository, the result is recorded as before. Where Dispatch cannot read the repository " + "of the check's issue, the result is recorded as before only when every linked read " + "answers and no linked repository holds the commit: a linked read that does not answer " + "is 502 GITHUB_UNREADABLE and nothing is recorded. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED. " + "A check a document version rewords while the result is being written is 409 " + "CHECK_CONTENDED, with nothing recorded: run the same command again. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + "With project, a CI job records its own result of one check of the spec files " + "(.dispatch/spec) at the commit it tested. The job runs the command under agent-secrets " + "result-grant, which gives it the secrets broker's proxy placeholder of its run as " + "DISPATCH_RESULTS_TOKEN; the command presents that placeholder alone and trades nothing, " + "and the airlock proxy puts the run's results token in its place. Dispatch refuses this form " + "from every other credential. The call sends commit, check, verdict and " + "observed. Dispatch takes the job, the procedure and the recorder from the token, from " + "GitHub and from the spec files at the commit. The recorder is the run, and no person. " + "Spec files that the graph logic refuses hold no check: 409 SPEC_FILES_REFUSED names the " + `first problem. A result keeps ${SPEC_CHECK_OBSERVED_MAX} characters of observed. The ` + "command sends a longer text as its start and its end, with a line between them that says " + "the middle was cut, and it sends a NUL as U+FFFD. verdict could_not_run is a test that did " + "not finish. The command prints the stored result as JSON, an in-toto statement of the " + "run. A write that reached Dispatch with no answer that says whether it stored the result " + 'prints {"write_outcome_unknown":"<code>"} and exits 1: the result may be stored, and a ' + "second run is safe, because Dispatch keeps each result. A tunnel the airlock proxy refuses " + "prints AIRLOCK_TUNNEL_REFUSED with its status, and an answer the proxy gives itself before " + "the write left it (Cipher-Proxy-Forwarded: false) prints its code and its words; each " + "says nothing reached Dispatch and exits 1, and a 5xx of either is asked again. An answer the " + "proxy gives itself after the write may have left it (Cipher-Proxy-Forwarded: unknown) is " + "asked again under the same key and, if no answer settles it, prints " + `{"write_outcome_unknown":"<code>"} and exits 1. A call that Dispatch's check of the ` + "run's token (429 " + "BROKER_TOKEN_RATE_LIMITED, 503 BROKER_UNAVAILABLE) turns away before anything " + "is stored is asked again after the answer's Retry-After, or a second. The whole call has " + "one bound, 60 s from its start, which every write runs under, and no round starts in its " + "last 7 s; a call turned away until then ends with the last answer, its code named, and " + "exits 1. It reads DISPATCH_URL and DISPATCH_RESULTS_TOKEN, and no broker variable. " + ISSUE_REFERENCE,
18594
18641
  arguments: (z) => ({
18595
18642
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
18596
- check: z.string().describe("The check block's id, or its canonical reference dispatch://KEY/artifact/verification-md#b-<id> when the id is not unique among the issue's Verification document and those of the issues above it.").optional(),
18643
+ project: z.string().describe("A project key such as ACME. With project, the call records a CI job's result of a check of the spec files.").optional(),
18644
+ check: z.string().describe("The check block's id, or its canonical reference dispatch://KEY/artifact/verification-md#b-<id> when the id is not unique among the issue's Verification document and those of the issues above it. With project, the check's id as the spec files hold it.").optional(),
18597
18645
  role: z.string({ max: 32 }).describe("Who ran it: implementer, tester, reviewer. At most 32 characters of a-z and -, printed in the pull-request line.").optional(),
18598
- verdict: z.enum(["pass", "fail"]).describe("Whether the check passed.").optional(),
18646
+ verdict: z.enum(["pass", "fail", "could_not_run"]).describe("Whether the check passed. could_not_run goes with project alone: the test did not finish.").optional(),
18599
18647
  commit: z.string().describe("The 40-character lowercase hex commit the check ran at.").optional(),
18600
18648
  surface: z.string().describe("Where a person reaches the change.").optional(),
18601
18649
  run: z.string().describe("The command that proved it.").optional(),
@@ -18653,13 +18701,21 @@ var dispatchToolSpecs = [
18653
18701
  {
18654
18702
  name: "dispatch_results",
18655
18703
  example: { issue: "DSP-1" },
18656
- description: "Print each check of an issue's Verification document with every result recorded against " + "it, newest first. " + "Each check prints what Dispatch compared its results with. A before_merge check is " + "compared with every open pull request head, or the final head of the last to merge when " + "none is open. An after_merge result counts only at a commit that holds the work's merge " + "on the compared branch. A default_branch check names the default branch alone. " + "With no known merge, an after_merge check compares with nothing and says so. " + "A read that failed is not known, never a pass or a fail. The newest branch result decides " + "and names its id and commit. A pass and fail at that commit are not known until retraction. " + "Production and graph checks count only results recorded for the current deploy of the " + "program they read. The output names that deploy and says why an excluded result counts " + "for nothing. The check's words must be unchanged and the result unretracted. " + "The check's own words print once, under the check. Each result then prints its verdict, " + "its role, its whole 40-character commit, where that commit stands, whether the check's " + "words moved after it was recorded, the time, its id, and the reading the role recorded. " + "A result nobody gave a reading says so. A retracted result prints as retracted, with " + "the reason and the caller that retracted it. A check with no result says so. " + `${CHECK_PROVED_BY_CI}: ` + "no role records its result. Dispatch reads GitHub at every open head, or the final head " + "of the last pull request to merge when none is open. Its result prints as `- <id> (before_merge): <verdict> at " + "<commit> by ci (CI run <name>, <conclusion>), <where that commit stands>. <the check's " + "words>`, then the `A pass stands:` line a recorded check prints, then `Pull request line:` " + "and the line to write into the pull-request body unchanged, then the reading: the " + "conclusion, the run's output title and summary, and its URL. A run that proves nothing " + "prints `- <id> (before_merge): no result:`, the sentence that names why, and the check's " + "words, then the `A pass stands:` line, then `Pull request line:` and `- Check <id> " + "(before_merge): CI run <name> has no result (<case>)`. That is a run that has not " + "concluded, one that concluded neutral, skipped or cancelled, one absent at the head, an " + "issue with no pull request head, or GitHub not read, with what GitHub answered. " + "A pull-request line writes `CI run <name>` only when it keeps every word of the name, " + "and `the CI run the check names` in its place where it drops one: a word the line drops, " + "such as an issue key or a word holding `_`. " + "A push that moves a pull request's head leaves a result at the commit before it, with " + "no write of anyone's: record the check again at the new head. A check CI proves is read " + "again at the new head by itself. " + ISSUE_REFERENCE,
18704
+ description: "Print each check of an issue's Verification document with every result recorded against " + "it, newest first. " + "Each check prints what Dispatch compared its results with. A before_merge check is " + "compared with every open pull request head, or the final head of the last to merge when " + "none is open. An after_merge result counts only at a commit that holds the work's merge " + "on the compared branch. A default_branch check names the default branch alone. " + "With no known merge, an after_merge check compares with nothing and says so. " + "A read that failed is not known, never a pass or a fail. The newest branch result decides " + "and names its id and commit. A pass and fail at that commit are not known until retraction. " + "Production and graph checks count only results recorded for the current deploy of the " + "program they read. The output names that deploy and says why an excluded result counts " + "for nothing. The check's words must be unchanged and the result unretracted. " + "The check's own words print once, under the check. Each result then prints its verdict, " + "its role, its whole 40-character commit, where that commit stands, whether the check's " + "words moved after it was recorded, the time, its id, and the reading the role recorded. " + "A result nobody gave a reading says so. A retracted result prints as retracted, with " + "the reason and the caller that retracted it. A check with no result says so. " + `${CHECK_PROVED_BY_CI}: ` + "no role records its result. Dispatch reads GitHub at every open head, or the final head " + "of the last pull request to merge when none is open. Its result prints as `- <id> (before_merge): <verdict> at " + "<commit> by ci (CI run <name>, <conclusion>), <where that commit stands>. <the check's " + "words>`, then the `A pass stands:` line a recorded check prints, then `Pull request line:` " + "and the line to write into the pull-request body unchanged, then the reading: the " + "conclusion, the run's output title and summary, and its URL. A run that proves nothing " + "prints `- <id> (before_merge): no result:`, the sentence that names why, and the check's " + "words, then the `A pass stands:` line, then `Pull request line:` and `- Check <id> " + "(before_merge): CI run <name> has no result (<case>)`. That is a run that has not " + "concluded, one that concluded neutral, skipped or cancelled, one absent at the head, an " + "issue with no pull request head, or GitHub not read, with what GitHub answered. " + "A pull-request line writes `CI run <name>` only when it keeps every word of the name, " + "and `the CI run the check names` in its place where it drops one: a word the line drops, " + "such as an issue key or a word holding `_`. " + "A push that moves a pull request's head leaves a result at the commit before it, with " + "no write of anyone's: record the check again at the new head. A check CI proves is read " + "again at the new head by itself. " + "With project and commit, the read prints each result that CI jobs stored for checks of " + "the project's spec files at that commit, newest first in Dispatch's record order, one " + "line each: its record number, the check, the verdict, the job, the leg of the matrix, " + "the run and its attempt, and the commit. check limits the read to one check, and json " + "prints the stored results as JSON. " + ISSUE_REFERENCE,
18657
18705
  arguments: (z) => ({
18658
- issue: z.string().describe(ISSUE_REFERENCE),
18706
+ issue: z.string().describe(ISSUE_REFERENCE).optional(),
18707
+ project: z.string().describe("A project key such as ACME. With commit, the read prints the results that CI jobs stored for checks of the project's spec files.").optional(),
18708
+ commit: z.string().describe("With project: the 40-character lowercase hex commit whose results the read prints.").optional(),
18709
+ check: z.string().describe("With project: the id of one check of the spec files, whose results alone the read prints.").optional(),
18659
18710
  at: z.string().describe("One commit of 40 lowercase hex characters. It becomes the only thing every check is compared with. Dispatch reads GitHub for none of it, except the check runs of a check CI proves, which it reads at each open pull request head, or with none open the final head of the newest merged one, as on every read, so that check's result stands at this commit only where it is the head it was read at.").optional(),
18660
18711
  brief: z.boolean().describe("Cut each reading whose result stands at none of the compared commits to its first 200 characters. Every other reading prints whole.").optional(),
18661
- json: z.boolean().describe("Print the complete results wire answer as JSON.").optional()
18662
- })
18712
+ json: z.boolean().describe("Print the complete results wire answer as JSON; with project, the stored results, one in-toto statement each.").optional()
18713
+ }),
18714
+ validation: {
18715
+ check: (value) => resultsProblem(value) === undefined,
18716
+ message: RESULTS_OWNER_RULE,
18717
+ refusal: (value) => resultsProblem(value) ?? RESULTS_OWNER_RULE
18718
+ }
18663
18719
  },
18664
18720
  {
18665
18721
  name: "dispatch_artifact",
@@ -23372,6 +23428,18 @@ function natsFailureReason(error) {
23372
23428
  return errorClass(error);
23373
23429
  }
23374
23430
 
23431
+ // ../envoy-client/src/go-space.ts
23432
+ var GO_SPACE = goSpaceClass();
23433
+ function goSpaceClass() {
23434
+ const set = /^\^\[(.+)\]\*\$$/u.exec(goBlankPattern.source)?.[1];
23435
+ if (set === undefined) {
23436
+ throw new Error(`goBlankPattern (@legion/contracts/go-blank) is no longer one character class: ${goBlankPattern.source}`);
23437
+ }
23438
+ return set;
23439
+ }
23440
+ var goSpaceAtEnds = new RegExp(`^[${GO_SPACE}]+|[${GO_SPACE}]+$`, "gu");
23441
+ var pathNamesNothingPattern = new RegExp(`^[${GO_SPACE}]*[./]*[${GO_SPACE}]*$`, "u");
23442
+
23375
23443
  // ../envoy-client/src/dispatch-command.ts
23376
23444
  var COMMANDS_OUTSIDE_THE_SPECS = [
23377
23445
  { name: PROXY_COMMAND, sentence: PROXY_SENTENCE, help: proxyHelp },
@@ -23831,6 +23899,28 @@ function parseCommand(argv, io) {
23831
23899
  }
23832
23900
  }
23833
23901
  }
23902
+ for (const { field, noun, tools, path } of IDENTIFIER_FIELDS) {
23903
+ const given = args[field];
23904
+ if (tools !== undefined && !tools.includes(tool))
23905
+ continue;
23906
+ const flag = setBy.get(field);
23907
+ for (const value of Array.isArray(given) ? given : [given]) {
23908
+ if (typeof value !== "string")
23909
+ continue;
23910
+ let problem;
23911
+ if (value === "") {
23912
+ problem = `${flag} is empty, so the call names no ${noun}: a variable that gives it may be empty or unset`;
23913
+ } else if (goBlankPattern.test(value)) {
23914
+ problem = `${flag} is only white space, so the call names no ${noun}`;
23915
+ } else if (path === true && pathNamesNothingPattern.test(value)) {
23916
+ problem = `${flag} is "${value.replace(goSpaceAtEnds, "")}", only dots and slashes, so the call names no ${noun}`;
23917
+ }
23918
+ if (problem === undefined)
23919
+ continue;
23920
+ problems.push(problem);
23921
+ break;
23922
+ }
23923
+ }
23834
23924
  if (help)
23835
23925
  return { kind: "help", tool };
23836
23926
  if (problems.length > 0) {
@@ -23855,6 +23945,18 @@ function appendedItem(kind, flag, value, number) {
23855
23945
  return parsed === undefined ? undefined : { value: parsed };
23856
23946
  }
23857
23947
  var ISSUE_KEY2 = /^[A-Z][A-Z0-9]*-\d+$/;
23948
+ var IDENTIFIER_FIELDS = [
23949
+ { field: "issue", noun: "issue", path: true },
23950
+ { field: "project", noun: "project", path: true },
23951
+ { field: "artifact", noun: "document", path: true },
23952
+ { field: "check", noun: "check" },
23953
+ { field: "commit", noun: "commit" },
23954
+ { field: "at", noun: "commit" },
23955
+ { field: "retract", noun: "result", path: true },
23956
+ { field: "comment", noun: "comment", path: true },
23957
+ { field: "session", noun: "session", path: true },
23958
+ { field: "parent", noun: "parent", tools: ["dispatch_issues", "dispatch_issue"] }
23959
+ ];
23858
23960
  function quoteWord(value) {
23859
23961
  return BARE_WORD.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
23860
23962
  }
@@ -26564,6 +26666,275 @@ async function fileBearer(bearer, url, section, env, commands = "run") {
26564
26666
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
26565
26667
  }
26566
26668
 
26669
+ // ../envoy-client/src/dispatch-write-rows.ts
26670
+ var components = looseObject({
26671
+ mode: string2(),
26672
+ ids: array(string2()).nullish(),
26673
+ reason: string2().nullish()
26674
+ });
26675
+ var advice = looseObject({
26676
+ decision_blocks: number2().int().optional(),
26677
+ issue_status: string2().optional(),
26678
+ legion_managed_status: boolean2().optional(),
26679
+ session_writes_since_human: number2().int().optional(),
26680
+ your_open_asks: array(looseObject({ id: string2(), question: string2() })).nullable().optional(),
26681
+ unparsed_openers: looseObject({ count: number2().int(), examples: array(string2()).nullable() }).optional(),
26682
+ moved_approval_request: looseObject({
26683
+ ask_id: string2(),
26684
+ issue: string2().optional(),
26685
+ project: string2().optional(),
26686
+ documents: array(looseObject({
26687
+ artifact_id: string2(),
26688
+ name: string2(),
26689
+ primary: boolean2(),
26690
+ role: string2().optional(),
26691
+ requested_version: number2().int(),
26692
+ version: number2().int()
26693
+ })).nullable()
26694
+ }).optional(),
26695
+ superseded_approval: looseObject({
26696
+ version: number2().int(),
26697
+ approved_version: number2().int(),
26698
+ approved_by: string2(),
26699
+ design_gates: array(looseObject({ issue: string2(), step: string2() })).optional()
26700
+ }).optional()
26701
+ }).optional();
26702
+ var caughtAdvice = unknown().optional();
26703
+ var ask = {
26704
+ id: askFields.id,
26705
+ issue_key: askFields.issue_key,
26706
+ artifact_id: askFields.artifact_id
26707
+ };
26708
+ var askWrite = looseObject({
26709
+ ...ask,
26710
+ question: askFields.question,
26711
+ urgency: string2(),
26712
+ waiting_on_person: string2().optional(),
26713
+ advice: caughtAdvice
26714
+ });
26715
+ var documentComment = {
26716
+ id: commentFields.id,
26717
+ ask_waiting_on: string2().optional(),
26718
+ advice
26719
+ };
26720
+ var suggestion = looseObject({ id: commentFields.id });
26721
+ var {
26722
+ repo: repo2,
26723
+ branch,
26724
+ last_error,
26725
+ last_commit,
26726
+ last_sync_at,
26727
+ components: sourceComponents
26728
+ } = ArchitectureSourceSchema.unwrap().shape;
26729
+ var architectureSource = looseObject({
26730
+ repo: repo2,
26731
+ branch,
26732
+ last_error,
26733
+ last_commit,
26734
+ last_sync_at,
26735
+ components: sourceComponents
26736
+ });
26737
+ var pictureUpload = {
26738
+ artifact: looseObject({ slug: artifactFields.slug }),
26739
+ version: looseObject({ number: versionFields.number })
26740
+ };
26741
+ var uploadedDocument = {
26742
+ id: artifactFields.id,
26743
+ slug: artifactFields.slug,
26744
+ name: artifactFields.name,
26745
+ primary: artifactFields.primary.optional(),
26746
+ role: string2().optional(),
26747
+ issue_key: artifactFields.issue_key.optional()
26748
+ };
26749
+ var actor = InboundActorSchema;
26750
+ var STORE_NOTHING = new WeakSet;
26751
+ function storesNothing(row) {
26752
+ STORE_NOTHING.add(row);
26753
+ return row;
26754
+ }
26755
+ function rowStores(row) {
26756
+ return !STORE_NOTHING.has(row);
26757
+ }
26758
+ var advance = looseObject(issueFields.advances.unwrap().unwrap().element.unwrap().shape);
26759
+ var externalLink = looseObject(ExternalLinkSchema.unwrap().shape);
26760
+ var updatedIssue = looseObject({
26761
+ key: issueFields.key,
26762
+ status: issueFields.status,
26763
+ title: issueFields.title.optional(),
26764
+ priority: issueFields.priority.optional(),
26765
+ assignee: issueFields.assignee.optional(),
26766
+ route: issueFields.route.optional(),
26767
+ parent: issueFields.parent.optional(),
26768
+ components: components.optional(),
26769
+ repo: issueFields.repo.optional(),
26770
+ resolved_repo: issueFields.resolved_repo.optional(),
26771
+ labels: issueFields.labels.nullish(),
26772
+ blocked_by: issueFields.blocked_by.nullish(),
26773
+ advances: array(advance).nullable().optional(),
26774
+ external_links: array(externalLink).nullish(),
26775
+ advice
26776
+ });
26777
+ var WRITE_ROWS = {
26778
+ issue: looseObject({
26779
+ key: issueFields.key,
26780
+ title: issueFields.title,
26781
+ project: issueFields.project,
26782
+ assignee: issueFields.assignee.optional(),
26783
+ repo: issueFields.repo.optional(),
26784
+ advice: caughtAdvice
26785
+ }),
26786
+ markdownRoundTrip: storesNothing(looseObject({ markdown: string2() })),
26787
+ fileRoundTrip: storesNothing(looseObject({ markdown: string2() })),
26788
+ related: storesNothing(looseObject({ outcome: string2() })),
26789
+ updateIssue: updatedIssue,
26790
+ updateIssueComponents: updatedIssue.extend({ components }),
26791
+ claimIssue: looseObject({
26792
+ status: issueFields.status,
26793
+ claim: looseObject({ at: string2() }).nullable(),
26794
+ legion_managed_status: boolean2().optional()
26795
+ }),
26796
+ changeIssueStatus: looseObject({
26797
+ changed: array(looseObject({
26798
+ key: issueFields.key,
26799
+ status: issueFields.status,
26800
+ parent: string2().nullable()
26801
+ })).nullable(),
26802
+ issue: looseObject({
26803
+ status: issueFields.status,
26804
+ external_links: array(externalLink).nullish()
26805
+ })
26806
+ }),
26807
+ ask: askWrite,
26808
+ artifactAsk: askWrite,
26809
+ editAsk: looseObject({ ...ask, question: askFields.question }),
26810
+ resolveAsk: looseObject({
26811
+ ...ask,
26812
+ resolution: looseObject({ reason: string2() }).optional()
26813
+ }),
26814
+ createProject: looseObject({
26815
+ key: string2(),
26816
+ name: string2(),
26817
+ created_at: string2(),
26818
+ default_assignee: string2().optional()
26819
+ }),
26820
+ syncArchitectureSources: array(architectureSource),
26821
+ syncArchitectureSource: architectureSource,
26822
+ requestApproval: looseObject({
26823
+ version: number2().int(),
26824
+ coverage: array(string2()).nullish(),
26825
+ coverage_unread: boolean2().optional(),
26826
+ ask: looseObject({
26827
+ ...ask,
26828
+ question: askFields.question,
26829
+ waiting_on_person: string2().optional()
26830
+ }).nullable(),
26831
+ approval: looseObject({ by: looseObject({ id: string2() }).nullish() })
26832
+ }),
26833
+ planApprove: looseObject({ version: number2().int() }),
26834
+ recordDeploy: looseObject({
26835
+ deploy: looseObject({
26836
+ program: string2(),
26837
+ commit: string2(),
26838
+ deployed_at: string2(),
26839
+ source: string2(),
26840
+ url: string2(),
26841
+ recorded_by: actor
26842
+ })
26843
+ }),
26844
+ reviewArtifact: looseObject({
26845
+ version: number2().int(),
26846
+ state: string2(),
26847
+ ask_id: string2().nullable(),
26848
+ reason: string2().nullable(),
26849
+ actor
26850
+ }),
26851
+ recordResult: looseObject({
26852
+ line: string2(),
26853
+ result: looseObject({
26854
+ id: string2(),
26855
+ verdict: string2(),
26856
+ role: string2(),
26857
+ check_block_id: string2(),
26858
+ check_issue_key: string2(),
26859
+ commit_sha: string2()
26860
+ })
26861
+ }),
26862
+ dryRunResult: storesNothing(looseObject({ line: string2(), result: unknown() })),
26863
+ retractResult: looseObject({
26864
+ result_id: string2(),
26865
+ reason: string2(),
26866
+ created_at: string2(),
26867
+ actor
26868
+ }),
26869
+ recordSpecCheckResult: looseObject({
26870
+ id: string2(),
26871
+ seq: number2().int(),
26872
+ attestation: looseObject({
26873
+ predicate: looseObject({ check: string2(), verdict: string2() })
26874
+ })
26875
+ }),
26876
+ comment: looseObject({ ...documentComment, issue_key: commentFields.issue_key }),
26877
+ artifactComment: looseObject(documentComment),
26878
+ suggest: suggestion,
26879
+ artifactSuggest: suggestion,
26880
+ resolveComment: looseObject({
26881
+ id: commentFields.id,
26882
+ issue_key: commentFields.issue_key,
26883
+ artifact_id: commentFields.artifact_id
26884
+ }),
26885
+ editComment: looseObject({
26886
+ id: commentFields.id,
26887
+ issue_key: commentFields.issue_key,
26888
+ artifact_id: commentFields.artifact_id
26889
+ }),
26890
+ message: looseObject({ id: messageFields.id, advice }),
26891
+ editMessage: looseObject({ id: messageFields.id, issue_key: messageFields.issue_key }),
26892
+ agentMessage: looseObject({
26893
+ id: messageFields.id,
26894
+ deliveries: array(looseObject({ state: string2(), error: string2().nullish(), delivery: string2() })).nullish()
26895
+ }),
26896
+ messageReply: looseObject({
26897
+ id: messageFields.id,
26898
+ body: messageFields.body,
26899
+ in_reply_to: messageFields.in_reply_to.optional(),
26900
+ duplicate: boolean2().optional()
26901
+ }),
26902
+ deliveryReply: looseObject({}),
26903
+ acceptMessageDelivery: looseObject({
26904
+ message_id: string2(),
26905
+ body: string2(),
26906
+ delivery: string2()
26907
+ }),
26908
+ docEdit: looseObject({
26909
+ applied: number2().int(),
26910
+ version: looseObject({ number: versionFields.number }).nullable(),
26911
+ changed: boolean2().optional(),
26912
+ unchanged_ops: array(number2().int()).nullish(),
26913
+ lost_ops: array(number2().int()).nullish(),
26914
+ written: string2().optional(),
26915
+ token: string2().optional(),
26916
+ advice: caughtAdvice
26917
+ }),
26918
+ nameArtifactVersion: looseObject({}),
26919
+ writeHandoff: looseObject({
26920
+ id: string2(),
26921
+ issue_key: string2(),
26922
+ phase: string2(),
26923
+ version: number2().int()
26924
+ }),
26925
+ projectArtifact: looseObject({
26926
+ artifact: looseObject({ ...uploadedDocument, project: artifactFields.project }),
26927
+ version: pictureUpload.version,
26928
+ advice
26929
+ }),
26930
+ agentArtifact: looseObject(pictureUpload),
26931
+ artifact: looseObject({
26932
+ artifact: looseObject(uploadedDocument),
26933
+ version: pictureUpload.version,
26934
+ advice
26935
+ })
26936
+ };
26937
+
26567
26938
  // ../envoy-client/src/excerpt.ts
26568
26939
  var REDACTED = "[redacted]";
26569
26940
  var EXCERPT_SCAN_LIMIT = 64 * 1024;
@@ -26660,6 +27031,7 @@ class SentTokens {
26660
27031
  var landed = (action) => ({ state: "may-have-landed", action });
26661
27032
  var nothing = (action) => ({ state: "nothing-sent", action });
26662
27033
  var WRITE_TRANSITIONS = {
27034
+ "uncommitted-401": { "nothing-sent": landed("end"), "may-have-landed": landed("end") },
26663
27035
  applied: { "nothing-sent": nothing("settle"), "may-have-landed": landed("settle") },
26664
27036
  judged: { "nothing-sent": nothing("settle"), "may-have-landed": landed("settle") },
26665
27037
  unjudged: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
@@ -26700,6 +27072,7 @@ var DISPATCH_URL_SETTING = "the configured Dispatch URL";
26700
27072
  class DispatchServiceError extends Error {
26701
27073
  code;
26702
27074
  status;
27075
+ retryAfterMs;
26703
27076
  name = "DispatchServiceError";
26704
27077
  fromDispatch = true;
26705
27078
  candidates;
@@ -26709,10 +27082,11 @@ class DispatchServiceError extends Error {
26709
27082
  changed;
26710
27083
  textRefusal;
26711
27084
  hint;
26712
- constructor(code, status, message, details = {}) {
27085
+ constructor(code, status, message, details = {}, retryAfterMs = null) {
26713
27086
  super(message);
26714
27087
  this.code = code;
26715
27088
  this.status = status;
27089
+ this.retryAfterMs = retryAfterMs;
26716
27090
  this.candidates = details.candidates;
26717
27091
  this.current = details.current;
26718
27092
  this.mismatches = details.mismatches;
@@ -26744,24 +27118,17 @@ class DispatchProxyRefusalError extends DispatchServiceError {
26744
27118
  fromDispatch = false;
26745
27119
  }
26746
27120
  var PROXY_CODE_FORM = /^[A-Z][A-Z0-9_]{0,63}$/;
26747
- function proxyTunnelAnswer(error) {
26748
- if (typeof error !== "object" || error === null)
27121
+ function proxyOwnAnswer(response) {
27122
+ const forwarded = response.headers.get(PROXY_FORWARDED_HEADER)?.trim().toLowerCase();
27123
+ const named = response.headers.get(PROXY_CODE_HEADER)?.trim() ?? "";
27124
+ if (forwarded !== "false" && forwarded !== "unknown" && named === "")
26749
27125
  return;
26750
- const { code, status, headers } = error;
26751
- if (code !== "ERR_PROXY_TUNNEL" || typeof status !== "number" || !(headers instanceof Headers)) {
26752
- return;
26753
- }
26754
- const proxyCode = headers.get(PROXY_CODE_HEADER) ?? "";
26755
- if (status < 400 || status > 599 || !PROXY_CODE_FORM.test(proxyCode))
26756
- return;
26757
- const forwarded = headers.get(PROXY_FORWARDED_HEADER);
26758
- return new Response(null, {
26759
- status,
26760
- headers: {
26761
- [PROXY_CODE_HEADER]: proxyCode,
26762
- ...forwarded === null ? {} : { [PROXY_FORWARDED_HEADER]: forwarded }
26763
- }
26764
- });
27126
+ return { code: named === "" ? `HTTP_${response.status}` : named, left: forwarded !== "false" };
27127
+ }
27128
+ function proxyEvent(status, left) {
27129
+ if (left)
27130
+ return "proxy-unsettled";
27131
+ return outage(status) ? "proxy-failed" : "proxy-refused";
26765
27132
  }
26766
27133
  var CREDENTIAL_ECHOED = "CREDENTIAL_ECHOED";
26767
27134
 
@@ -26782,6 +27149,8 @@ class DispatchWriteUnsettledError extends Error {
26782
27149
  let why = last instanceof DispatchServiceError && mayHaveReachedServer(last.status) || last instanceof DispatchProxyRefusalError ? "an attempt of the write may have reached Dispatch" : "an earlier attempt of the write may have reached Dispatch";
26783
27150
  if (last instanceof DispatchGatewayError) {
26784
27151
  answer = last.answer;
27152
+ if (last.status < 300)
27153
+ why = "the write may have reached Dispatch behind what answered it";
26785
27154
  } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
26786
27155
  answer = last.code;
26787
27156
  why = "Dispatch was still running an earlier attempt of the write";
@@ -26803,10 +27172,10 @@ class DispatchWriteLandedError extends Error {
26803
27172
  code;
26804
27173
  status;
26805
27174
  name = "DispatchWriteLandedError";
26806
- constructor(code, status, method, shownUrl) {
27175
+ constructor(code, status, method, shownUrl, options) {
26807
27176
  const lost = code === IDEMPOTENCY_ANSWER_NOT_KEPT ? "Dispatch gives no copy of its answer, which was too large to keep or holds a comment " + "or a message that was deleted, or a document version name a delete replaced" : "its answer was lost on the way back";
26808
27177
  const request = `${method} ${shownUrl}`;
26809
- super(`${request} was made, but ${lost} (${code}), so this command cannot print what it ` + "made: read it back with `dispatch read`, or with the matching list for something it created.");
27178
+ super(`${request} was made, but ${lost} (${code}), so this command cannot print what it ` + "made: read it back with `dispatch read`, or with the matching list for something it created.", options);
26810
27179
  this.code = code;
26811
27180
  this.status = status;
26812
27181
  }
@@ -26870,10 +27239,12 @@ class DispatchNoRouteError extends DispatchServiceError {
26870
27239
  class DispatchUnreachableError extends Error {
26871
27240
  reachedNothing;
26872
27241
  failure;
27242
+ code;
26873
27243
  constructor(message, reachedNothing, failure) {
26874
27244
  super(message);
26875
27245
  this.reachedNothing = reachedNothing;
26876
27246
  this.failure = failure;
27247
+ this.code = /^[A-Z][A-Z0-9_]*$/.test(failure) ? failure : undefined;
26877
27248
  }
26878
27249
  }
26879
27250
  function reviewNoRouteRefusal(baseUrl, route, version) {
@@ -26917,6 +27288,9 @@ function pauseFor(ms, signal) {
26917
27288
  signal.addEventListener("abort", stop, { once: true });
26918
27289
  return promise;
26919
27290
  }
27291
+ function keyEchoed(response, key) {
27292
+ return key !== "" && keyNamedBack(response) === key;
27293
+ }
26920
27294
  var STREAMED_BODY_MIN = 1 << 20;
26921
27295
  var STREAMED_BODY_CHUNK = 64 << 10;
26922
27296
  function attemptBody(body, headers, progress) {
@@ -26974,7 +27348,7 @@ function refusalIn(json) {
26974
27348
  };
26975
27349
  }
26976
27350
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
26977
- async function writeAnswer(response) {
27351
+ async function writeAnswer(response, echoed) {
26978
27352
  if (NULL_BODY_STATUSES.has(response.status)) {
26979
27353
  return {
26980
27354
  response,
@@ -26985,7 +27359,8 @@ async function writeAnswer(response) {
26985
27359
  code: undefined,
26986
27360
  error: undefined,
26987
27361
  replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
26988
- keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
27362
+ echoed,
27363
+ proxy: proxyOwnAnswer(response)
26989
27364
  };
26990
27365
  }
26991
27366
  const text = await response.text();
@@ -27001,25 +27376,23 @@ async function writeAnswer(response) {
27001
27376
  code: refusal?.code,
27002
27377
  error: refusal?.error,
27003
27378
  replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
27004
- keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
27379
+ echoed,
27380
+ proxy: proxyOwnAnswer(response)
27005
27381
  };
27006
27382
  }
27007
27383
  function isStoredKeyStatus(status) {
27008
27384
  return status >= 400 && status < 500 && status !== 401 && !outage(status);
27009
27385
  }
27010
- function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
27386
+ function answerEvent(answer, canTellDeadToken) {
27011
27387
  const { status } = answer.response;
27012
- if (proxied && answer.response.headers.get(PROXY_CODE_HEADER) !== null) {
27013
- if (answer.response.headers.get(PROXY_FORWARDED_HEADER) !== "false")
27014
- return "proxy-unsettled";
27015
- return outage(status) ? "proxy-failed" : "proxy-refused";
27016
- }
27388
+ if (answer.proxy !== undefined)
27389
+ return proxyEvent(status, answer.proxy.left);
27017
27390
  if (status >= 200 && status < 300) {
27018
27391
  if (answer.notJson)
27019
27392
  return "foreign-2xx";
27020
27393
  if (answer.malformed)
27021
27394
  return "body-malformed";
27022
- return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
27395
+ return answer.echoed ? "applied" : "foreign-2xx";
27023
27396
  }
27024
27397
  if (status >= 300 && status < 400)
27025
27398
  return "redirect";
@@ -27029,15 +27402,21 @@ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
27029
27402
  if (status === 404 && answer.code === "NOT_FOUND" && answer.error?.startsWith(NO_ROUTE_MESSAGE_PREFIX) === true) {
27030
27403
  return "no-route";
27031
27404
  }
27405
+ if (status === 401 && answer.echoed)
27406
+ return "uncommitted-401";
27407
+ if (tokenNotCheckedAnswer(status, answer.code))
27408
+ return "try-later";
27032
27409
  const textRefusal = answer.error !== undefined && answer.response.headers.has(TEXT_REFUSAL_HEADER);
27033
27410
  if (!textRefusal && retriesUnderKey(status, answer.code)) {
27034
27411
  if (status === 409)
27035
27412
  return "in-flight";
27036
27413
  return mayHaveReachedServer(status) ? "may-have-run" : "try-later";
27037
27414
  }
27415
+ if (!answer.echoed)
27416
+ return "unjudged";
27038
27417
  if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
27039
27418
  return "judged";
27040
- if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
27419
+ if (!isStoredKeyStatus(status))
27041
27420
  return "unjudged";
27042
27421
  if (answer.code === IDEMPOTENCY_KEY_REUSED)
27043
27422
  return "judged";
@@ -27104,6 +27483,103 @@ function gatewayAdvice(method, status) {
27104
27483
  function gatewayClears(status) {
27105
27484
  return outage(status) || status >= 200 && status < 300;
27106
27485
  }
27486
+ var DISPATCH_ANSWER_LOST = "ANSWER_LOST";
27487
+
27488
+ class DispatchAnswerMissingError extends Error {
27489
+ status;
27490
+ name = "DispatchAnswerMissingError";
27491
+ code = DISPATCH_ANSWER_LOST;
27492
+ constructor(status, method, url, options) {
27493
+ super(`${method} ${url} answered ${status} without the answer it asks for ` + `(${DISPATCH_ANSWER_LOST}); it stores nothing, so nothing was made, and asking again is safe.`, options);
27494
+ this.status = status;
27495
+ }
27496
+ }
27497
+
27498
+ class DispatchEmptyPathError extends Error {
27499
+ name = "DispatchEmptyPathError";
27500
+ constructor(path) {
27501
+ const route = path.map((segment) => segment === "" ? "{empty}" : pathNamesNothingPattern.test(segment) ? `{${JSON.stringify(segment)}}` : segment).join("/");
27502
+ super(`/${route} holds a value that names nothing where the call names what it is about (empty, only white space, or only dots and slashes, which name no step of a path), so nothing was sent: a variable that gives it may be empty or unset`);
27503
+ }
27504
+ }
27505
+ var PROXY_TUNNEL_REFUSED = /: (\d{3}) ?(.*)$/;
27506
+
27507
+ class AirlockTunnelRefusedError extends Error {
27508
+ status;
27509
+ reason;
27510
+ proxyCode;
27511
+ name = "AirlockTunnelRefusedError";
27512
+ code = "AIRLOCK_TUNNEL_REFUSED";
27513
+ constructor(status, reason, proxyCode, options) {
27514
+ const said = status === 0 ? reason : `${status}${reason === "" ? "" : ` ${reason}`}`;
27515
+ super(`the airlock proxy refused the connection (${said}); nothing was sent to Dispatch`, options);
27516
+ this.status = status;
27517
+ this.reason = reason;
27518
+ this.proxyCode = proxyCode;
27519
+ }
27520
+ }
27521
+ function tunnelRefusal(error) {
27522
+ if (!(error instanceof Error) || Reflect.get(error, "code") !== "ERR_PROXY_TUNNEL") {
27523
+ return;
27524
+ }
27525
+ const headers = Reflect.get(error, "headers");
27526
+ const named = headers instanceof Headers ? headers.get(PROXY_CODE_HEADER)?.trim() ?? "" : "";
27527
+ const proxyCode = PROXY_CODE_FORM.test(named) ? named : undefined;
27528
+ const said = PROXY_TUNNEL_REFUSED.exec(error.message);
27529
+ return said === null ? new AirlockTunnelRefusedError(0, error.message, proxyCode, { cause: error }) : new AirlockTunnelRefusedError(Number(said[1]), said[2]?.trim() ?? "", proxyCode, {
27530
+ cause: error
27531
+ });
27532
+ }
27533
+
27534
+ class AirlockRefusedError extends Error {
27535
+ status;
27536
+ code;
27537
+ body;
27538
+ name = "AirlockRefusedError";
27539
+ constructor(status, code, body) {
27540
+ super(`the airlock proxy answered ${status} ${code} itself, and sent nothing on: ${body}`);
27541
+ this.status = status;
27542
+ this.code = code;
27543
+ this.body = body;
27544
+ }
27545
+ }
27546
+
27547
+ class AirlockOutcomeUnknownError extends Error {
27548
+ status;
27549
+ code;
27550
+ body;
27551
+ name = "AirlockOutcomeUnknownError";
27552
+ constructor(status, code, body) {
27553
+ super(`the airlock proxy answered ${status} ${code} itself after the write may have reached Dispatch: ${body}`);
27554
+ this.status = status;
27555
+ this.code = code;
27556
+ this.body = body;
27557
+ }
27558
+ }
27559
+ var TOKEN_NOT_CHECKED = {
27560
+ BROKER_TOKEN_RATE_LIMITED: 429,
27561
+ BROKER_UNAVAILABLE: 503
27562
+ };
27563
+ function tokenNotCheckedAnswer(status, code) {
27564
+ return code !== undefined && TOKEN_NOT_CHECKED[code] === status;
27565
+ }
27566
+ function tokenNotChecked(error) {
27567
+ return error instanceof DispatchServiceError && error.fromDispatch && tokenNotCheckedAnswer(error.status, error.code);
27568
+ }
27569
+ function writeOutcomeUnknown(error) {
27570
+ if (error instanceof DispatchWriteUnsettledError)
27571
+ return true;
27572
+ if (error instanceof DispatchGatewayError)
27573
+ return error.mayHaveReachedDispatch;
27574
+ if (error instanceof DispatchProxyRefusalError)
27575
+ return false;
27576
+ if (error instanceof DispatchServiceError)
27577
+ return error.status >= 500 && !tokenNotChecked(error);
27578
+ return false;
27579
+ }
27580
+ function keyNamedBack(response) {
27581
+ return (response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "").replace(/^"(.*)"$/, "$1");
27582
+ }
27107
27583
 
27108
27584
  class DispatchClient {
27109
27585
  fetchImpl;
@@ -27127,6 +27603,9 @@ class DispatchClient {
27127
27603
  try {
27128
27604
  return await fetchImpl(input, { ...init, redirect: "manual" });
27129
27605
  } catch (error) {
27606
+ const tunnel = tunnelRefusal(error);
27607
+ if (tunnel !== undefined)
27608
+ throw tunnel;
27130
27609
  if (error instanceof TypeError) {
27131
27610
  throw new DispatchUnreachableError(`Dispatch at ${shown} is unreachable: ${errorClass(error)}. If the Dispatch URL changed, restart this agent process so it picks up the new configuration.`, reachedNothing(error), errorClass(error));
27132
27611
  }
@@ -27145,7 +27624,7 @@ class DispatchClient {
27145
27624
  return this.#credential.secret();
27146
27625
  }
27147
27626
  async issue(input) {
27148
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "issues"], input);
27627
+ const answer = await this.#writeAnswer("POST", ["api", "v1", "issues"], WRITE_ROWS.issue, input);
27149
27628
  return { ...answer.payload, created: answer.status === 201 };
27150
27629
  }
27151
27630
  async resolveIssue(issueReference) {
@@ -27173,28 +27652,28 @@ class DispatchClient {
27173
27652
  async listIssueArtifacts(issue) {
27174
27653
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"]);
27175
27654
  }
27176
- async markdownRoundTrip(markdown, newDocument) {
27177
- return this.#roundTrip(["api", "v1", "markdown", "round-trip"], { markdown }, newDocument);
27655
+ async markdownRoundTrip(markdown, newDocument = false) {
27656
+ return this.#roundTrip(["api", "v1", "markdown", "round-trip"], WRITE_ROWS.markdownRoundTrip, { markdown }, newDocument);
27178
27657
  }
27179
- async fileRoundTrip(bytes, newDocument) {
27658
+ async fileRoundTrip(bytes, newDocument = false) {
27180
27659
  const file = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
27181
- return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], { file }, newDocument);
27660
+ return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], WRITE_ROWS.fileRoundTrip, { file }, newDocument);
27182
27661
  }
27183
- async#roundTrip(path, body, newDocument) {
27184
- const answer = await this.#writingNothing(path, newDocument ? { ...body, new_document: true } : body, { writes: false });
27662
+ async#roundTrip(path, row, body, newDocument) {
27663
+ const answer = await this.#writingNothing(path, row, newDocument ? { ...body, new_document: true } : body);
27185
27664
  return answer.markdown;
27186
27665
  }
27187
27666
  async listProjectArtifacts(project, unlinked = false) {
27188
27667
  return this.#json("GET", ["api", "v1", "projects", project, "artifacts"], undefined, unlinked ? { unlinked: "true" } : undefined);
27189
27668
  }
27190
27669
  async projectArtifact(project, input, key) {
27191
- return this.#upload(["api", "v1", "projects", project, "artifacts"], input, key);
27670
+ return this.#upload(["api", "v1", "projects", project, "artifacts"], input, WRITE_ROWS.projectArtifact, key);
27192
27671
  }
27193
27672
  async getProjectArtifact(project, slug) {
27194
27673
  return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug]);
27195
27674
  }
27196
27675
  async agentArtifact(sessionId, input) {
27197
- return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input);
27676
+ return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input, WRITE_ROWS.agentArtifact);
27198
27677
  }
27199
27678
  async getAgentArtifact(sessionId, slug) {
27200
27679
  return this.#json("GET", ["api", "v1", "agents", sessionId, "artifacts", slug]);
@@ -27215,24 +27694,24 @@ class DispatchClient {
27215
27694
  return this.#json("GET", path, undefined, request);
27216
27695
  }
27217
27696
  async related(project, input) {
27218
- return this.#writingNothing(["api", "v1", "projects", project, "related"], input);
27697
+ return this.#writingNothing(["api", "v1", "projects", project, "related"], WRITE_ROWS.related, input);
27219
27698
  }
27220
27699
  async getIssue(issue) {
27221
27700
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue)]);
27222
27701
  }
27223
27702
  async updateIssue(issue, input) {
27224
- return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
27703
+ return this.#write("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input.components === undefined ? WRITE_ROWS.updateIssue : WRITE_ROWS.updateIssueComponents, input);
27225
27704
  }
27226
27705
  async changeIssueStatus(issue, input) {
27227
27706
  const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "status-change"];
27228
27707
  try {
27229
- return await this.#json("POST", path, input);
27708
+ return await this.#write("POST", path, WRITE_ROWS.changeIssueStatus, input);
27230
27709
  } catch (error) {
27231
27710
  throw this.#refusalOfNoRoute(error, path, (route) => statusChangeNoRouteRefusal(this.#baseUrl, route));
27232
27711
  }
27233
27712
  }
27234
27713
  async claimIssue(issue, input = {}) {
27235
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
27714
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], WRITE_ROWS.claimIssue, input);
27236
27715
  }
27237
27716
  async releaseIssueClaim(issue, input = {}) {
27238
27717
  return this.#json("DELETE", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
@@ -27262,7 +27741,7 @@ class DispatchClient {
27262
27741
  return { issue, events };
27263
27742
  }
27264
27743
  async ask(issue, input) {
27265
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], input);
27744
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], WRITE_ROWS.ask, input);
27266
27745
  }
27267
27746
  async openAsks(sessionID, since) {
27268
27747
  return this.#json("GET", ["api", "v1", "asks", "open"], undefined, {
@@ -27307,7 +27786,7 @@ class DispatchClient {
27307
27786
  return this.#json("GET", ["api", "v1", "credential-requests"], undefined, { approver: "me" });
27308
27787
  }
27309
27788
  async createProject(input) {
27310
- return this.#json("POST", ["api", "v1", "projects"], input);
27789
+ return this.#write("POST", ["api", "v1", "projects"], WRITE_ROWS.createProject, input);
27311
27790
  }
27312
27791
  async listProjects() {
27313
27792
  return this.#json("GET", ["api", "v1", "projects"]);
@@ -27343,26 +27822,12 @@ class DispatchClient {
27343
27822
  }
27344
27823
  async syncArchitectureSources(project) {
27345
27824
  try {
27346
- return await this.#json("POST", [
27347
- "api",
27348
- "v1",
27349
- "projects",
27350
- project,
27351
- "architecture-sources",
27352
- "sync"
27353
- ]);
27825
+ return await this.#write("POST", ["api", "v1", "projects", project, "architecture-sources", "sync"], WRITE_ROWS.syncArchitectureSources);
27354
27826
  } catch (error) {
27355
27827
  if (!(error instanceof DispatchNoRouteError))
27356
27828
  throw error;
27357
27829
  }
27358
- const source = await this.#json("POST", [
27359
- "api",
27360
- "v1",
27361
- "projects",
27362
- project,
27363
- "architecture-source",
27364
- "sync"
27365
- ]);
27830
+ const source = await this.#write("POST", ["api", "v1", "projects", project, "architecture-source", "sync"], WRITE_ROWS.syncArchitectureSource);
27366
27831
  return [source];
27367
27832
  }
27368
27833
  async syncArchitectureSource(project, repo) {
@@ -27370,37 +27835,25 @@ class DispatchClient {
27370
27835
  if (!owner || !name || rest.length > 0) {
27371
27836
  throw new Error(`repository must be owner/name, got ${JSON.stringify(repo)}`);
27372
27837
  }
27373
- return this.#json("POST", [
27374
- "api",
27375
- "v1",
27376
- "projects",
27377
- project,
27378
- "architecture-sources",
27379
- owner,
27380
- name,
27381
- "sync"
27382
- ]);
27838
+ return this.#write("POST", ["api", "v1", "projects", project, "architecture-sources", owner, name, "sync"], WRITE_ROWS.syncArchitectureSource);
27383
27839
  }
27384
27840
  async resolveAsk(id, input) {
27385
- return this.#json("POST", ["api", "v1", "asks", id, "resolve"], input);
27841
+ return this.#write("POST", ["api", "v1", "asks", id, "resolve"], WRITE_ROWS.resolveAsk, input);
27386
27842
  }
27387
27843
  async requestApproval(artifactID, input) {
27388
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], input);
27844
+ const answer = await this.#writeAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], WRITE_ROWS.requestApproval, input);
27389
27845
  return { ...answer.payload, recorded: answer.status === 201 };
27390
27846
  }
27391
27847
  async planApprove(artifactID, input) {
27392
- return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
27848
+ return this.#write("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], WRITE_ROWS.planApprove, input);
27393
27849
  }
27394
27850
  async reviewArtifact(artifactID, version, input) {
27395
27851
  const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
27396
27852
  const body = { state: input.state, reason: input.reason };
27397
27853
  try {
27398
27854
  const route = await this.#credential.approveRoute?.(this.#credentialSignal(this.#signal));
27399
- if (route !== undefined) {
27400
- const via = this.#throughProxy(route, this.#url(path));
27401
- return (await this.#jsonAnswer("POST", path, body, { via })).payload;
27402
- }
27403
- return await this.#json("POST", path, body);
27855
+ const via = route === undefined ? undefined : this.#throughProxy(route, this.#url(path));
27856
+ return await this.#write("POST", path, WRITE_ROWS.reviewArtifact, body, { via });
27404
27857
  } catch (error) {
27405
27858
  throw this.#refusalOfNoRoute(error, path, (route) => reviewNoRouteRefusal(this.#baseUrl, route, version));
27406
27859
  }
@@ -27421,12 +27874,12 @@ class DispatchClient {
27421
27874
  return { credential, init: { proxy: proxy.toString(), tls: { ca: route.caCertificate } } };
27422
27875
  }
27423
27876
  async recordResult(issue, input) {
27424
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
27877
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], WRITE_ROWS.recordResult, input);
27425
27878
  }
27426
27879
  async dryRunResult(issue, input) {
27427
27880
  const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "results", "dry-run"];
27428
27881
  try {
27429
- return await this.#writingNothing(path, input, { writes: false });
27882
+ return await this.#writingNothing(path, WRITE_ROWS.dryRunResult, input);
27430
27883
  } catch (error) {
27431
27884
  throw this.#refusalOfNoRoute(error, path, (route) => resultDryRunNoRouteRefusal(this.#baseUrl, route));
27432
27885
  }
@@ -27435,19 +27888,19 @@ class DispatchClient {
27435
27888
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], undefined, at === undefined ? undefined : { at });
27436
27889
  }
27437
27890
  async recordDeploy(input) {
27438
- return this.#json("POST", ["api", "v1", "deploys"], input);
27891
+ return this.#write("POST", ["api", "v1", "deploys"], WRITE_ROWS.recordDeploy, input);
27439
27892
  }
27440
27893
  async deploys(repo) {
27441
27894
  return this.#json("GET", ["api", "v1", "deploys"], undefined, { repo });
27442
27895
  }
27443
27896
  async retractResult(resultID, input) {
27444
- return this.#json("POST", ["api", "v1", "results", resultID, "retract"], input);
27897
+ return this.#write("POST", ["api", "v1", "results", resultID, "retract"], WRITE_ROWS.retractResult, input);
27445
27898
  }
27446
27899
  async editAsk(id, input) {
27447
- return this.#json("PATCH", ["api", "v1", "asks", id], input);
27900
+ return this.#write("PATCH", ["api", "v1", "asks", id], WRITE_ROWS.editAsk, input);
27448
27901
  }
27449
27902
  async comment(issue, input) {
27450
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], input);
27903
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], WRITE_ROWS.comment, input);
27451
27904
  }
27452
27905
  async listIssueAsks(issue, state) {
27453
27906
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], undefined, state === undefined ? undefined : { state });
@@ -27456,11 +27909,11 @@ class DispatchClient {
27456
27909
  return this.#json("GET", ["api", "v1", "artifacts", id, "asks"], undefined, state === undefined ? undefined : { state });
27457
27910
  }
27458
27911
  async artifactAsk(id, input) {
27459
- return this.#json("POST", ["api", "v1", "artifacts", id, "asks"], input);
27912
+ return this.#write("POST", ["api", "v1", "artifacts", id, "asks"], WRITE_ROWS.artifactAsk, input);
27460
27913
  }
27461
27914
  async suggest(issue, input) {
27462
27915
  const { replace_with, ...comment } = input;
27463
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], {
27916
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], WRITE_ROWS.suggest, {
27464
27917
  ...comment,
27465
27918
  suggestion: { replace_with }
27466
27919
  });
@@ -27469,27 +27922,27 @@ class DispatchClient {
27469
27922
  return this.#json("GET", ["api", "v1", "artifacts", id, "comments"]);
27470
27923
  }
27471
27924
  async artifactComment(id, input) {
27472
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], input);
27925
+ return this.#write("POST", ["api", "v1", "artifacts", id, "comments"], WRITE_ROWS.artifactComment, input);
27473
27926
  }
27474
27927
  async artifactSuggest(id, input) {
27475
27928
  const { replace_with, ...comment } = input;
27476
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], {
27929
+ return this.#write("POST", ["api", "v1", "artifacts", id, "comments"], WRITE_ROWS.artifactSuggest, {
27477
27930
  ...comment,
27478
27931
  suggestion: { replace_with }
27479
27932
  });
27480
27933
  }
27481
27934
  async message(issue, input) {
27482
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
27935
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], WRITE_ROWS.message, input);
27483
27936
  }
27484
27937
  async agentMessage(sessionId, input) {
27485
- return this.#json("POST", ["api", "v1", "agents", sessionId, "messages"], input);
27938
+ return this.#write("POST", ["api", "v1", "agents", sessionId, "messages"], WRITE_ROWS.agentMessage, input);
27486
27939
  }
27487
27940
  async messageReply(id, input, options = {}) {
27488
- return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
27941
+ return this.#write("POST", ["api", "v1", "messages", id, "reply"], WRITE_ROWS.messageReply, input, { query: options.followUp === true ? { follow_up: "true" } : undefined });
27489
27942
  }
27490
27943
  async deliveryReply(resource, id, input, options = {}) {
27491
27944
  const collection = resource === "message" ? "messages" : "comments";
27492
- await this.#json("POST", ["api", "v1", collection, id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
27945
+ await this.#write("POST", ["api", "v1", collection, id, "reply"], WRITE_ROWS.deliveryReply, input, { query: options.followUp === true ? { follow_up: "true" } : undefined });
27493
27946
  }
27494
27947
  async getMessage(issue, id) {
27495
27948
  return this.#json("GET", [
@@ -27505,7 +27958,7 @@ class DispatchClient {
27505
27958
  return this.#json("GET", ["api", "v1", "messages", id], undefined, session === undefined ? undefined : { session });
27506
27959
  }
27507
27960
  async editMessage(id, input) {
27508
- return this.#json("PATCH", ["api", "v1", "messages", id], input);
27961
+ return this.#write("PATCH", ["api", "v1", "messages", id], WRITE_ROWS.editMessage, input);
27509
27962
  }
27510
27963
  async deleteMessage(id, actor) {
27511
27964
  return this.#json("DELETE", ["api", "v1", "messages", id], { actor });
@@ -27517,10 +27970,10 @@ class DispatchClient {
27517
27970
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"]);
27518
27971
  }
27519
27972
  async acceptMessageDelivery(id, attempt, input) {
27520
- return this.#json("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], input);
27973
+ return this.#write("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], WRITE_ROWS.acceptMessageDelivery, input);
27521
27974
  }
27522
27975
  async artifact(issue, input) {
27523
- return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input);
27976
+ return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input, WRITE_ROWS.artifact);
27524
27977
  }
27525
27978
  async getArtifact(id) {
27526
27979
  return this.#json("GET", ["api", "v1", "artifacts", id]);
@@ -27562,10 +28015,12 @@ class DispatchClient {
27562
28015
  return this.#json("GET", ["api", "v1", "messages", id, "blocks"], undefined, session === undefined ? undefined : { session });
27563
28016
  }
27564
28017
  async docEdit(id, input, key) {
27565
- return this.#json("POST", ["api", "v1", "artifacts", id, "edits"], input, undefined, undefined, key);
28018
+ return this.#write("POST", ["api", "v1", "artifacts", id, "edits"], WRITE_ROWS.docEdit, input, {
28019
+ key
28020
+ });
27566
28021
  }
27567
28022
  async nameArtifactVersion(id, input) {
27568
- return this.#json("POST", ["api", "v1", "artifacts", id, "versions"], input);
28023
+ return this.#write("POST", ["api", "v1", "artifacts", id, "versions"], WRITE_ROWS.nameArtifactVersion, input);
27569
28024
  }
27570
28025
  async getArtifactEvents(id, after = 0, limit = 200) {
27571
28026
  return this.#json("GET", ["api", "v1", "artifacts", id, "events"], undefined, { after, limit });
@@ -27586,10 +28041,12 @@ class DispatchClient {
27586
28041
  return this.#json("GET", ["api", "v1", "comments", id]);
27587
28042
  }
27588
28043
  async resolveComment(id, actor) {
27589
- return this.#json("POST", ["api", "v1", "comments", id, "resolve"], { actor });
28044
+ return this.#write("POST", ["api", "v1", "comments", id, "resolve"], WRITE_ROWS.resolveComment, {
28045
+ actor
28046
+ });
27590
28047
  }
27591
28048
  async editComment(id, input) {
27592
- return this.#json("PATCH", ["api", "v1", "comments", id], input);
28049
+ return this.#write("PATCH", ["api", "v1", "comments", id], WRITE_ROWS.editComment, input);
27593
28050
  }
27594
28051
  async deleteComment(id, actor) {
27595
28052
  return this.#json("DELETE", ["api", "v1", "comments", id], { actor });
@@ -27601,7 +28058,7 @@ class DispatchClient {
27601
28058
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"]);
27602
28059
  }
27603
28060
  async writeHandoff(issue, phase, input) {
27604
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs", phase], input);
28061
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs", phase], WRITE_ROWS.writeHandoff, input);
27605
28062
  }
27606
28063
  async listHandoffs(issue) {
27607
28064
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs"]);
@@ -27636,6 +28093,60 @@ class DispatchClient {
27636
28093
  ...query.since === undefined ? {} : { since: query.since }
27637
28094
  });
27638
28095
  }
28096
+ #writePayload(method, url, answer, write) {
28097
+ const stores = rowStores(write.row);
28098
+ if (!answer.response.ok) {
28099
+ if (!stores && answer.echoed && answer.code === IDEMPOTENCY_KEY_COMMITTED)
28100
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
28101
+ return this.#payloadOf(method, url, answer);
28102
+ }
28103
+ if (NULL_BODY_STATUSES.has(answer.response.status) && !stores)
28104
+ return this.#payloadOf(method, url, answer);
28105
+ const value = answer.json?.value;
28106
+ const replayed = answer.response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1";
28107
+ if (answerNotKept(answer.response.status, replayed, value)) {
28108
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text, undefined, IDEMPOTENCY_ANSWER_NOT_KEPT);
28109
+ }
28110
+ const parsed = write.row.safeParse(value);
28111
+ if (!parsed.success)
28112
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text, parsed.error);
28113
+ return value;
28114
+ }
28115
+ #missingWriteAnswer(method, url, response, write, text, cause, code = DISPATCH_ANSWER_LOST) {
28116
+ const shown = requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING);
28117
+ if (!rowStores(write.row))
28118
+ return code === IDEMPOTENCY_ANSWER_NOT_KEPT && keyEchoed(response, write.key) ? new DispatchAnswerNotKeptError(response.status, method, shown) : new DispatchAnswerMissingError(response.status, method, shown, { cause });
28119
+ if (keyEchoed(response, write.key))
28120
+ return new DispatchWriteLandedError(code, response.status, method, shown, { cause });
28121
+ const names = keyNamedBack(response) === "" ? "naming no key back" : "naming another request's key back";
28122
+ return new DispatchWriteUnsettledError(this.#gatewayError(method, url, response, text, "the write's answer", {
28123
+ advice: "the write may have reached Dispatch behind what answered it",
28124
+ also: `${names}, `
28125
+ }), write.progress.sent, write.key);
28126
+ }
28127
+ async#writeAnswer(method, path, row, body, options = {}) {
28128
+ const url = this.#url(path, options.query);
28129
+ const write = this.#writeCall(method, url, row, options.key);
28130
+ const answer = await this.#sendWrite(method, url, body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" }, "application/json", undefined, write, options.via);
28131
+ return {
28132
+ status: answer.response.status,
28133
+ payload: this.#writePayload(method, url, answer, write)
28134
+ };
28135
+ }
28136
+ async#write(method, path, row, body, options = {}) {
28137
+ return (await this.#writeAnswer(method, path, row, body, options)).payload;
28138
+ }
28139
+ async specCheckResults(project, commit, check) {
28140
+ return this.#json("GET", ["api", "v1", "projects", project, "results"], undefined, {
28141
+ commit,
28142
+ check
28143
+ });
28144
+ }
28145
+ async recordSpecCheckResult(project, input) {
28146
+ const { commit, check, verdict, observed } = input;
28147
+ const body = { commit, check, verdict, observed };
28148
+ return this.#write("POST", ["api", "v1", "projects", project, "results"], WRITE_ROWS.recordSpecCheckResult, body);
28149
+ }
27639
28150
  async#resolveIssue(issueReference) {
27640
28151
  if (!issueReference.includes("#"))
27641
28152
  return issueReference;
@@ -27653,21 +28164,12 @@ class DispatchClient {
27653
28164
  throw error;
27654
28165
  }
27655
28166
  }
27656
- async#json(method, path, body, query, signal, key) {
27657
- return (await this.#jsonAnswer(method, path, body, { query, signal, key })).payload;
27658
- }
27659
- async#jsonAnswer(method, path, body, options = {}) {
27660
- const { query, signal, key, writes = true, via } = options;
28167
+ async#json(method, path, body, query, signal) {
27661
28168
  const url = this.#url(path, query);
27662
28169
  const encoded = body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" };
27663
- const write = this.#writeCall(method, url, key, writes);
27664
- if (write !== undefined) {
27665
- const answer = await this.#write(method, url, encoded, "application/json", signal, write, via);
27666
- return { status: answer.response.status, payload: this.#payloadOf(method, url, answer) };
27667
- }
27668
28170
  return this.#noRoute(async () => {
27669
28171
  const { answer: response } = await this.#send(method, url, encoded, undefined, signal);
27670
- return { status: response.status, payload: await this.#response(method, url, response) };
28172
+ return this.#response(method, url, response);
27671
28173
  }, signal);
27672
28174
  }
27673
28175
  async#noRoute(attempt, signal) {
@@ -27684,19 +28186,17 @@ class DispatchClient {
27684
28186
  return error;
27685
28187
  return refuse(`POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`);
27686
28188
  }
27687
- #writeCall(method, url, key, writes = true) {
27688
- if (method !== "POST" && method !== "PATCH")
27689
- return;
28189
+ #writeCall(method, url, row, key) {
27690
28190
  return {
27691
28191
  key: key ?? crypto.randomUUID(),
27692
28192
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
27693
- writes,
27694
- progress: { sent: 0, running: false, keyEchoed: false }
28193
+ row,
28194
+ progress: { sent: 0, running: false }
27695
28195
  };
27696
28196
  }
27697
- async#upload(path, input, key) {
28197
+ async#upload(path, input, row, key) {
27698
28198
  if (input.file === undefined) {
27699
- return this.#json("POST", path, input, undefined, undefined, key);
28199
+ return this.#write("POST", path, row, input, { key });
27700
28200
  }
27701
28201
  const form = new FormData;
27702
28202
  form.set("name", input.name);
@@ -27707,31 +28207,24 @@ class DispatchClient {
27707
28207
  if (input.actor !== undefined)
27708
28208
  form.set("actor", JSON.stringify(input.actor));
27709
28209
  form.set("file", input.file, input.name);
27710
- return this.#form("POST", path, form, key);
28210
+ return this.#form(path, form, row, key);
27711
28211
  }
27712
- async#form(method, path, form, callerKey) {
28212
+ async#form(path, form, row, key) {
27713
28213
  const url = this.#url(path);
27714
28214
  const encoded = new Response(form);
27715
28215
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
27716
28216
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
27717
- const write = this.#writeCall(method, url, callerKey);
27718
- if (write !== undefined) {
27719
- const answer = await this.#write(method, url, body, "application/json", undefined, write);
27720
- return this.#payloadOf(method, url, answer);
27721
- }
27722
- return this.#noRoute(async () => this.#response(method, url, (await this.#send(method, url, body)).answer));
28217
+ const write = this.#writeCall("POST", url, row, key);
28218
+ const answer = await this.#sendWrite("POST", url, body, "application/json", undefined, write);
28219
+ return this.#writePayload("POST", url, answer, write);
27723
28220
  }
27724
- async#writingNothing(path, body, options = {}) {
28221
+ async#writingNothing(path, row, body) {
27725
28222
  for (let keys = 1;; keys++) {
27726
28223
  try {
27727
- return (await this.#jsonAnswer("POST", path, body, options)).payload;
28224
+ return await this.#write("POST", path, row, body);
27728
28225
  } catch (error) {
27729
- if (!(error instanceof DispatchWriteLandedError) || error.code !== IDEMPOTENCY_ANSWER_NOT_KEPT) {
28226
+ if (!(error instanceof DispatchAnswerNotKeptError) || keys === 2)
27730
28227
  throw error;
27731
- }
27732
- if (keys === 2) {
27733
- throw new DispatchAnswerNotKeptError(error.status, "POST", requestForText(this.#baseUrl, this.#url(path), DISPATCH_URL_SETTING));
27734
- }
27735
28228
  }
27736
28229
  }
27737
28230
  }
@@ -27803,9 +28296,10 @@ class DispatchClient {
27803
28296
  });
27804
28297
  return { answer, presented };
27805
28298
  }
27806
- async#write(method, url, body, accept, signal, write, via) {
28299
+ async#sendWrite(method, url, body, accept, signal, write, via) {
27807
28300
  const limit = signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]);
27808
28301
  const { key, progress } = write;
28302
+ const stores = rowStores(write.row);
27809
28303
  const credential = via?.credential ?? this.#credential;
27810
28304
  const headers = { Accept: accept, [IDEMPOTENCY_KEY_HEADER]: key };
27811
28305
  if (body !== undefined)
@@ -27852,18 +28346,17 @@ class DispatchClient {
27852
28346
  response = await this.#attempt(url, method, { ...headers, ...presented }, body, silenceMs, limit, via?.init);
27853
28347
  } catch (error) {
27854
28348
  return {
27855
- event: stoppedEvent(limit, true, error) ?? (error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
28349
+ event: stoppedEvent(limit, true, error) ?? (error instanceof AirlockTunnelRefusedError ? proxyEvent(error.status, false) : error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
27856
28350
  failure: error,
27857
28351
  presented,
27858
28352
  sent
27859
28353
  };
27860
28354
  }
28355
+ const echoed = keyEchoed(response, key);
27861
28356
  const heard = { retryAfterMs: retryAfterMs(response.headers) };
27862
- if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
27863
- progress.keyEchoed = true;
27864
28357
  let answer;
27865
28358
  try {
27866
- answer = await writeAnswer(response);
28359
+ answer = await writeAnswer(response, echoed);
27867
28360
  } catch (error) {
27868
28361
  const stop = stoppedEvent(limit, true, error);
27869
28362
  return {
@@ -27875,7 +28368,7 @@ class DispatchClient {
27875
28368
  };
27876
28369
  }
27877
28370
  return {
27878
- event: answerEvent(answer, write.key, progress.keyEchoed, credential.stale !== undefined && !deadTokenTold, via !== undefined),
28371
+ event: answerEvent(answer, credential.stale !== undefined && !deadTokenTold),
27879
28372
  answer,
27880
28373
  presented,
27881
28374
  sent,
@@ -27893,13 +28386,14 @@ class DispatchClient {
27893
28386
  return result;
27894
28387
  };
27895
28388
  const waitStopped = (error) => ({
28389
+ ...state === "nothing-sent" && error instanceof Error && error.name === "TimeoutError" ? last : {},
27896
28390
  event: stoppedEvent(limit, false, error) ?? "cancelled",
27897
28391
  failure: error
27898
28392
  });
27899
28393
  let last = await next();
27900
28394
  let event = last.event;
27901
28395
  for (;; ) {
27902
- const step = writeStep(state, event, write.writes);
28396
+ const step = writeStep(state, event, stores);
27903
28397
  state = step.state;
27904
28398
  if ((event === "silence" || event === "in-flight") && !upload)
27905
28399
  progress.running = true;
@@ -27991,9 +28485,6 @@ class DispatchClient {
27991
28485
  } catch (error) {
27992
28486
  if (cut.signal.aborted && !limit.aborted)
27993
28487
  throw cut.signal.reason;
27994
- const refused = transport === undefined ? undefined : proxyTunnelAnswer(error);
27995
- if (refused !== undefined)
27996
- return refused;
27997
28488
  throw error;
27998
28489
  } finally {
27999
28490
  answered = true;
@@ -28002,15 +28493,22 @@ class DispatchClient {
28002
28493
  }
28003
28494
  async#endWrite(method, url, state, event, answer, failure, write, routeSpent, via) {
28004
28495
  const { request, progress } = write;
28496
+ if (answer?.response.status === 409 && answer.code === IDEMPOTENCY_KEY_COMMITTED && !answer.echoed) {
28497
+ return this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
28498
+ }
28005
28499
  let own = failure;
28006
- const proxyCode = via === undefined ? null : answer?.response.headers.get(PROXY_CODE_HEADER);
28007
- if (via !== undefined && answer !== undefined && typeof proxyCode === "string") {
28008
- own = this.#proxyRefusal(request, via, answer, proxyCode, state, event);
28500
+ if (answer?.proxy !== undefined) {
28501
+ own = via === undefined ? this.#airlockAnswer(answer, answer.proxy) : this.#proxyRefusal(request, via, answer.response.status, answer.proxy.code, answer.text, state, event);
28502
+ } else if (via !== undefined && failure instanceof AirlockTunnelRefusedError) {
28503
+ own = this.#proxyRefusal(request, via, failure.status, failure.proxyCode ?? failure.code, "", state, event);
28009
28504
  } else if (via !== undefined && failure instanceof DispatchUnreachableError) {
28010
28505
  own = this.#proxyUnreachable(via, failure, state);
28011
28506
  } else if (answer?.response.ok === true) {
28507
+ if (!answer.echoed || !rowStores(write.row)) {
28508
+ return this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
28509
+ }
28012
28510
  const { status } = answer.response;
28013
- own = new Error(answer.notJson ? `${request} answered ${status} with ${bodyForText(answer.text, this.#sent.with(this.token), "JSON")}, though every Dispatch write answers JSON, so something in Dispatch's place answered` : event === "foreign-2xx" ? `${request} answered ${status} without carrying back its ${IDEMPOTENCY_KEY_HEADER}, though an earlier answer of this write carried it and Dispatch answers every keyed write with it, so something in Dispatch's place answered` : `${request} answered ${status} with a body that is not the JSON its Content-Type says`);
28511
+ own = new Error(answer.notJson ? `${request} answered ${status} with ${bodyForText(answer.text, this.#sent.with(this.token), "JSON")}, though every Dispatch write answers JSON, so something in Dispatch's place answered` : `${request} answered ${status} with a body that is not the JSON its Content-Type says`);
28014
28512
  } else if (answer !== undefined) {
28015
28513
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
28016
28514
  }
@@ -28018,7 +28516,7 @@ class DispatchClient {
28018
28516
  return own;
28019
28517
  const last = own instanceof Error ? own : new Error(String(own));
28020
28518
  let unanswered;
28021
- if (answer === undefined) {
28519
+ if (answer === undefined || answer.proxy !== undefined) {
28022
28520
  switch (event) {
28023
28521
  case "silence":
28024
28522
  unanswered = `${request} ${last.message}`;
@@ -28048,14 +28546,21 @@ class DispatchClient {
28048
28546
  const again = state === "nothing-sent" ? " The review can be sent again once the broker answers." : "";
28049
28547
  return new DispatchUnreachableError(`Dispatch at ${urlForText(this.#baseUrl, DISPATCH_URL_SETTING)}, through Cipher's proxy at ${originOf(via.init.proxy)}, is unreachable: ${failure.failure}. The proxy is the secrets broker's.${again}`, failure.reachedNothing, failure.failure);
28050
28548
  }
28051
- #proxyRefusal(request, via, answer, code, state, event) {
28052
- const { status } = answer.response;
28053
- const said = excerpt(answer.text, this.#sent.with(this.token));
28549
+ #proxyRefusal(request, via, status, code, text, state, event) {
28550
+ const said = excerpt(text, this.#sent.with(this.token));
28054
28551
  const by = `${request} was answered ${status} ${code} by Cipher's proxy at ${originOf(via.init.proxy)}${said === "" ? "" : ` (${JSON.stringify(said)})`}`;
28055
28552
  const message = state !== "nothing-sent" ? event === "proxy-unsettled" ? `${by}, after this attempt may have reached Dispatch` : `${by} before this attempt left the proxy, after an earlier attempt of the review may have reached Dispatch` : event === "proxy-failed" ? `${by} before any of it left the proxy, so nothing reached Dispatch. The proxy is the secrets broker's, and a new \`dispatch review\` trades a new grant once the broker answers.` : `${by} before any of it left the proxy, so nothing reached Dispatch, and a new \`dispatch review\` trades a new grant.`;
28056
28553
  return new DispatchProxyRefusalError(code, status, message);
28057
28554
  }
28555
+ #airlockAnswer(answer, proxy) {
28556
+ const body = excerpt(answer.text, this.#sent.with(this.token));
28557
+ const { status } = answer.response;
28558
+ return proxy.left ? new AirlockOutcomeUnknownError(status, proxy.code, body) : new AirlockRefusedError(status, proxy.code, body);
28559
+ }
28058
28560
  #url(path, query) {
28561
+ if (path.some((segment) => pathNamesNothingPattern.test(segment))) {
28562
+ throw new DispatchEmptyPathError(path);
28563
+ }
28059
28564
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
28060
28565
  if (query) {
28061
28566
  for (const [name, value] of Object.entries(query)) {
@@ -28085,7 +28590,7 @@ class DispatchClient {
28085
28590
  throw new DispatchServiceError(refusal.code ?? `HTTP_${response.status}`, response.status, refusal.error, {
28086
28591
  ...refusal,
28087
28592
  textRefusal: response.headers.has(TEXT_REFUSAL_HEADER)
28088
- });
28593
+ }, retryAfterMs(response.headers) || null);
28089
28594
  }
28090
28595
  throw this.#gatewayError(method, url, response, text, "Dispatch's error JSON");
28091
28596
  }
@@ -28105,7 +28610,7 @@ class DispatchClient {
28105
28610
  return error;
28106
28611
  }
28107
28612
  }
28108
- #gatewayError(method, url, response, text, notWhat) {
28613
+ #gatewayError(method, url, response, text, notWhat, caller = {}) {
28109
28614
  const tokens = this.#sent.with(this.token);
28110
28615
  const body = bodyForText(text, tokens, notWhat);
28111
28616
  const reasonPhrase = excerpt(response.statusText, tokens);
@@ -28113,7 +28618,7 @@ class DispatchClient {
28113
28618
  const target = redirectOrigin(response, url, tokens);
28114
28619
  const redirected = target === undefined ? "" : ` (a redirect to ${target}, which this client does not follow)`;
28115
28620
  const request = `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`;
28116
- return new DispatchGatewayError(response.status, `${request} answered ${response.status}${reason}${redirected} with ${body}, ${GATEWAY_PAGE}`, gatewayAdvice(method, response.status));
28621
+ return new DispatchGatewayError(response.status, `${request} answered ${response.status}${reason}${redirected} with ${body}, ${caller.also ?? ""}${GATEWAY_PAGE}`, caller.advice ?? gatewayAdvice(method, response.status));
28117
28622
  }
28118
28623
  }
28119
28624
 
@@ -30954,6 +31459,40 @@ function notMadeLine(reason, context, searchQuery) {
30954
31459
  return `No related-item check was made: ${reason}. Search before you rely on this being new: dispatch search --project ${context.project}${query}`;
30955
31460
  }
30956
31461
 
31462
+ // ../envoy-client/src/runner-log.ts
31463
+ var ESCAPED = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/gu;
31464
+ var JSON_ESCAPED = /[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;
31465
+ var SHORT_ESCAPES = {
31466
+ "\x07": "\\a",
31467
+ "\b": "\\b",
31468
+ "\f": "\\f",
31469
+ "\n": "\\n",
31470
+ "\r": "\\r",
31471
+ "\t": "\\t",
31472
+ "\v": "\\v"
31473
+ };
31474
+ function hex3(value, digits) {
31475
+ return value.toString(16).padStart(digits, "0");
31476
+ }
31477
+ function goEscape(character) {
31478
+ const short = SHORT_ESCAPES[character];
31479
+ if (short !== undefined)
31480
+ return short;
31481
+ const point = character.codePointAt(0) ?? 0;
31482
+ if (point < 32 || point === 127)
31483
+ return `\\x${hex3(point, 2)}`;
31484
+ return point > 65535 ? `\\U${hex3(point, 8)}` : `\\u${hex3(point, 4)}`;
31485
+ }
31486
+ function printable(text) {
31487
+ return text.replace(ESCAPED, goEscape).replaceAll("##[", "##\\x5b");
31488
+ }
31489
+ function printableLine(text) {
31490
+ return printable(text).replace(/^(\s*):(?=:)/u, "$1\\x3a");
31491
+ }
31492
+ function printableJson(json) {
31493
+ return json.replace(JSON_ESCAPED, (character) => Array.from({ length: character.length }, (_, unit) => `\\u${hex3(character.charCodeAt(unit), 4)}`).join("")).replaceAll("##[", "##\\u005b");
31494
+ }
31495
+
30957
31496
  // ../envoy-client/src/dispatch-commands/advice.ts
30958
31497
  var triageAdviceShown = new Set;
30959
31498
  function adviceMemory() {
@@ -31064,6 +31603,31 @@ async function otherAdviceLines(render) {
31064
31603
  }
31065
31604
  }
31066
31605
 
31606
+ // ../envoy-client/src/dispatch-commands/observed-text.ts
31607
+ function lengthOfFirst(text, count) {
31608
+ let at = 0;
31609
+ for (let seen = 0;seen < count && at < text.length; seen += 1) {
31610
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
31611
+ }
31612
+ return at < text.length ? at : undefined;
31613
+ }
31614
+ function startOfLast(text, count) {
31615
+ let at = text.length;
31616
+ for (let seen = 0;seen < count && at > 0; seen += 1) {
31617
+ const low = text.charCodeAt(at - 1);
31618
+ const high = at > 1 ? text.charCodeAt(at - 2) : 0;
31619
+ at -= low >= 56320 && low <= 57343 && high >= 55296 && high <= 56319 ? 2 : 1;
31620
+ }
31621
+ return at;
31622
+ }
31623
+ function observedAsKept(observed) {
31624
+ const text = observed.replaceAll("\x00", "\uFFFD");
31625
+ if (lengthOfFirst(text, SPEC_CHECK_OBSERVED_MAX) === undefined)
31626
+ return text;
31627
+ const start = text.slice(0, lengthOfFirst(text, SPEC_CHECK_OBSERVED_START));
31628
+ return `${start}${SPEC_CHECK_OBSERVED_CUT_NOTE}${text.slice(startOfLast(text, SPEC_CHECK_OBSERVED_END))}`;
31629
+ }
31630
+
31067
31631
  // ../envoy-client/src/dispatch-commands/render-graph.ts
31068
31632
  function referenceLines(read) {
31069
31633
  if (typeof read === "string")
@@ -32339,11 +32903,54 @@ async function issuesCommand(context) {
32339
32903
  };
32340
32904
  }
32341
32905
  function dryRunAsksDispatch(tool, args) {
32342
- const { retract } = args;
32343
- return tool === "dispatch_result" && retract === undefined;
32906
+ const { retract, project } = args;
32907
+ return tool === "dispatch_result" && retract === undefined && project === undefined;
32908
+ }
32909
+ async function specCheckResultCommand(client, args) {
32910
+ const project = stringArg(args, "project");
32911
+ const observed = optionalString(args, "observed");
32912
+ const stored = await client.recordSpecCheckResult(project, {
32913
+ commit: stringArg(args, "commit"),
32914
+ check: stringArg(args, "check"),
32915
+ verdict: stringArg(args, "verdict"),
32916
+ ...observed === undefined ? {} : { observed: observedAsKept(observed) }
32917
+ });
32918
+ const { predicate } = stored.attestation;
32919
+ return {
32920
+ text: JSON.stringify(stored, null, 2),
32921
+ details: {
32922
+ project,
32923
+ result: stored.id,
32924
+ seq: stored.seq,
32925
+ check: predicate.check,
32926
+ verdict: predicate.verdict
32927
+ }
32928
+ };
32929
+ }
32930
+ function specCheckResultLine(result) {
32931
+ const { predicate, subject } = result.attestation;
32932
+ const leg = predicate.leg === "" ? "no leg" : `leg ${printable(predicate.leg)}`;
32933
+ const commit = subject?.[0]?.digest?.["gitCommit"] ?? "an unnamed commit";
32934
+ return `- #${result.seq} ${printable(predicate.check)}: ${printable(predicate.verdict)}. Job ${printable(predicate.job)}, ${leg}, run ${printable(predicate.run.run_id)} attempt ${predicate.run.attempt}, commit ${printable(commit)}.`;
32935
+ }
32936
+ async function specCheckResultsCommand(client, args) {
32937
+ const project = stringArg(args, "project");
32938
+ const commit = stringArg(args, "commit");
32939
+ const check = optionalString(args, "check");
32940
+ const results = (await client.specCheckResults(project, commit, check)).results ?? [];
32941
+ const what = check === undefined ? project : `check ${printable(check)} of ${project}`;
32942
+ const text = optionalBoolean(args, "json") === true ? printableJson(JSON.stringify(results, null, 2)) : results.length === 0 ? `No result of ${what} is stored at ${printable(commit)}.` : [
32943
+ `Results of ${what} at ${printable(commit)}, newest first:`,
32944
+ ...results.map(specCheckResultLine)
32945
+ ].join(`
32946
+ `);
32947
+ return { text, details: { project, commit, results: results.length } };
32344
32948
  }
32345
32949
  async function resultCommand(context) {
32346
32950
  const { args, client, actor } = context;
32951
+ if (optionalString(args, "project") !== undefined) {
32952
+ return await specCheckResultCommand(client, args);
32953
+ }
32347
32954
  const retract = optionalString(args, "retract");
32348
32955
  if (retract !== undefined) {
32349
32956
  const retraction = await client.retractResult(retract, {
@@ -32415,6 +33022,9 @@ ${recorded.line}`,
32415
33022
  }
32416
33023
  async function resultsCommand(context) {
32417
33024
  const { args, client } = context;
33025
+ if (optionalString(args, "project") !== undefined) {
33026
+ return await specCheckResultsCommand(client, args);
33027
+ }
32418
33028
  const issue = stringArg(args, "issue");
32419
33029
  const at = optionalString(args, "at");
32420
33030
  const brief = optionalBoolean(args, "brief") === true;
@@ -32853,6 +33463,7 @@ var WRITE_ROUTES = [
32853
33463
  { method: "POST", pattern: "/api/v1/issues/{key}/results", commands: ["result"] },
32854
33464
  { method: "POST", pattern: "/api/v1/issues/{key}/results/dry-run", commands: ["result"] },
32855
33465
  { method: "POST", pattern: "/api/v1/results/{id}/retract", commands: ["result"] },
33466
+ { method: "POST", pattern: "/api/v1/projects/{key}/results", commands: ["result"] },
32856
33467
  { method: "POST", pattern: "/api/v1/deploys", commands: ["deploy"] },
32857
33468
  { method: "POST", pattern: "/api/v1/issues/{key}/handoffs/{phase}", commands: ["handoff-write"] },
32858
33469
  { method: "POST", pattern: "/api/v1/issues/{key}/artifacts", commands: ["artifact"] },
@@ -34379,7 +34990,7 @@ async function askRoundTrip(client, route, ask) {
34379
34990
  }
34380
34991
  return {
34381
34992
  kind: "unanswered",
34382
- failure: error instanceof DispatchAnswerNotKeptError ? `${route} wrote nothing, and Dispatch kept no copy of its answer (${error.code})` : `${route} failed with ${messageFor(error)}`,
34993
+ failure: error instanceof DispatchAnswerNotKeptError ? `${route} wrote nothing, and Dispatch kept no copy of its answer (${error.code})` : error instanceof DispatchAnswerMissingError ? `${route} answered without the text it would store (${error.code})` : `${route} failed with ${messageFor(error).replace(/\.$/, "")}`,
34383
34994
  error,
34384
34995
  routeAbsent
34385
34996
  };
@@ -36594,7 +37205,7 @@ function deviceLoginBroker(brokerUrl) {
36594
37205
  function loginDpopKey(key) {
36595
37206
  return dpopKeyOf(key, "this machine's device login key");
36596
37207
  }
36597
- function printable(value, what, endpoint) {
37208
+ function printable2(value, what, endpoint) {
36598
37209
  if (UNPRINTABLE.test(value)) {
36599
37210
  throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered a ${what} holding a control or format character, which this machine does not print`);
36600
37211
  }
@@ -36604,7 +37215,7 @@ function page(uri, endpoint) {
36604
37215
  if (!isHttpUrl(uri)) {
36605
37216
  throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered a page to type the code in that is no http or https URL`);
36606
37217
  }
36607
- return printable(uri, "page to type the code in", endpoint);
37218
+ return printable2(uri, "page to type the code in", endpoint);
36608
37219
  }
36609
37220
  async function withDeviceLoginLock(path, work, options = {}) {
36610
37221
  await deviceLoginDirectory(path);
@@ -36636,7 +37247,7 @@ function loginOf(key, broker, answered, now) {
36636
37247
  const accessExpiresAt = new Date(now + accessSeconds * 1000);
36637
37248
  return {
36638
37249
  key,
36639
- credentialId: printable(credentialId, "credential_id", endpoint),
37250
+ credentialId: printable2(credentialId, "credential_id", endpoint),
36640
37251
  refreshToken: holdSecret(refreshToken, expiresAt),
36641
37252
  expiresAt,
36642
37253
  broker,
@@ -36686,7 +37297,7 @@ async function startDeviceLogin(options) {
36686
37297
  return {
36687
37298
  brokerUrl,
36688
37299
  person,
36689
- userCode: printable(answered.user_code, "user code", endpoint),
37300
+ userCode: printable2(answered.user_code, "user code", endpoint),
36690
37301
  verificationUri: page(answered.verification_uri, endpoint),
36691
37302
  verificationUriComplete: answered.verification_uri_complete === undefined ? undefined : page(answered.verification_uri_complete, endpoint),
36692
37303
  expiresAt,
@@ -37419,6 +38030,16 @@ async function brokerTokenClient(env, own = "", read) {
37419
38030
  return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
37420
38031
  }
37421
38032
 
38033
+ // ../envoy-client/src/airlock-credential.ts
38034
+ var AIRLOCK_RESULTS_VAR = "DISPATCH_RESULTS_TOKEN";
38035
+ function airlockCredential(placeholder) {
38036
+ return {
38037
+ scheme: "DPoP",
38038
+ headers: () => ({ Authorization: `DPoP ${placeholder}` }),
38039
+ secret: () => placeholder
38040
+ };
38041
+ }
38042
+
37422
38043
  // ../envoy-client/src/broker-credential.ts
37423
38044
  function sessionName(naming) {
37424
38045
  if (naming === undefined)
@@ -37724,6 +38345,26 @@ async function dispatchUrl(env, config) {
37724
38345
  const target = await dispatchTarget(env, config);
37725
38346
  return target.enabled ? target.url : undefined;
37726
38347
  }
38348
+ function ownIdentityDispatch(env) {
38349
+ const url = nonEmpty(env.DISPATCH_URL);
38350
+ if (url === undefined) {
38351
+ return offWithError("DISPATCH_URL is not set: a CI job's write reads Dispatch's server from it alone");
38352
+ }
38353
+ if (httpUrl2(url) === undefined)
38354
+ return offWithError("DISPATCH_URL must be an http or https URL");
38355
+ const placeholder = nonEmpty(env[AIRLOCK_RESULTS_VAR]);
38356
+ if (placeholder === undefined) {
38357
+ return offWithError(`dispatch result --project runs under \`agent-secrets result-grant -- \u2026\`, which gives it ${AIRLOCK_RESULTS_VAR}; this environment holds none, so nothing was sent`);
38358
+ }
38359
+ if (!sendable(placeholder)) {
38360
+ return offWithError(`${AIRLOCK_RESULTS_VAR} holds white space or a control character, so it is no placeholder \`agent-secrets result-grant\` gives, and nothing was sent`);
38361
+ }
38362
+ return {
38363
+ enabled: true,
38364
+ url: withoutTrailingSlashes(url),
38365
+ credential: airlockCredential(placeholder)
38366
+ };
38367
+ }
37727
38368
  var BESIDE_TOKEN_FILES = [
37728
38369
  "DISPATCH_TOKEN_BROKER",
37729
38370
  "DISPATCH_TOKEN_BROKER_READ",