@sjawhar/claude-envoy 6.19.1 → 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.
@@ -13890,6 +13890,12 @@ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
13890
13890
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
13891
13891
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
13892
13892
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
13893
+ var SPEC_CHECK_OBSERVED_MAX = 2000;
13894
+ var SPEC_CHECK_OBSERVED_CUT_NOTE = `
13895
+ [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.]
13896
+ `;
13897
+ var SPEC_CHECK_OBSERVED_START = 500;
13898
+ var SPEC_CHECK_OBSERVED_END = SPEC_CHECK_OBSERVED_MAX - SPEC_CHECK_OBSERVED_START - [...SPEC_CHECK_OBSERVED_CUT_NOTE].length;
13893
13899
  function retriesUnderKey(status, code) {
13894
13900
  return outage(status) || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
13895
13901
  }
@@ -14491,8 +14497,16 @@ var RESULT_RECORD_FIELDS = [
14491
14497
  "excluded",
14492
14498
  "screenshots"
14493
14499
  ];
14500
+ var RESULT_PROJECT_FIELDS = ["check", "verdict", "commit", "observed"];
14501
+ var RESULT_PROJECT_REQUIRED = ["check", "verdict", "commit"];
14494
14502
  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.";
14495
- 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.";
14503
+ 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.";
14504
+ var RESULT_NOT_PROJECT_FIELDS = [
14505
+ ...RESULT_RECORD_FIELDS.filter((field) => !RESULT_PROJECT_FIELDS.includes(field)),
14506
+ "retract",
14507
+ "reason"
14508
+ ];
14509
+ 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;
14496
14510
  var DEPLOY_REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
14497
14511
  var DEPLOY_PROGRAM = /^[a-z0-9-]{1,64}$/;
14498
14512
  var DEPLOY_COMMIT = /^[0-9a-f]{40}$/;
@@ -14528,6 +14542,20 @@ function deployProblem(value) {
14528
14542
  }
14529
14543
  function resultProblem(value) {
14530
14544
  const input = value;
14545
+ if (input["project"] !== undefined) {
14546
+ const others = RESULT_NOT_PROJECT_FIELDS.filter((field) => input[field] !== undefined);
14547
+ if (others.length > 0) {
14548
+ return `${RESULT_PROJECT_RULE} This call also carries ${others.join(", ")}.`;
14549
+ }
14550
+ const missing = RESULT_PROJECT_REQUIRED.filter((field) => input[field] === undefined);
14551
+ if (missing.length > 0) {
14552
+ return `a CI job's result needs ${missing.join(", ")}. ${RESULT_PROJECT_RULE}`;
14553
+ }
14554
+ return;
14555
+ }
14556
+ if (input["verdict"] === "could_not_run") {
14557
+ return "verdict could_not_run goes with project alone: a role's result of a check of a Verification document is pass or fail.";
14558
+ }
14531
14559
  const carried = RESULT_RECORD_FIELDS.filter((field) => input[field] !== undefined);
14532
14560
  if (typeof input.retract === "string") {
14533
14561
  const reason = input.reason;
@@ -14548,6 +14576,25 @@ function resultProblem(value) {
14548
14576
  }
14549
14577
  return;
14550
14578
  }
14579
+ 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.";
14580
+ function resultsProblem(value) {
14581
+ const input = value;
14582
+ if (input["issue"] === undefined === (input["project"] === undefined)) {
14583
+ return RESULTS_OWNER_RULE;
14584
+ }
14585
+ if (input["project"] !== undefined) {
14586
+ const issueOnly = ["at", "brief"].filter((field) => input[field] !== undefined);
14587
+ if (issueOnly.length > 0) {
14588
+ return `With project, the read takes commit, check and json alone, and this call also carries ${issueOnly.join(", ")}.`;
14589
+ }
14590
+ if (input["commit"] === undefined) {
14591
+ return "With project, the read needs commit, the 40-character lowercase hex commit whose results it prints.";
14592
+ }
14593
+ return;
14594
+ }
14595
+ const projectOnly = ["commit", "check", "json"].filter((field) => input[field] !== undefined);
14596
+ return projectOnly.length === 0 ? undefined : `With issue, the read takes at and brief alone, and this call also carries ${projectOnly.join(", ")}.`;
14597
+ }
14551
14598
  var SEARCH_QUERY_MAX = 1000;
14552
14599
  var SEARCH_QUERY_HINT = "search with a short phrase of a few words, not a passage";
14553
14600
  var SEARCH_KIND_DEPTH = 100;
@@ -15003,12 +15050,13 @@ var dispatchToolSpecs = [
15003
15050
  verdict: "pass",
15004
15051
  commit: "1111111111111111111111111111111111111111"
15005
15052
  },
15006
- 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,
15053
+ 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,
15007
15054
  arguments: (z) => ({
15008
15055
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
15009
- 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(),
15056
+ 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(),
15057
+ 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(),
15010
15058
  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(),
15011
- verdict: z.enum(["pass", "fail"]).describe("Whether the check passed.").optional(),
15059
+ 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(),
15012
15060
  commit: z.string().describe("The 40-character lowercase hex commit the check ran at.").optional(),
15013
15061
  surface: z.string().describe("Where a person reaches the change.").optional(),
15014
15062
  run: z.string().describe("The command that proved it.").optional(),
@@ -15066,13 +15114,21 @@ var dispatchToolSpecs = [
15066
15114
  {
15067
15115
  name: "dispatch_results",
15068
15116
  example: { issue: "DSP-1" },
15069
- 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,
15117
+ 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,
15070
15118
  arguments: (z) => ({
15071
- issue: z.string().describe(ISSUE_REFERENCE),
15119
+ issue: z.string().describe(ISSUE_REFERENCE).optional(),
15120
+ 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(),
15121
+ commit: z.string().describe("With project: the 40-character lowercase hex commit whose results the read prints.").optional(),
15122
+ check: z.string().describe("With project: the id of one check of the spec files, whose results alone the read prints.").optional(),
15072
15123
  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(),
15073
15124
  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(),
15074
- json: z.boolean().describe("Print the complete results wire answer as JSON.").optional()
15075
- })
15125
+ json: z.boolean().describe("Print the complete results wire answer as JSON; with project, the stored results, one in-toto statement each.").optional()
15126
+ }),
15127
+ validation: {
15128
+ check: (value) => resultsProblem(value) === undefined,
15129
+ message: RESULTS_OWNER_RULE,
15130
+ refusal: (value) => resultsProblem(value) ?? RESULTS_OWNER_RULE
15131
+ }
15076
15132
  },
15077
15133
  {
15078
15134
  name: "dispatch_artifact",
@@ -19988,6 +20044,18 @@ function natsFailureReason(error) {
19988
20044
  return errorClass(error);
19989
20045
  }
19990
20046
 
20047
+ // ../envoy-client/src/go-space.ts
20048
+ var GO_SPACE = goSpaceClass();
20049
+ function goSpaceClass() {
20050
+ const set = /^\^\[(.+)\]\*\$$/u.exec(goBlankPattern.source)?.[1];
20051
+ if (set === undefined) {
20052
+ throw new Error(`goBlankPattern (@legion/contracts/go-blank) is no longer one character class: ${goBlankPattern.source}`);
20053
+ }
20054
+ return set;
20055
+ }
20056
+ var goSpaceAtEnds = new RegExp(`^[${GO_SPACE}]+|[${GO_SPACE}]+$`, "gu");
20057
+ var pathNamesNothingPattern = new RegExp(`^[${GO_SPACE}]*[./]*[${GO_SPACE}]*$`, "u");
20058
+
19991
20059
  // ../envoy-client/src/dispatch-command.ts
19992
20060
  var COMMANDS_OUTSIDE_THE_SPECS = [
19993
20061
  { name: PROXY_COMMAND, sentence: PROXY_SENTENCE, help: proxyHelp },
@@ -20447,6 +20515,28 @@ function parseCommand(argv, io) {
20447
20515
  }
20448
20516
  }
20449
20517
  }
20518
+ for (const { field, noun, tools, path } of IDENTIFIER_FIELDS) {
20519
+ const given = args[field];
20520
+ if (tools !== undefined && !tools.includes(tool))
20521
+ continue;
20522
+ const flag = setBy.get(field);
20523
+ for (const value of Array.isArray(given) ? given : [given]) {
20524
+ if (typeof value !== "string")
20525
+ continue;
20526
+ let problem;
20527
+ if (value === "") {
20528
+ problem = `${flag} is empty, so the call names no ${noun}: a variable that gives it may be empty or unset`;
20529
+ } else if (goBlankPattern.test(value)) {
20530
+ problem = `${flag} is only white space, so the call names no ${noun}`;
20531
+ } else if (path === true && pathNamesNothingPattern.test(value)) {
20532
+ problem = `${flag} is "${value.replace(goSpaceAtEnds, "")}", only dots and slashes, so the call names no ${noun}`;
20533
+ }
20534
+ if (problem === undefined)
20535
+ continue;
20536
+ problems.push(problem);
20537
+ break;
20538
+ }
20539
+ }
20450
20540
  if (help)
20451
20541
  return { kind: "help", tool };
20452
20542
  if (problems.length > 0) {
@@ -20471,6 +20561,18 @@ function appendedItem(kind, flag, value, number) {
20471
20561
  return parsed === undefined ? undefined : { value: parsed };
20472
20562
  }
20473
20563
  var ISSUE_KEY2 = /^[A-Z][A-Z0-9]*-\d+$/;
20564
+ var IDENTIFIER_FIELDS = [
20565
+ { field: "issue", noun: "issue", path: true },
20566
+ { field: "project", noun: "project", path: true },
20567
+ { field: "artifact", noun: "document", path: true },
20568
+ { field: "check", noun: "check" },
20569
+ { field: "commit", noun: "commit" },
20570
+ { field: "at", noun: "commit" },
20571
+ { field: "retract", noun: "result", path: true },
20572
+ { field: "comment", noun: "comment", path: true },
20573
+ { field: "session", noun: "session", path: true },
20574
+ { field: "parent", noun: "parent", tools: ["dispatch_issues", "dispatch_issue"] }
20575
+ ];
20474
20576
  function quoteWord(value) {
20475
20577
  return BARE_WORD.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
20476
20578
  }
@@ -22708,7 +22810,7 @@ var POLICY_REFUSAL_PATTERNS = [
22708
22810
  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),
22709
22811
  policy("sessionInvalid", "the registration of %s names a session of %d bytes; %s", K8S_ACCOUNT, NUMBER, SESSION_RULE),
22710
22812
  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),
22711
- policy("claimMissing", "the subject token's workflow_ref is not <owner>/<name>/<path>@<ref> under its repository %s", REPOSITORY),
22813
+ 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),
22712
22814
  policy("noEntry", "no entry lists the workflow %s of %s on %s", WORKFLOW_PATH, REPOSITORY, GIT_REF),
22713
22815
  policy("claimMissing", "the subject token carries no email claim, so it names no account (ask for it with format=full)"),
22714
22816
  policy("noEntry", "no entry lists the Google account %s", EMAIL),
@@ -23660,6 +23762,275 @@ async function fileBearer(bearer, url, section, env, commands = "run") {
23660
23762
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
23661
23763
  }
23662
23764
 
23765
+ // ../envoy-client/src/dispatch-write-rows.ts
23766
+ var components = looseObject({
23767
+ mode: string2(),
23768
+ ids: array(string2()).nullish(),
23769
+ reason: string2().nullish()
23770
+ });
23771
+ var advice = looseObject({
23772
+ decision_blocks: number2().int().optional(),
23773
+ issue_status: string2().optional(),
23774
+ legion_managed_status: boolean2().optional(),
23775
+ session_writes_since_human: number2().int().optional(),
23776
+ your_open_asks: array(looseObject({ id: string2(), question: string2() })).nullable().optional(),
23777
+ unparsed_openers: looseObject({ count: number2().int(), examples: array(string2()).nullable() }).optional(),
23778
+ moved_approval_request: looseObject({
23779
+ ask_id: string2(),
23780
+ issue: string2().optional(),
23781
+ project: string2().optional(),
23782
+ documents: array(looseObject({
23783
+ artifact_id: string2(),
23784
+ name: string2(),
23785
+ primary: boolean2(),
23786
+ role: string2().optional(),
23787
+ requested_version: number2().int(),
23788
+ version: number2().int()
23789
+ })).nullable()
23790
+ }).optional(),
23791
+ superseded_approval: looseObject({
23792
+ version: number2().int(),
23793
+ approved_version: number2().int(),
23794
+ approved_by: string2(),
23795
+ design_gates: array(looseObject({ issue: string2(), step: string2() })).optional()
23796
+ }).optional()
23797
+ }).optional();
23798
+ var caughtAdvice = unknown().optional();
23799
+ var ask = {
23800
+ id: askFields.id,
23801
+ issue_key: askFields.issue_key,
23802
+ artifact_id: askFields.artifact_id
23803
+ };
23804
+ var askWrite = looseObject({
23805
+ ...ask,
23806
+ question: askFields.question,
23807
+ urgency: string2(),
23808
+ waiting_on_person: string2().optional(),
23809
+ advice: caughtAdvice
23810
+ });
23811
+ var documentComment = {
23812
+ id: commentFields.id,
23813
+ ask_waiting_on: string2().optional(),
23814
+ advice
23815
+ };
23816
+ var suggestion = looseObject({ id: commentFields.id });
23817
+ var {
23818
+ repo: repo2,
23819
+ branch,
23820
+ last_error,
23821
+ last_commit,
23822
+ last_sync_at,
23823
+ components: sourceComponents
23824
+ } = ArchitectureSourceSchema.unwrap().shape;
23825
+ var architectureSource = looseObject({
23826
+ repo: repo2,
23827
+ branch,
23828
+ last_error,
23829
+ last_commit,
23830
+ last_sync_at,
23831
+ components: sourceComponents
23832
+ });
23833
+ var pictureUpload = {
23834
+ artifact: looseObject({ slug: artifactFields.slug }),
23835
+ version: looseObject({ number: versionFields.number })
23836
+ };
23837
+ var uploadedDocument = {
23838
+ id: artifactFields.id,
23839
+ slug: artifactFields.slug,
23840
+ name: artifactFields.name,
23841
+ primary: artifactFields.primary.optional(),
23842
+ role: string2().optional(),
23843
+ issue_key: artifactFields.issue_key.optional()
23844
+ };
23845
+ var actor = InboundActorSchema;
23846
+ var STORE_NOTHING = new WeakSet;
23847
+ function storesNothing(row) {
23848
+ STORE_NOTHING.add(row);
23849
+ return row;
23850
+ }
23851
+ function rowStores(row) {
23852
+ return !STORE_NOTHING.has(row);
23853
+ }
23854
+ var advance = looseObject(issueFields.advances.unwrap().unwrap().element.unwrap().shape);
23855
+ var externalLink = looseObject(ExternalLinkSchema.unwrap().shape);
23856
+ var updatedIssue = looseObject({
23857
+ key: issueFields.key,
23858
+ status: issueFields.status,
23859
+ title: issueFields.title.optional(),
23860
+ priority: issueFields.priority.optional(),
23861
+ assignee: issueFields.assignee.optional(),
23862
+ route: issueFields.route.optional(),
23863
+ parent: issueFields.parent.optional(),
23864
+ components: components.optional(),
23865
+ repo: issueFields.repo.optional(),
23866
+ resolved_repo: issueFields.resolved_repo.optional(),
23867
+ labels: issueFields.labels.nullish(),
23868
+ blocked_by: issueFields.blocked_by.nullish(),
23869
+ advances: array(advance).nullable().optional(),
23870
+ external_links: array(externalLink).nullish(),
23871
+ advice
23872
+ });
23873
+ var WRITE_ROWS = {
23874
+ issue: looseObject({
23875
+ key: issueFields.key,
23876
+ title: issueFields.title,
23877
+ project: issueFields.project,
23878
+ assignee: issueFields.assignee.optional(),
23879
+ repo: issueFields.repo.optional(),
23880
+ advice: caughtAdvice
23881
+ }),
23882
+ markdownRoundTrip: storesNothing(looseObject({ markdown: string2() })),
23883
+ fileRoundTrip: storesNothing(looseObject({ markdown: string2() })),
23884
+ related: storesNothing(looseObject({ outcome: string2() })),
23885
+ updateIssue: updatedIssue,
23886
+ updateIssueComponents: updatedIssue.extend({ components }),
23887
+ claimIssue: looseObject({
23888
+ status: issueFields.status,
23889
+ claim: looseObject({ at: string2() }).nullable(),
23890
+ legion_managed_status: boolean2().optional()
23891
+ }),
23892
+ changeIssueStatus: looseObject({
23893
+ changed: array(looseObject({
23894
+ key: issueFields.key,
23895
+ status: issueFields.status,
23896
+ parent: string2().nullable()
23897
+ })).nullable(),
23898
+ issue: looseObject({
23899
+ status: issueFields.status,
23900
+ external_links: array(externalLink).nullish()
23901
+ })
23902
+ }),
23903
+ ask: askWrite,
23904
+ artifactAsk: askWrite,
23905
+ editAsk: looseObject({ ...ask, question: askFields.question }),
23906
+ resolveAsk: looseObject({
23907
+ ...ask,
23908
+ resolution: looseObject({ reason: string2() }).optional()
23909
+ }),
23910
+ createProject: looseObject({
23911
+ key: string2(),
23912
+ name: string2(),
23913
+ created_at: string2(),
23914
+ default_assignee: string2().optional()
23915
+ }),
23916
+ syncArchitectureSources: array(architectureSource),
23917
+ syncArchitectureSource: architectureSource,
23918
+ requestApproval: looseObject({
23919
+ version: number2().int(),
23920
+ coverage: array(string2()).nullish(),
23921
+ coverage_unread: boolean2().optional(),
23922
+ ask: looseObject({
23923
+ ...ask,
23924
+ question: askFields.question,
23925
+ waiting_on_person: string2().optional()
23926
+ }).nullable(),
23927
+ approval: looseObject({ by: looseObject({ id: string2() }).nullish() })
23928
+ }),
23929
+ planApprove: looseObject({ version: number2().int() }),
23930
+ recordDeploy: looseObject({
23931
+ deploy: looseObject({
23932
+ program: string2(),
23933
+ commit: string2(),
23934
+ deployed_at: string2(),
23935
+ source: string2(),
23936
+ url: string2(),
23937
+ recorded_by: actor
23938
+ })
23939
+ }),
23940
+ reviewArtifact: looseObject({
23941
+ version: number2().int(),
23942
+ state: string2(),
23943
+ ask_id: string2().nullable(),
23944
+ reason: string2().nullable(),
23945
+ actor
23946
+ }),
23947
+ recordResult: looseObject({
23948
+ line: string2(),
23949
+ result: looseObject({
23950
+ id: string2(),
23951
+ verdict: string2(),
23952
+ role: string2(),
23953
+ check_block_id: string2(),
23954
+ check_issue_key: string2(),
23955
+ commit_sha: string2()
23956
+ })
23957
+ }),
23958
+ dryRunResult: storesNothing(looseObject({ line: string2(), result: unknown() })),
23959
+ retractResult: looseObject({
23960
+ result_id: string2(),
23961
+ reason: string2(),
23962
+ created_at: string2(),
23963
+ actor
23964
+ }),
23965
+ recordSpecCheckResult: looseObject({
23966
+ id: string2(),
23967
+ seq: number2().int(),
23968
+ attestation: looseObject({
23969
+ predicate: looseObject({ check: string2(), verdict: string2() })
23970
+ })
23971
+ }),
23972
+ comment: looseObject({ ...documentComment, issue_key: commentFields.issue_key }),
23973
+ artifactComment: looseObject(documentComment),
23974
+ suggest: suggestion,
23975
+ artifactSuggest: suggestion,
23976
+ resolveComment: looseObject({
23977
+ id: commentFields.id,
23978
+ issue_key: commentFields.issue_key,
23979
+ artifact_id: commentFields.artifact_id
23980
+ }),
23981
+ editComment: looseObject({
23982
+ id: commentFields.id,
23983
+ issue_key: commentFields.issue_key,
23984
+ artifact_id: commentFields.artifact_id
23985
+ }),
23986
+ message: looseObject({ id: messageFields.id, advice }),
23987
+ editMessage: looseObject({ id: messageFields.id, issue_key: messageFields.issue_key }),
23988
+ agentMessage: looseObject({
23989
+ id: messageFields.id,
23990
+ deliveries: array(looseObject({ state: string2(), error: string2().nullish(), delivery: string2() })).nullish()
23991
+ }),
23992
+ messageReply: looseObject({
23993
+ id: messageFields.id,
23994
+ body: messageFields.body,
23995
+ in_reply_to: messageFields.in_reply_to.optional(),
23996
+ duplicate: boolean2().optional()
23997
+ }),
23998
+ deliveryReply: looseObject({}),
23999
+ acceptMessageDelivery: looseObject({
24000
+ message_id: string2(),
24001
+ body: string2(),
24002
+ delivery: string2()
24003
+ }),
24004
+ docEdit: looseObject({
24005
+ applied: number2().int(),
24006
+ version: looseObject({ number: versionFields.number }).nullable(),
24007
+ changed: boolean2().optional(),
24008
+ unchanged_ops: array(number2().int()).nullish(),
24009
+ lost_ops: array(number2().int()).nullish(),
24010
+ written: string2().optional(),
24011
+ token: string2().optional(),
24012
+ advice: caughtAdvice
24013
+ }),
24014
+ nameArtifactVersion: looseObject({}),
24015
+ writeHandoff: looseObject({
24016
+ id: string2(),
24017
+ issue_key: string2(),
24018
+ phase: string2(),
24019
+ version: number2().int()
24020
+ }),
24021
+ projectArtifact: looseObject({
24022
+ artifact: looseObject({ ...uploadedDocument, project: artifactFields.project }),
24023
+ version: pictureUpload.version,
24024
+ advice
24025
+ }),
24026
+ agentArtifact: looseObject(pictureUpload),
24027
+ artifact: looseObject({
24028
+ artifact: looseObject(uploadedDocument),
24029
+ version: pictureUpload.version,
24030
+ advice
24031
+ })
24032
+ };
24033
+
23663
24034
  // ../envoy-client/src/excerpt.ts
23664
24035
  var REDACTED = "[redacted]";
23665
24036
  var EXCERPT_SCAN_LIMIT = 64 * 1024;
@@ -23756,6 +24127,7 @@ class SentTokens {
23756
24127
  var landed = (action) => ({ state: "may-have-landed", action });
23757
24128
  var nothing = (action) => ({ state: "nothing-sent", action });
23758
24129
  var WRITE_TRANSITIONS = {
24130
+ "uncommitted-401": { "nothing-sent": landed("end"), "may-have-landed": landed("end") },
23759
24131
  applied: { "nothing-sent": nothing("settle"), "may-have-landed": landed("settle") },
23760
24132
  judged: { "nothing-sent": nothing("settle"), "may-have-landed": landed("settle") },
23761
24133
  unjudged: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
@@ -23796,6 +24168,7 @@ var DISPATCH_URL_SETTING = "the configured Dispatch URL";
23796
24168
  class DispatchServiceError extends Error {
23797
24169
  code;
23798
24170
  status;
24171
+ retryAfterMs;
23799
24172
  name = "DispatchServiceError";
23800
24173
  fromDispatch = true;
23801
24174
  candidates;
@@ -23805,10 +24178,11 @@ class DispatchServiceError extends Error {
23805
24178
  changed;
23806
24179
  textRefusal;
23807
24180
  hint;
23808
- constructor(code, status, message, details = {}) {
24181
+ constructor(code, status, message, details = {}, retryAfterMs = null) {
23809
24182
  super(message);
23810
24183
  this.code = code;
23811
24184
  this.status = status;
24185
+ this.retryAfterMs = retryAfterMs;
23812
24186
  this.candidates = details.candidates;
23813
24187
  this.current = details.current;
23814
24188
  this.mismatches = details.mismatches;
@@ -23840,24 +24214,17 @@ class DispatchProxyRefusalError extends DispatchServiceError {
23840
24214
  fromDispatch = false;
23841
24215
  }
23842
24216
  var PROXY_CODE_FORM = /^[A-Z][A-Z0-9_]{0,63}$/;
23843
- function proxyTunnelAnswer(error) {
23844
- if (typeof error !== "object" || error === null)
24217
+ function proxyOwnAnswer(response) {
24218
+ const forwarded = response.headers.get(PROXY_FORWARDED_HEADER)?.trim().toLowerCase();
24219
+ const named = response.headers.get(PROXY_CODE_HEADER)?.trim() ?? "";
24220
+ if (forwarded !== "false" && forwarded !== "unknown" && named === "")
23845
24221
  return;
23846
- const { code, status, headers } = error;
23847
- if (code !== "ERR_PROXY_TUNNEL" || typeof status !== "number" || !(headers instanceof Headers)) {
23848
- return;
23849
- }
23850
- const proxyCode = headers.get(PROXY_CODE_HEADER) ?? "";
23851
- if (status < 400 || status > 599 || !PROXY_CODE_FORM.test(proxyCode))
23852
- return;
23853
- const forwarded = headers.get(PROXY_FORWARDED_HEADER);
23854
- return new Response(null, {
23855
- status,
23856
- headers: {
23857
- [PROXY_CODE_HEADER]: proxyCode,
23858
- ...forwarded === null ? {} : { [PROXY_FORWARDED_HEADER]: forwarded }
23859
- }
23860
- });
24222
+ return { code: named === "" ? `HTTP_${response.status}` : named, left: forwarded !== "false" };
24223
+ }
24224
+ function proxyEvent(status, left) {
24225
+ if (left)
24226
+ return "proxy-unsettled";
24227
+ return outage(status) ? "proxy-failed" : "proxy-refused";
23861
24228
  }
23862
24229
  var CREDENTIAL_ECHOED = "CREDENTIAL_ECHOED";
23863
24230
 
@@ -23878,6 +24245,8 @@ class DispatchWriteUnsettledError extends Error {
23878
24245
  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";
23879
24246
  if (last instanceof DispatchGatewayError) {
23880
24247
  answer = last.answer;
24248
+ if (last.status < 300)
24249
+ why = "the write may have reached Dispatch behind what answered it";
23881
24250
  } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
23882
24251
  answer = last.code;
23883
24252
  why = "Dispatch was still running an earlier attempt of the write";
@@ -23899,10 +24268,10 @@ class DispatchWriteLandedError extends Error {
23899
24268
  code;
23900
24269
  status;
23901
24270
  name = "DispatchWriteLandedError";
23902
- constructor(code, status, method, shownUrl) {
24271
+ constructor(code, status, method, shownUrl, options) {
23903
24272
  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";
23904
24273
  const request = `${method} ${shownUrl}`;
23905
- 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.");
24274
+ 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);
23906
24275
  this.code = code;
23907
24276
  this.status = status;
23908
24277
  }
@@ -23966,10 +24335,12 @@ class DispatchNoRouteError extends DispatchServiceError {
23966
24335
  class DispatchUnreachableError extends Error {
23967
24336
  reachedNothing;
23968
24337
  failure;
24338
+ code;
23969
24339
  constructor(message, reachedNothing, failure) {
23970
24340
  super(message);
23971
24341
  this.reachedNothing = reachedNothing;
23972
24342
  this.failure = failure;
24343
+ this.code = /^[A-Z][A-Z0-9_]*$/.test(failure) ? failure : undefined;
23973
24344
  }
23974
24345
  }
23975
24346
  function reviewNoRouteRefusal(baseUrl, route, version) {
@@ -24013,6 +24384,9 @@ function pauseFor(ms, signal) {
24013
24384
  signal.addEventListener("abort", stop, { once: true });
24014
24385
  return promise;
24015
24386
  }
24387
+ function keyEchoed(response, key) {
24388
+ return key !== "" && keyNamedBack(response) === key;
24389
+ }
24016
24390
  var STREAMED_BODY_MIN = 1 << 20;
24017
24391
  var STREAMED_BODY_CHUNK = 64 << 10;
24018
24392
  function attemptBody(body, headers, progress) {
@@ -24070,7 +24444,7 @@ function refusalIn(json) {
24070
24444
  };
24071
24445
  }
24072
24446
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
24073
- async function writeAnswer(response) {
24447
+ async function writeAnswer(response, echoed) {
24074
24448
  if (NULL_BODY_STATUSES.has(response.status)) {
24075
24449
  return {
24076
24450
  response,
@@ -24081,7 +24455,8 @@ async function writeAnswer(response) {
24081
24455
  code: undefined,
24082
24456
  error: undefined,
24083
24457
  replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
24084
- keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
24458
+ echoed,
24459
+ proxy: proxyOwnAnswer(response)
24085
24460
  };
24086
24461
  }
24087
24462
  const text = await response.text();
@@ -24097,25 +24472,23 @@ async function writeAnswer(response) {
24097
24472
  code: refusal?.code,
24098
24473
  error: refusal?.error,
24099
24474
  replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
24100
- keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
24475
+ echoed,
24476
+ proxy: proxyOwnAnswer(response)
24101
24477
  };
24102
24478
  }
24103
24479
  function isStoredKeyStatus(status) {
24104
24480
  return status >= 400 && status < 500 && status !== 401 && !outage(status);
24105
24481
  }
24106
- function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
24482
+ function answerEvent(answer, canTellDeadToken) {
24107
24483
  const { status } = answer.response;
24108
- if (proxied && answer.response.headers.get(PROXY_CODE_HEADER) !== null) {
24109
- if (answer.response.headers.get(PROXY_FORWARDED_HEADER) !== "false")
24110
- return "proxy-unsettled";
24111
- return outage(status) ? "proxy-failed" : "proxy-refused";
24112
- }
24484
+ if (answer.proxy !== undefined)
24485
+ return proxyEvent(status, answer.proxy.left);
24113
24486
  if (status >= 200 && status < 300) {
24114
24487
  if (answer.notJson)
24115
24488
  return "foreign-2xx";
24116
24489
  if (answer.malformed)
24117
24490
  return "body-malformed";
24118
- return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
24491
+ return answer.echoed ? "applied" : "foreign-2xx";
24119
24492
  }
24120
24493
  if (status >= 300 && status < 400)
24121
24494
  return "redirect";
@@ -24125,15 +24498,21 @@ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
24125
24498
  if (status === 404 && answer.code === "NOT_FOUND" && answer.error?.startsWith(NO_ROUTE_MESSAGE_PREFIX) === true) {
24126
24499
  return "no-route";
24127
24500
  }
24501
+ if (status === 401 && answer.echoed)
24502
+ return "uncommitted-401";
24503
+ if (tokenNotCheckedAnswer(status, answer.code))
24504
+ return "try-later";
24128
24505
  const textRefusal = answer.error !== undefined && answer.response.headers.has(TEXT_REFUSAL_HEADER);
24129
24506
  if (!textRefusal && retriesUnderKey(status, answer.code)) {
24130
24507
  if (status === 409)
24131
24508
  return "in-flight";
24132
24509
  return mayHaveReachedServer(status) ? "may-have-run" : "try-later";
24133
24510
  }
24511
+ if (!answer.echoed)
24512
+ return "unjudged";
24134
24513
  if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
24135
24514
  return "judged";
24136
- if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
24515
+ if (!isStoredKeyStatus(status))
24137
24516
  return "unjudged";
24138
24517
  if (answer.code === IDEMPOTENCY_KEY_REUSED)
24139
24518
  return "judged";
@@ -24200,6 +24579,103 @@ function gatewayAdvice(method, status) {
24200
24579
  function gatewayClears(status) {
24201
24580
  return outage(status) || status >= 200 && status < 300;
24202
24581
  }
24582
+ var DISPATCH_ANSWER_LOST = "ANSWER_LOST";
24583
+
24584
+ class DispatchAnswerMissingError extends Error {
24585
+ status;
24586
+ name = "DispatchAnswerMissingError";
24587
+ code = DISPATCH_ANSWER_LOST;
24588
+ constructor(status, method, url, options) {
24589
+ 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);
24590
+ this.status = status;
24591
+ }
24592
+ }
24593
+
24594
+ class DispatchEmptyPathError extends Error {
24595
+ name = "DispatchEmptyPathError";
24596
+ constructor(path) {
24597
+ const route = path.map((segment) => segment === "" ? "{empty}" : pathNamesNothingPattern.test(segment) ? `{${JSON.stringify(segment)}}` : segment).join("/");
24598
+ 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`);
24599
+ }
24600
+ }
24601
+ var PROXY_TUNNEL_REFUSED = /: (\d{3}) ?(.*)$/;
24602
+
24603
+ class AirlockTunnelRefusedError extends Error {
24604
+ status;
24605
+ reason;
24606
+ proxyCode;
24607
+ name = "AirlockTunnelRefusedError";
24608
+ code = "AIRLOCK_TUNNEL_REFUSED";
24609
+ constructor(status, reason, proxyCode, options) {
24610
+ const said = status === 0 ? reason : `${status}${reason === "" ? "" : ` ${reason}`}`;
24611
+ super(`the airlock proxy refused the connection (${said}); nothing was sent to Dispatch`, options);
24612
+ this.status = status;
24613
+ this.reason = reason;
24614
+ this.proxyCode = proxyCode;
24615
+ }
24616
+ }
24617
+ function tunnelRefusal(error) {
24618
+ if (!(error instanceof Error) || Reflect.get(error, "code") !== "ERR_PROXY_TUNNEL") {
24619
+ return;
24620
+ }
24621
+ const headers = Reflect.get(error, "headers");
24622
+ const named = headers instanceof Headers ? headers.get(PROXY_CODE_HEADER)?.trim() ?? "" : "";
24623
+ const proxyCode = PROXY_CODE_FORM.test(named) ? named : undefined;
24624
+ const said = PROXY_TUNNEL_REFUSED.exec(error.message);
24625
+ return said === null ? new AirlockTunnelRefusedError(0, error.message, proxyCode, { cause: error }) : new AirlockTunnelRefusedError(Number(said[1]), said[2]?.trim() ?? "", proxyCode, {
24626
+ cause: error
24627
+ });
24628
+ }
24629
+
24630
+ class AirlockRefusedError extends Error {
24631
+ status;
24632
+ code;
24633
+ body;
24634
+ name = "AirlockRefusedError";
24635
+ constructor(status, code, body) {
24636
+ super(`the airlock proxy answered ${status} ${code} itself, and sent nothing on: ${body}`);
24637
+ this.status = status;
24638
+ this.code = code;
24639
+ this.body = body;
24640
+ }
24641
+ }
24642
+
24643
+ class AirlockOutcomeUnknownError extends Error {
24644
+ status;
24645
+ code;
24646
+ body;
24647
+ name = "AirlockOutcomeUnknownError";
24648
+ constructor(status, code, body) {
24649
+ super(`the airlock proxy answered ${status} ${code} itself after the write may have reached Dispatch: ${body}`);
24650
+ this.status = status;
24651
+ this.code = code;
24652
+ this.body = body;
24653
+ }
24654
+ }
24655
+ var TOKEN_NOT_CHECKED = {
24656
+ BROKER_TOKEN_RATE_LIMITED: 429,
24657
+ BROKER_UNAVAILABLE: 503
24658
+ };
24659
+ function tokenNotCheckedAnswer(status, code) {
24660
+ return code !== undefined && TOKEN_NOT_CHECKED[code] === status;
24661
+ }
24662
+ function tokenNotChecked(error) {
24663
+ return error instanceof DispatchServiceError && error.fromDispatch && tokenNotCheckedAnswer(error.status, error.code);
24664
+ }
24665
+ function writeOutcomeUnknown(error) {
24666
+ if (error instanceof DispatchWriteUnsettledError)
24667
+ return true;
24668
+ if (error instanceof DispatchGatewayError)
24669
+ return error.mayHaveReachedDispatch;
24670
+ if (error instanceof DispatchProxyRefusalError)
24671
+ return false;
24672
+ if (error instanceof DispatchServiceError)
24673
+ return error.status >= 500 && !tokenNotChecked(error);
24674
+ return false;
24675
+ }
24676
+ function keyNamedBack(response) {
24677
+ return (response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "").replace(/^"(.*)"$/, "$1");
24678
+ }
24203
24679
 
24204
24680
  class DispatchClient {
24205
24681
  fetchImpl;
@@ -24223,6 +24699,9 @@ class DispatchClient {
24223
24699
  try {
24224
24700
  return await fetchImpl(input, { ...init, redirect: "manual" });
24225
24701
  } catch (error) {
24702
+ const tunnel = tunnelRefusal(error);
24703
+ if (tunnel !== undefined)
24704
+ throw tunnel;
24226
24705
  if (error instanceof TypeError) {
24227
24706
  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));
24228
24707
  }
@@ -24241,7 +24720,7 @@ class DispatchClient {
24241
24720
  return this.#credential.secret();
24242
24721
  }
24243
24722
  async issue(input) {
24244
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "issues"], input);
24723
+ const answer = await this.#writeAnswer("POST", ["api", "v1", "issues"], WRITE_ROWS.issue, input);
24245
24724
  return { ...answer.payload, created: answer.status === 201 };
24246
24725
  }
24247
24726
  async resolveIssue(issueReference) {
@@ -24269,28 +24748,28 @@ class DispatchClient {
24269
24748
  async listIssueArtifacts(issue) {
24270
24749
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"]);
24271
24750
  }
24272
- async markdownRoundTrip(markdown, newDocument) {
24273
- return this.#roundTrip(["api", "v1", "markdown", "round-trip"], { markdown }, newDocument);
24751
+ async markdownRoundTrip(markdown, newDocument = false) {
24752
+ return this.#roundTrip(["api", "v1", "markdown", "round-trip"], WRITE_ROWS.markdownRoundTrip, { markdown }, newDocument);
24274
24753
  }
24275
- async fileRoundTrip(bytes, newDocument) {
24754
+ async fileRoundTrip(bytes, newDocument = false) {
24276
24755
  const file = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
24277
- return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], { file }, newDocument);
24756
+ return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], WRITE_ROWS.fileRoundTrip, { file }, newDocument);
24278
24757
  }
24279
- async#roundTrip(path, body, newDocument) {
24280
- const answer = await this.#writingNothing(path, newDocument ? { ...body, new_document: true } : body, { writes: false });
24758
+ async#roundTrip(path, row, body, newDocument) {
24759
+ const answer = await this.#writingNothing(path, row, newDocument ? { ...body, new_document: true } : body);
24281
24760
  return answer.markdown;
24282
24761
  }
24283
24762
  async listProjectArtifacts(project, unlinked = false) {
24284
24763
  return this.#json("GET", ["api", "v1", "projects", project, "artifacts"], undefined, unlinked ? { unlinked: "true" } : undefined);
24285
24764
  }
24286
24765
  async projectArtifact(project, input, key) {
24287
- return this.#upload(["api", "v1", "projects", project, "artifacts"], input, key);
24766
+ return this.#upload(["api", "v1", "projects", project, "artifacts"], input, WRITE_ROWS.projectArtifact, key);
24288
24767
  }
24289
24768
  async getProjectArtifact(project, slug) {
24290
24769
  return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug]);
24291
24770
  }
24292
24771
  async agentArtifact(sessionId, input) {
24293
- return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input);
24772
+ return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input, WRITE_ROWS.agentArtifact);
24294
24773
  }
24295
24774
  async getAgentArtifact(sessionId, slug) {
24296
24775
  return this.#json("GET", ["api", "v1", "agents", sessionId, "artifacts", slug]);
@@ -24311,24 +24790,24 @@ class DispatchClient {
24311
24790
  return this.#json("GET", path, undefined, request);
24312
24791
  }
24313
24792
  async related(project, input) {
24314
- return this.#writingNothing(["api", "v1", "projects", project, "related"], input);
24793
+ return this.#writingNothing(["api", "v1", "projects", project, "related"], WRITE_ROWS.related, input);
24315
24794
  }
24316
24795
  async getIssue(issue) {
24317
24796
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue)]);
24318
24797
  }
24319
24798
  async updateIssue(issue, input) {
24320
- return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
24799
+ return this.#write("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input.components === undefined ? WRITE_ROWS.updateIssue : WRITE_ROWS.updateIssueComponents, input);
24321
24800
  }
24322
24801
  async changeIssueStatus(issue, input) {
24323
24802
  const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "status-change"];
24324
24803
  try {
24325
- return await this.#json("POST", path, input);
24804
+ return await this.#write("POST", path, WRITE_ROWS.changeIssueStatus, input);
24326
24805
  } catch (error) {
24327
24806
  throw this.#refusalOfNoRoute(error, path, (route) => statusChangeNoRouteRefusal(this.#baseUrl, route));
24328
24807
  }
24329
24808
  }
24330
24809
  async claimIssue(issue, input = {}) {
24331
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
24810
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], WRITE_ROWS.claimIssue, input);
24332
24811
  }
24333
24812
  async releaseIssueClaim(issue, input = {}) {
24334
24813
  return this.#json("DELETE", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
@@ -24358,7 +24837,7 @@ class DispatchClient {
24358
24837
  return { issue, events };
24359
24838
  }
24360
24839
  async ask(issue, input) {
24361
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], input);
24840
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], WRITE_ROWS.ask, input);
24362
24841
  }
24363
24842
  async openAsks(sessionID, since) {
24364
24843
  return this.#json("GET", ["api", "v1", "asks", "open"], undefined, {
@@ -24403,7 +24882,7 @@ class DispatchClient {
24403
24882
  return this.#json("GET", ["api", "v1", "credential-requests"], undefined, { approver: "me" });
24404
24883
  }
24405
24884
  async createProject(input) {
24406
- return this.#json("POST", ["api", "v1", "projects"], input);
24885
+ return this.#write("POST", ["api", "v1", "projects"], WRITE_ROWS.createProject, input);
24407
24886
  }
24408
24887
  async listProjects() {
24409
24888
  return this.#json("GET", ["api", "v1", "projects"]);
@@ -24439,26 +24918,12 @@ class DispatchClient {
24439
24918
  }
24440
24919
  async syncArchitectureSources(project) {
24441
24920
  try {
24442
- return await this.#json("POST", [
24443
- "api",
24444
- "v1",
24445
- "projects",
24446
- project,
24447
- "architecture-sources",
24448
- "sync"
24449
- ]);
24921
+ return await this.#write("POST", ["api", "v1", "projects", project, "architecture-sources", "sync"], WRITE_ROWS.syncArchitectureSources);
24450
24922
  } catch (error) {
24451
24923
  if (!(error instanceof DispatchNoRouteError))
24452
24924
  throw error;
24453
24925
  }
24454
- const source = await this.#json("POST", [
24455
- "api",
24456
- "v1",
24457
- "projects",
24458
- project,
24459
- "architecture-source",
24460
- "sync"
24461
- ]);
24926
+ const source = await this.#write("POST", ["api", "v1", "projects", project, "architecture-source", "sync"], WRITE_ROWS.syncArchitectureSource);
24462
24927
  return [source];
24463
24928
  }
24464
24929
  async syncArchitectureSource(project, repo) {
@@ -24466,37 +24931,25 @@ class DispatchClient {
24466
24931
  if (!owner || !name || rest.length > 0) {
24467
24932
  throw new Error(`repository must be owner/name, got ${JSON.stringify(repo)}`);
24468
24933
  }
24469
- return this.#json("POST", [
24470
- "api",
24471
- "v1",
24472
- "projects",
24473
- project,
24474
- "architecture-sources",
24475
- owner,
24476
- name,
24477
- "sync"
24478
- ]);
24934
+ return this.#write("POST", ["api", "v1", "projects", project, "architecture-sources", owner, name, "sync"], WRITE_ROWS.syncArchitectureSource);
24479
24935
  }
24480
24936
  async resolveAsk(id, input) {
24481
- return this.#json("POST", ["api", "v1", "asks", id, "resolve"], input);
24937
+ return this.#write("POST", ["api", "v1", "asks", id, "resolve"], WRITE_ROWS.resolveAsk, input);
24482
24938
  }
24483
24939
  async requestApproval(artifactID, input) {
24484
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], input);
24940
+ const answer = await this.#writeAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], WRITE_ROWS.requestApproval, input);
24485
24941
  return { ...answer.payload, recorded: answer.status === 201 };
24486
24942
  }
24487
24943
  async planApprove(artifactID, input) {
24488
- return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
24944
+ return this.#write("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], WRITE_ROWS.planApprove, input);
24489
24945
  }
24490
24946
  async reviewArtifact(artifactID, version, input) {
24491
24947
  const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
24492
24948
  const body = { state: input.state, reason: input.reason };
24493
24949
  try {
24494
24950
  const route = await this.#credential.approveRoute?.(this.#credentialSignal(this.#signal));
24495
- if (route !== undefined) {
24496
- const via = this.#throughProxy(route, this.#url(path));
24497
- return (await this.#jsonAnswer("POST", path, body, { via })).payload;
24498
- }
24499
- return await this.#json("POST", path, body);
24951
+ const via = route === undefined ? undefined : this.#throughProxy(route, this.#url(path));
24952
+ return await this.#write("POST", path, WRITE_ROWS.reviewArtifact, body, { via });
24500
24953
  } catch (error) {
24501
24954
  throw this.#refusalOfNoRoute(error, path, (route) => reviewNoRouteRefusal(this.#baseUrl, route, version));
24502
24955
  }
@@ -24517,12 +24970,12 @@ class DispatchClient {
24517
24970
  return { credential, init: { proxy: proxy.toString(), tls: { ca: route.caCertificate } } };
24518
24971
  }
24519
24972
  async recordResult(issue, input) {
24520
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
24973
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], WRITE_ROWS.recordResult, input);
24521
24974
  }
24522
24975
  async dryRunResult(issue, input) {
24523
24976
  const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "results", "dry-run"];
24524
24977
  try {
24525
- return await this.#writingNothing(path, input, { writes: false });
24978
+ return await this.#writingNothing(path, WRITE_ROWS.dryRunResult, input);
24526
24979
  } catch (error) {
24527
24980
  throw this.#refusalOfNoRoute(error, path, (route) => resultDryRunNoRouteRefusal(this.#baseUrl, route));
24528
24981
  }
@@ -24531,19 +24984,19 @@ class DispatchClient {
24531
24984
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], undefined, at === undefined ? undefined : { at });
24532
24985
  }
24533
24986
  async recordDeploy(input) {
24534
- return this.#json("POST", ["api", "v1", "deploys"], input);
24987
+ return this.#write("POST", ["api", "v1", "deploys"], WRITE_ROWS.recordDeploy, input);
24535
24988
  }
24536
24989
  async deploys(repo) {
24537
24990
  return this.#json("GET", ["api", "v1", "deploys"], undefined, { repo });
24538
24991
  }
24539
24992
  async retractResult(resultID, input) {
24540
- return this.#json("POST", ["api", "v1", "results", resultID, "retract"], input);
24993
+ return this.#write("POST", ["api", "v1", "results", resultID, "retract"], WRITE_ROWS.retractResult, input);
24541
24994
  }
24542
24995
  async editAsk(id, input) {
24543
- return this.#json("PATCH", ["api", "v1", "asks", id], input);
24996
+ return this.#write("PATCH", ["api", "v1", "asks", id], WRITE_ROWS.editAsk, input);
24544
24997
  }
24545
24998
  async comment(issue, input) {
24546
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], input);
24999
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], WRITE_ROWS.comment, input);
24547
25000
  }
24548
25001
  async listIssueAsks(issue, state) {
24549
25002
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], undefined, state === undefined ? undefined : { state });
@@ -24552,11 +25005,11 @@ class DispatchClient {
24552
25005
  return this.#json("GET", ["api", "v1", "artifacts", id, "asks"], undefined, state === undefined ? undefined : { state });
24553
25006
  }
24554
25007
  async artifactAsk(id, input) {
24555
- return this.#json("POST", ["api", "v1", "artifacts", id, "asks"], input);
25008
+ return this.#write("POST", ["api", "v1", "artifacts", id, "asks"], WRITE_ROWS.artifactAsk, input);
24556
25009
  }
24557
25010
  async suggest(issue, input) {
24558
25011
  const { replace_with, ...comment } = input;
24559
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], {
25012
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], WRITE_ROWS.suggest, {
24560
25013
  ...comment,
24561
25014
  suggestion: { replace_with }
24562
25015
  });
@@ -24565,27 +25018,27 @@ class DispatchClient {
24565
25018
  return this.#json("GET", ["api", "v1", "artifacts", id, "comments"]);
24566
25019
  }
24567
25020
  async artifactComment(id, input) {
24568
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], input);
25021
+ return this.#write("POST", ["api", "v1", "artifacts", id, "comments"], WRITE_ROWS.artifactComment, input);
24569
25022
  }
24570
25023
  async artifactSuggest(id, input) {
24571
25024
  const { replace_with, ...comment } = input;
24572
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], {
25025
+ return this.#write("POST", ["api", "v1", "artifacts", id, "comments"], WRITE_ROWS.artifactSuggest, {
24573
25026
  ...comment,
24574
25027
  suggestion: { replace_with }
24575
25028
  });
24576
25029
  }
24577
25030
  async message(issue, input) {
24578
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
25031
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], WRITE_ROWS.message, input);
24579
25032
  }
24580
25033
  async agentMessage(sessionId, input) {
24581
- return this.#json("POST", ["api", "v1", "agents", sessionId, "messages"], input);
25034
+ return this.#write("POST", ["api", "v1", "agents", sessionId, "messages"], WRITE_ROWS.agentMessage, input);
24582
25035
  }
24583
25036
  async messageReply(id, input, options = {}) {
24584
- return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
25037
+ return this.#write("POST", ["api", "v1", "messages", id, "reply"], WRITE_ROWS.messageReply, input, { query: options.followUp === true ? { follow_up: "true" } : undefined });
24585
25038
  }
24586
25039
  async deliveryReply(resource, id, input, options = {}) {
24587
25040
  const collection = resource === "message" ? "messages" : "comments";
24588
- await this.#json("POST", ["api", "v1", collection, id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
25041
+ await this.#write("POST", ["api", "v1", collection, id, "reply"], WRITE_ROWS.deliveryReply, input, { query: options.followUp === true ? { follow_up: "true" } : undefined });
24589
25042
  }
24590
25043
  async getMessage(issue, id) {
24591
25044
  return this.#json("GET", [
@@ -24601,7 +25054,7 @@ class DispatchClient {
24601
25054
  return this.#json("GET", ["api", "v1", "messages", id], undefined, session === undefined ? undefined : { session });
24602
25055
  }
24603
25056
  async editMessage(id, input) {
24604
- return this.#json("PATCH", ["api", "v1", "messages", id], input);
25057
+ return this.#write("PATCH", ["api", "v1", "messages", id], WRITE_ROWS.editMessage, input);
24605
25058
  }
24606
25059
  async deleteMessage(id, actor) {
24607
25060
  return this.#json("DELETE", ["api", "v1", "messages", id], { actor });
@@ -24613,10 +25066,10 @@ class DispatchClient {
24613
25066
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"]);
24614
25067
  }
24615
25068
  async acceptMessageDelivery(id, attempt, input) {
24616
- return this.#json("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], input);
25069
+ return this.#write("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], WRITE_ROWS.acceptMessageDelivery, input);
24617
25070
  }
24618
25071
  async artifact(issue, input) {
24619
- return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input);
25072
+ return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input, WRITE_ROWS.artifact);
24620
25073
  }
24621
25074
  async getArtifact(id) {
24622
25075
  return this.#json("GET", ["api", "v1", "artifacts", id]);
@@ -24658,10 +25111,12 @@ class DispatchClient {
24658
25111
  return this.#json("GET", ["api", "v1", "messages", id, "blocks"], undefined, session === undefined ? undefined : { session });
24659
25112
  }
24660
25113
  async docEdit(id, input, key) {
24661
- return this.#json("POST", ["api", "v1", "artifacts", id, "edits"], input, undefined, undefined, key);
25114
+ return this.#write("POST", ["api", "v1", "artifacts", id, "edits"], WRITE_ROWS.docEdit, input, {
25115
+ key
25116
+ });
24662
25117
  }
24663
25118
  async nameArtifactVersion(id, input) {
24664
- return this.#json("POST", ["api", "v1", "artifacts", id, "versions"], input);
25119
+ return this.#write("POST", ["api", "v1", "artifacts", id, "versions"], WRITE_ROWS.nameArtifactVersion, input);
24665
25120
  }
24666
25121
  async getArtifactEvents(id, after = 0, limit = 200) {
24667
25122
  return this.#json("GET", ["api", "v1", "artifacts", id, "events"], undefined, { after, limit });
@@ -24682,10 +25137,12 @@ class DispatchClient {
24682
25137
  return this.#json("GET", ["api", "v1", "comments", id]);
24683
25138
  }
24684
25139
  async resolveComment(id, actor) {
24685
- return this.#json("POST", ["api", "v1", "comments", id, "resolve"], { actor });
25140
+ return this.#write("POST", ["api", "v1", "comments", id, "resolve"], WRITE_ROWS.resolveComment, {
25141
+ actor
25142
+ });
24686
25143
  }
24687
25144
  async editComment(id, input) {
24688
- return this.#json("PATCH", ["api", "v1", "comments", id], input);
25145
+ return this.#write("PATCH", ["api", "v1", "comments", id], WRITE_ROWS.editComment, input);
24689
25146
  }
24690
25147
  async deleteComment(id, actor) {
24691
25148
  return this.#json("DELETE", ["api", "v1", "comments", id], { actor });
@@ -24697,7 +25154,7 @@ class DispatchClient {
24697
25154
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"]);
24698
25155
  }
24699
25156
  async writeHandoff(issue, phase, input) {
24700
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs", phase], input);
25157
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs", phase], WRITE_ROWS.writeHandoff, input);
24701
25158
  }
24702
25159
  async listHandoffs(issue) {
24703
25160
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs"]);
@@ -24732,6 +25189,60 @@ class DispatchClient {
24732
25189
  ...query.since === undefined ? {} : { since: query.since }
24733
25190
  });
24734
25191
  }
25192
+ #writePayload(method, url, answer, write) {
25193
+ const stores = rowStores(write.row);
25194
+ if (!answer.response.ok) {
25195
+ if (!stores && answer.echoed && answer.code === IDEMPOTENCY_KEY_COMMITTED)
25196
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
25197
+ return this.#payloadOf(method, url, answer);
25198
+ }
25199
+ if (NULL_BODY_STATUSES.has(answer.response.status) && !stores)
25200
+ return this.#payloadOf(method, url, answer);
25201
+ const value = answer.json?.value;
25202
+ const replayed = answer.response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1";
25203
+ if (answerNotKept(answer.response.status, replayed, value)) {
25204
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text, undefined, IDEMPOTENCY_ANSWER_NOT_KEPT);
25205
+ }
25206
+ const parsed = write.row.safeParse(value);
25207
+ if (!parsed.success)
25208
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text, parsed.error);
25209
+ return value;
25210
+ }
25211
+ #missingWriteAnswer(method, url, response, write, text, cause, code = DISPATCH_ANSWER_LOST) {
25212
+ const shown = requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING);
25213
+ if (!rowStores(write.row))
25214
+ return code === IDEMPOTENCY_ANSWER_NOT_KEPT && keyEchoed(response, write.key) ? new DispatchAnswerNotKeptError(response.status, method, shown) : new DispatchAnswerMissingError(response.status, method, shown, { cause });
25215
+ if (keyEchoed(response, write.key))
25216
+ return new DispatchWriteLandedError(code, response.status, method, shown, { cause });
25217
+ const names = keyNamedBack(response) === "" ? "naming no key back" : "naming another request's key back";
25218
+ return new DispatchWriteUnsettledError(this.#gatewayError(method, url, response, text, "the write's answer", {
25219
+ advice: "the write may have reached Dispatch behind what answered it",
25220
+ also: `${names}, `
25221
+ }), write.progress.sent, write.key);
25222
+ }
25223
+ async#writeAnswer(method, path, row, body, options = {}) {
25224
+ const url = this.#url(path, options.query);
25225
+ const write = this.#writeCall(method, url, row, options.key);
25226
+ const answer = await this.#sendWrite(method, url, body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" }, "application/json", undefined, write, options.via);
25227
+ return {
25228
+ status: answer.response.status,
25229
+ payload: this.#writePayload(method, url, answer, write)
25230
+ };
25231
+ }
25232
+ async#write(method, path, row, body, options = {}) {
25233
+ return (await this.#writeAnswer(method, path, row, body, options)).payload;
25234
+ }
25235
+ async specCheckResults(project, commit, check) {
25236
+ return this.#json("GET", ["api", "v1", "projects", project, "results"], undefined, {
25237
+ commit,
25238
+ check
25239
+ });
25240
+ }
25241
+ async recordSpecCheckResult(project, input) {
25242
+ const { commit, check, verdict, observed } = input;
25243
+ const body = { commit, check, verdict, observed };
25244
+ return this.#write("POST", ["api", "v1", "projects", project, "results"], WRITE_ROWS.recordSpecCheckResult, body);
25245
+ }
24735
25246
  async#resolveIssue(issueReference) {
24736
25247
  if (!issueReference.includes("#"))
24737
25248
  return issueReference;
@@ -24749,21 +25260,12 @@ class DispatchClient {
24749
25260
  throw error;
24750
25261
  }
24751
25262
  }
24752
- async#json(method, path, body, query, signal, key) {
24753
- return (await this.#jsonAnswer(method, path, body, { query, signal, key })).payload;
24754
- }
24755
- async#jsonAnswer(method, path, body, options = {}) {
24756
- const { query, signal, key, writes = true, via } = options;
25263
+ async#json(method, path, body, query, signal) {
24757
25264
  const url = this.#url(path, query);
24758
25265
  const encoded = body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" };
24759
- const write = this.#writeCall(method, url, key, writes);
24760
- if (write !== undefined) {
24761
- const answer = await this.#write(method, url, encoded, "application/json", signal, write, via);
24762
- return { status: answer.response.status, payload: this.#payloadOf(method, url, answer) };
24763
- }
24764
25266
  return this.#noRoute(async () => {
24765
25267
  const { answer: response } = await this.#send(method, url, encoded, undefined, signal);
24766
- return { status: response.status, payload: await this.#response(method, url, response) };
25268
+ return this.#response(method, url, response);
24767
25269
  }, signal);
24768
25270
  }
24769
25271
  async#noRoute(attempt, signal) {
@@ -24780,19 +25282,17 @@ class DispatchClient {
24780
25282
  return error;
24781
25283
  return refuse(`POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`);
24782
25284
  }
24783
- #writeCall(method, url, key, writes = true) {
24784
- if (method !== "POST" && method !== "PATCH")
24785
- return;
25285
+ #writeCall(method, url, row, key) {
24786
25286
  return {
24787
25287
  key: key ?? crypto.randomUUID(),
24788
25288
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
24789
- writes,
24790
- progress: { sent: 0, running: false, keyEchoed: false }
25289
+ row,
25290
+ progress: { sent: 0, running: false }
24791
25291
  };
24792
25292
  }
24793
- async#upload(path, input, key) {
25293
+ async#upload(path, input, row, key) {
24794
25294
  if (input.file === undefined) {
24795
- return this.#json("POST", path, input, undefined, undefined, key);
25295
+ return this.#write("POST", path, row, input, { key });
24796
25296
  }
24797
25297
  const form = new FormData;
24798
25298
  form.set("name", input.name);
@@ -24803,31 +25303,24 @@ class DispatchClient {
24803
25303
  if (input.actor !== undefined)
24804
25304
  form.set("actor", JSON.stringify(input.actor));
24805
25305
  form.set("file", input.file, input.name);
24806
- return this.#form("POST", path, form, key);
25306
+ return this.#form(path, form, row, key);
24807
25307
  }
24808
- async#form(method, path, form, callerKey) {
25308
+ async#form(path, form, row, key) {
24809
25309
  const url = this.#url(path);
24810
25310
  const encoded = new Response(form);
24811
25311
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
24812
25312
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
24813
- const write = this.#writeCall(method, url, callerKey);
24814
- if (write !== undefined) {
24815
- const answer = await this.#write(method, url, body, "application/json", undefined, write);
24816
- return this.#payloadOf(method, url, answer);
24817
- }
24818
- return this.#noRoute(async () => this.#response(method, url, (await this.#send(method, url, body)).answer));
25313
+ const write = this.#writeCall("POST", url, row, key);
25314
+ const answer = await this.#sendWrite("POST", url, body, "application/json", undefined, write);
25315
+ return this.#writePayload("POST", url, answer, write);
24819
25316
  }
24820
- async#writingNothing(path, body, options = {}) {
25317
+ async#writingNothing(path, row, body) {
24821
25318
  for (let keys = 1;; keys++) {
24822
25319
  try {
24823
- return (await this.#jsonAnswer("POST", path, body, options)).payload;
25320
+ return await this.#write("POST", path, row, body);
24824
25321
  } catch (error) {
24825
- if (!(error instanceof DispatchWriteLandedError) || error.code !== IDEMPOTENCY_ANSWER_NOT_KEPT) {
25322
+ if (!(error instanceof DispatchAnswerNotKeptError) || keys === 2)
24826
25323
  throw error;
24827
- }
24828
- if (keys === 2) {
24829
- throw new DispatchAnswerNotKeptError(error.status, "POST", requestForText(this.#baseUrl, this.#url(path), DISPATCH_URL_SETTING));
24830
- }
24831
25324
  }
24832
25325
  }
24833
25326
  }
@@ -24899,9 +25392,10 @@ class DispatchClient {
24899
25392
  });
24900
25393
  return { answer, presented };
24901
25394
  }
24902
- async#write(method, url, body, accept, signal, write, via) {
25395
+ async#sendWrite(method, url, body, accept, signal, write, via) {
24903
25396
  const limit = signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]);
24904
25397
  const { key, progress } = write;
25398
+ const stores = rowStores(write.row);
24905
25399
  const credential = via?.credential ?? this.#credential;
24906
25400
  const headers = { Accept: accept, [IDEMPOTENCY_KEY_HEADER]: key };
24907
25401
  if (body !== undefined)
@@ -24948,18 +25442,17 @@ class DispatchClient {
24948
25442
  response = await this.#attempt(url, method, { ...headers, ...presented }, body, silenceMs, limit, via?.init);
24949
25443
  } catch (error) {
24950
25444
  return {
24951
- event: stoppedEvent(limit, true, error) ?? (error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
25445
+ event: stoppedEvent(limit, true, error) ?? (error instanceof AirlockTunnelRefusedError ? proxyEvent(error.status, false) : error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
24952
25446
  failure: error,
24953
25447
  presented,
24954
25448
  sent
24955
25449
  };
24956
25450
  }
25451
+ const echoed = keyEchoed(response, key);
24957
25452
  const heard = { retryAfterMs: retryAfterMs(response.headers) };
24958
- if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
24959
- progress.keyEchoed = true;
24960
25453
  let answer;
24961
25454
  try {
24962
- answer = await writeAnswer(response);
25455
+ answer = await writeAnswer(response, echoed);
24963
25456
  } catch (error) {
24964
25457
  const stop = stoppedEvent(limit, true, error);
24965
25458
  return {
@@ -24971,7 +25464,7 @@ class DispatchClient {
24971
25464
  };
24972
25465
  }
24973
25466
  return {
24974
- event: answerEvent(answer, write.key, progress.keyEchoed, credential.stale !== undefined && !deadTokenTold, via !== undefined),
25467
+ event: answerEvent(answer, credential.stale !== undefined && !deadTokenTold),
24975
25468
  answer,
24976
25469
  presented,
24977
25470
  sent,
@@ -24989,13 +25482,14 @@ class DispatchClient {
24989
25482
  return result;
24990
25483
  };
24991
25484
  const waitStopped = (error) => ({
25485
+ ...state === "nothing-sent" && error instanceof Error && error.name === "TimeoutError" ? last : {},
24992
25486
  event: stoppedEvent(limit, false, error) ?? "cancelled",
24993
25487
  failure: error
24994
25488
  });
24995
25489
  let last = await next();
24996
25490
  let event = last.event;
24997
25491
  for (;; ) {
24998
- const step = writeStep(state, event, write.writes);
25492
+ const step = writeStep(state, event, stores);
24999
25493
  state = step.state;
25000
25494
  if ((event === "silence" || event === "in-flight") && !upload)
25001
25495
  progress.running = true;
@@ -25087,9 +25581,6 @@ class DispatchClient {
25087
25581
  } catch (error) {
25088
25582
  if (cut.signal.aborted && !limit.aborted)
25089
25583
  throw cut.signal.reason;
25090
- const refused = transport === undefined ? undefined : proxyTunnelAnswer(error);
25091
- if (refused !== undefined)
25092
- return refused;
25093
25584
  throw error;
25094
25585
  } finally {
25095
25586
  answered = true;
@@ -25098,15 +25589,22 @@ class DispatchClient {
25098
25589
  }
25099
25590
  async#endWrite(method, url, state, event, answer, failure, write, routeSpent, via) {
25100
25591
  const { request, progress } = write;
25592
+ if (answer?.response.status === 409 && answer.code === IDEMPOTENCY_KEY_COMMITTED && !answer.echoed) {
25593
+ return this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
25594
+ }
25101
25595
  let own = failure;
25102
- const proxyCode = via === undefined ? null : answer?.response.headers.get(PROXY_CODE_HEADER);
25103
- if (via !== undefined && answer !== undefined && typeof proxyCode === "string") {
25104
- own = this.#proxyRefusal(request, via, answer, proxyCode, state, event);
25596
+ if (answer?.proxy !== undefined) {
25597
+ own = via === undefined ? this.#airlockAnswer(answer, answer.proxy) : this.#proxyRefusal(request, via, answer.response.status, answer.proxy.code, answer.text, state, event);
25598
+ } else if (via !== undefined && failure instanceof AirlockTunnelRefusedError) {
25599
+ own = this.#proxyRefusal(request, via, failure.status, failure.proxyCode ?? failure.code, "", state, event);
25105
25600
  } else if (via !== undefined && failure instanceof DispatchUnreachableError) {
25106
25601
  own = this.#proxyUnreachable(via, failure, state);
25107
25602
  } else if (answer?.response.ok === true) {
25603
+ if (!answer.echoed || !rowStores(write.row)) {
25604
+ return this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
25605
+ }
25108
25606
  const { status } = answer.response;
25109
- 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`);
25607
+ 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`);
25110
25608
  } else if (answer !== undefined) {
25111
25609
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
25112
25610
  }
@@ -25114,7 +25612,7 @@ class DispatchClient {
25114
25612
  return own;
25115
25613
  const last = own instanceof Error ? own : new Error(String(own));
25116
25614
  let unanswered;
25117
- if (answer === undefined) {
25615
+ if (answer === undefined || answer.proxy !== undefined) {
25118
25616
  switch (event) {
25119
25617
  case "silence":
25120
25618
  unanswered = `${request} ${last.message}`;
@@ -25144,14 +25642,21 @@ class DispatchClient {
25144
25642
  const again = state === "nothing-sent" ? " The review can be sent again once the broker answers." : "";
25145
25643
  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);
25146
25644
  }
25147
- #proxyRefusal(request, via, answer, code, state, event) {
25148
- const { status } = answer.response;
25149
- const said = excerpt(answer.text, this.#sent.with(this.token));
25645
+ #proxyRefusal(request, via, status, code, text, state, event) {
25646
+ const said = excerpt(text, this.#sent.with(this.token));
25150
25647
  const by = `${request} was answered ${status} ${code} by Cipher's proxy at ${originOf(via.init.proxy)}${said === "" ? "" : ` (${JSON.stringify(said)})`}`;
25151
25648
  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.`;
25152
25649
  return new DispatchProxyRefusalError(code, status, message);
25153
25650
  }
25651
+ #airlockAnswer(answer, proxy) {
25652
+ const body = excerpt(answer.text, this.#sent.with(this.token));
25653
+ const { status } = answer.response;
25654
+ return proxy.left ? new AirlockOutcomeUnknownError(status, proxy.code, body) : new AirlockRefusedError(status, proxy.code, body);
25655
+ }
25154
25656
  #url(path, query) {
25657
+ if (path.some((segment) => pathNamesNothingPattern.test(segment))) {
25658
+ throw new DispatchEmptyPathError(path);
25659
+ }
25155
25660
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
25156
25661
  if (query) {
25157
25662
  for (const [name, value] of Object.entries(query)) {
@@ -25181,7 +25686,7 @@ class DispatchClient {
25181
25686
  throw new DispatchServiceError(refusal.code ?? `HTTP_${response.status}`, response.status, refusal.error, {
25182
25687
  ...refusal,
25183
25688
  textRefusal: response.headers.has(TEXT_REFUSAL_HEADER)
25184
- });
25689
+ }, retryAfterMs(response.headers) || null);
25185
25690
  }
25186
25691
  throw this.#gatewayError(method, url, response, text, "Dispatch's error JSON");
25187
25692
  }
@@ -25201,7 +25706,7 @@ class DispatchClient {
25201
25706
  return error;
25202
25707
  }
25203
25708
  }
25204
- #gatewayError(method, url, response, text, notWhat) {
25709
+ #gatewayError(method, url, response, text, notWhat, caller = {}) {
25205
25710
  const tokens = this.#sent.with(this.token);
25206
25711
  const body = bodyForText(text, tokens, notWhat);
25207
25712
  const reasonPhrase = excerpt(response.statusText, tokens);
@@ -25209,7 +25714,7 @@ class DispatchClient {
25209
25714
  const target = redirectOrigin(response, url, tokens);
25210
25715
  const redirected = target === undefined ? "" : ` (a redirect to ${target}, which this client does not follow)`;
25211
25716
  const request = `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`;
25212
- return new DispatchGatewayError(response.status, `${request} answered ${response.status}${reason}${redirected} with ${body}, ${GATEWAY_PAGE}`, gatewayAdvice(method, response.status));
25717
+ return new DispatchGatewayError(response.status, `${request} answered ${response.status}${reason}${redirected} with ${body}, ${caller.also ?? ""}${GATEWAY_PAGE}`, caller.advice ?? gatewayAdvice(method, response.status));
25213
25718
  }
25214
25719
  }
25215
25720
 
@@ -28050,6 +28555,40 @@ function notMadeLine(reason, context, searchQuery) {
28050
28555
  return `No related-item check was made: ${reason}. Search before you rely on this being new: dispatch search --project ${context.project}${query}`;
28051
28556
  }
28052
28557
 
28558
+ // ../envoy-client/src/runner-log.ts
28559
+ var ESCAPED = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/gu;
28560
+ var JSON_ESCAPED = /[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;
28561
+ var SHORT_ESCAPES = {
28562
+ "\x07": "\\a",
28563
+ "\b": "\\b",
28564
+ "\f": "\\f",
28565
+ "\n": "\\n",
28566
+ "\r": "\\r",
28567
+ "\t": "\\t",
28568
+ "\v": "\\v"
28569
+ };
28570
+ function hex3(value, digits) {
28571
+ return value.toString(16).padStart(digits, "0");
28572
+ }
28573
+ function goEscape(character) {
28574
+ const short = SHORT_ESCAPES[character];
28575
+ if (short !== undefined)
28576
+ return short;
28577
+ const point = character.codePointAt(0) ?? 0;
28578
+ if (point < 32 || point === 127)
28579
+ return `\\x${hex3(point, 2)}`;
28580
+ return point > 65535 ? `\\U${hex3(point, 8)}` : `\\u${hex3(point, 4)}`;
28581
+ }
28582
+ function printable(text) {
28583
+ return text.replace(ESCAPED, goEscape).replaceAll("##[", "##\\x5b");
28584
+ }
28585
+ function printableLine(text) {
28586
+ return printable(text).replace(/^(\s*):(?=:)/u, "$1\\x3a");
28587
+ }
28588
+ function printableJson(json) {
28589
+ return json.replace(JSON_ESCAPED, (character) => Array.from({ length: character.length }, (_, unit) => `\\u${hex3(character.charCodeAt(unit), 4)}`).join("")).replaceAll("##[", "##\\u005b");
28590
+ }
28591
+
28053
28592
  // ../envoy-client/src/dispatch-commands/advice.ts
28054
28593
  var triageAdviceShown = new Set;
28055
28594
  function adviceMemory() {
@@ -28160,6 +28699,31 @@ async function otherAdviceLines(render) {
28160
28699
  }
28161
28700
  }
28162
28701
 
28702
+ // ../envoy-client/src/dispatch-commands/observed-text.ts
28703
+ function lengthOfFirst(text, count) {
28704
+ let at = 0;
28705
+ for (let seen = 0;seen < count && at < text.length; seen += 1) {
28706
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
28707
+ }
28708
+ return at < text.length ? at : undefined;
28709
+ }
28710
+ function startOfLast(text, count) {
28711
+ let at = text.length;
28712
+ for (let seen = 0;seen < count && at > 0; seen += 1) {
28713
+ const low = text.charCodeAt(at - 1);
28714
+ const high = at > 1 ? text.charCodeAt(at - 2) : 0;
28715
+ at -= low >= 56320 && low <= 57343 && high >= 55296 && high <= 56319 ? 2 : 1;
28716
+ }
28717
+ return at;
28718
+ }
28719
+ function observedAsKept(observed) {
28720
+ const text = observed.replaceAll("\x00", "\uFFFD");
28721
+ if (lengthOfFirst(text, SPEC_CHECK_OBSERVED_MAX) === undefined)
28722
+ return text;
28723
+ const start = text.slice(0, lengthOfFirst(text, SPEC_CHECK_OBSERVED_START));
28724
+ return `${start}${SPEC_CHECK_OBSERVED_CUT_NOTE}${text.slice(startOfLast(text, SPEC_CHECK_OBSERVED_END))}`;
28725
+ }
28726
+
28163
28727
  // ../envoy-client/src/dispatch-commands/render-graph.ts
28164
28728
  function referenceLines(read) {
28165
28729
  if (typeof read === "string")
@@ -29435,11 +29999,54 @@ async function issuesCommand(context) {
29435
29999
  };
29436
30000
  }
29437
30001
  function dryRunAsksDispatch(tool, args) {
29438
- const { retract } = args;
29439
- return tool === "dispatch_result" && retract === undefined;
30002
+ const { retract, project } = args;
30003
+ return tool === "dispatch_result" && retract === undefined && project === undefined;
30004
+ }
30005
+ async function specCheckResultCommand(client, args) {
30006
+ const project = stringArg(args, "project");
30007
+ const observed = optionalString(args, "observed");
30008
+ const stored = await client.recordSpecCheckResult(project, {
30009
+ commit: stringArg(args, "commit"),
30010
+ check: stringArg(args, "check"),
30011
+ verdict: stringArg(args, "verdict"),
30012
+ ...observed === undefined ? {} : { observed: observedAsKept(observed) }
30013
+ });
30014
+ const { predicate } = stored.attestation;
30015
+ return {
30016
+ text: JSON.stringify(stored, null, 2),
30017
+ details: {
30018
+ project,
30019
+ result: stored.id,
30020
+ seq: stored.seq,
30021
+ check: predicate.check,
30022
+ verdict: predicate.verdict
30023
+ }
30024
+ };
30025
+ }
30026
+ function specCheckResultLine(result) {
30027
+ const { predicate, subject } = result.attestation;
30028
+ const leg = predicate.leg === "" ? "no leg" : `leg ${printable(predicate.leg)}`;
30029
+ const commit = subject?.[0]?.digest?.["gitCommit"] ?? "an unnamed commit";
30030
+ 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)}.`;
30031
+ }
30032
+ async function specCheckResultsCommand(client, args) {
30033
+ const project = stringArg(args, "project");
30034
+ const commit = stringArg(args, "commit");
30035
+ const check = optionalString(args, "check");
30036
+ const results = (await client.specCheckResults(project, commit, check)).results ?? [];
30037
+ const what = check === undefined ? project : `check ${printable(check)} of ${project}`;
30038
+ const text = optionalBoolean(args, "json") === true ? printableJson(JSON.stringify(results, null, 2)) : results.length === 0 ? `No result of ${what} is stored at ${printable(commit)}.` : [
30039
+ `Results of ${what} at ${printable(commit)}, newest first:`,
30040
+ ...results.map(specCheckResultLine)
30041
+ ].join(`
30042
+ `);
30043
+ return { text, details: { project, commit, results: results.length } };
29440
30044
  }
29441
30045
  async function resultCommand(context) {
29442
30046
  const { args, client, actor } = context;
30047
+ if (optionalString(args, "project") !== undefined) {
30048
+ return await specCheckResultCommand(client, args);
30049
+ }
29443
30050
  const retract = optionalString(args, "retract");
29444
30051
  if (retract !== undefined) {
29445
30052
  const retraction = await client.retractResult(retract, {
@@ -29511,6 +30118,9 @@ ${recorded.line}`,
29511
30118
  }
29512
30119
  async function resultsCommand(context) {
29513
30120
  const { args, client } = context;
30121
+ if (optionalString(args, "project") !== undefined) {
30122
+ return await specCheckResultsCommand(client, args);
30123
+ }
29514
30124
  const issue = stringArg(args, "issue");
29515
30125
  const at = optionalString(args, "at");
29516
30126
  const brief = optionalBoolean(args, "brief") === true;
@@ -29949,6 +30559,7 @@ var WRITE_ROUTES = [
29949
30559
  { method: "POST", pattern: "/api/v1/issues/{key}/results", commands: ["result"] },
29950
30560
  { method: "POST", pattern: "/api/v1/issues/{key}/results/dry-run", commands: ["result"] },
29951
30561
  { method: "POST", pattern: "/api/v1/results/{id}/retract", commands: ["result"] },
30562
+ { method: "POST", pattern: "/api/v1/projects/{key}/results", commands: ["result"] },
29952
30563
  { method: "POST", pattern: "/api/v1/deploys", commands: ["deploy"] },
29953
30564
  { method: "POST", pattern: "/api/v1/issues/{key}/handoffs/{phase}", commands: ["handoff-write"] },
29954
30565
  { method: "POST", pattern: "/api/v1/issues/{key}/artifacts", commands: ["artifact"] },
@@ -31475,7 +32086,7 @@ async function askRoundTrip(client, route, ask) {
31475
32086
  }
31476
32087
  return {
31477
32088
  kind: "unanswered",
31478
- failure: error instanceof DispatchAnswerNotKeptError ? `${route} wrote nothing, and Dispatch kept no copy of its answer (${error.code})` : `${route} failed with ${messageFor(error)}`,
32089
+ 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(/\.$/, "")}`,
31479
32090
  error,
31480
32091
  routeAbsent
31481
32092
  };
@@ -36570,7 +37181,7 @@ function deviceLoginBroker(brokerUrl) {
36570
37181
  function loginDpopKey(key) {
36571
37182
  return dpopKeyOf(key, "this machine's device login key");
36572
37183
  }
36573
- function printable(value, what, endpoint) {
37184
+ function printable2(value, what, endpoint) {
36574
37185
  if (UNPRINTABLE.test(value)) {
36575
37186
  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`);
36576
37187
  }
@@ -36580,7 +37191,7 @@ function page(uri, endpoint) {
36580
37191
  if (!isHttpUrl(uri)) {
36581
37192
  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`);
36582
37193
  }
36583
- return printable(uri, "page to type the code in", endpoint);
37194
+ return printable2(uri, "page to type the code in", endpoint);
36584
37195
  }
36585
37196
  async function withDeviceLoginLock(path, work, options = {}) {
36586
37197
  await deviceLoginDirectory(path);
@@ -36612,7 +37223,7 @@ function loginOf(key, broker, answered, now) {
36612
37223
  const accessExpiresAt = new Date(now + accessSeconds * 1000);
36613
37224
  return {
36614
37225
  key,
36615
- credentialId: printable(credentialId, "credential_id", endpoint),
37226
+ credentialId: printable2(credentialId, "credential_id", endpoint),
36616
37227
  refreshToken: holdSecret(refreshToken, expiresAt),
36617
37228
  expiresAt,
36618
37229
  broker,
@@ -36662,7 +37273,7 @@ async function startDeviceLogin(options) {
36662
37273
  return {
36663
37274
  brokerUrl,
36664
37275
  person,
36665
- userCode: printable(answered.user_code, "user code", endpoint),
37276
+ userCode: printable2(answered.user_code, "user code", endpoint),
36666
37277
  verificationUri: page(answered.verification_uri, endpoint),
36667
37278
  verificationUriComplete: answered.verification_uri_complete === undefined ? undefined : page(answered.verification_uri_complete, endpoint),
36668
37279
  expiresAt,
@@ -37395,6 +38006,16 @@ async function brokerTokenClient(env, own = "", read) {
37395
38006
  return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
37396
38007
  }
37397
38008
 
38009
+ // ../envoy-client/src/airlock-credential.ts
38010
+ var AIRLOCK_RESULTS_VAR = "DISPATCH_RESULTS_TOKEN";
38011
+ function airlockCredential(placeholder) {
38012
+ return {
38013
+ scheme: "DPoP",
38014
+ headers: () => ({ Authorization: `DPoP ${placeholder}` }),
38015
+ secret: () => placeholder
38016
+ };
38017
+ }
38018
+
37398
38019
  // ../envoy-client/src/broker-credential.ts
37399
38020
  function sessionName(naming) {
37400
38021
  if (naming === undefined)
@@ -37700,6 +38321,26 @@ async function dispatchUrl(env, config) {
37700
38321
  const target = await dispatchTarget(env, config);
37701
38322
  return target.enabled ? target.url : undefined;
37702
38323
  }
38324
+ function ownIdentityDispatch(env) {
38325
+ const url = nonEmpty(env.DISPATCH_URL);
38326
+ if (url === undefined) {
38327
+ return offWithError("DISPATCH_URL is not set: a CI job's write reads Dispatch's server from it alone");
38328
+ }
38329
+ if (httpUrl2(url) === undefined)
38330
+ return offWithError("DISPATCH_URL must be an http or https URL");
38331
+ const placeholder = nonEmpty(env[AIRLOCK_RESULTS_VAR]);
38332
+ if (placeholder === undefined) {
38333
+ 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`);
38334
+ }
38335
+ if (!sendable(placeholder)) {
38336
+ 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`);
38337
+ }
38338
+ return {
38339
+ enabled: true,
38340
+ url: withoutTrailingSlashes(url),
38341
+ credential: airlockCredential(placeholder)
38342
+ };
38343
+ }
37703
38344
  var BESIDE_TOKEN_FILES = [
37704
38345
  "DISPATCH_TOKEN_BROKER",
37705
38346
  "DISPATCH_TOKEN_BROKER_READ",