@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.
package/dist/dispatch.js CHANGED
@@ -14490,6 +14490,12 @@ var IDEMPOTENCY_KEY_REUSED = "KEY_REUSED";
14490
14490
  var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
14491
14491
  var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
14492
14492
  var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
14493
+ var SPEC_CHECK_OBSERVED_MAX = 2000;
14494
+ var SPEC_CHECK_OBSERVED_CUT_NOTE = `
14495
+ [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.]
14496
+ `;
14497
+ var SPEC_CHECK_OBSERVED_START = 500;
14498
+ var SPEC_CHECK_OBSERVED_END = SPEC_CHECK_OBSERVED_MAX - SPEC_CHECK_OBSERVED_START - [...SPEC_CHECK_OBSERVED_CUT_NOTE].length;
14493
14499
  function retriesUnderKey(status, code) {
14494
14500
  return outage(status) || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
14495
14501
  }
@@ -15091,8 +15097,16 @@ var RESULT_RECORD_FIELDS = [
15091
15097
  "excluded",
15092
15098
  "screenshots"
15093
15099
  ];
15100
+ var RESULT_PROJECT_FIELDS = ["check", "verdict", "commit", "observed"];
15101
+ var RESULT_PROJECT_REQUIRED = ["check", "verdict", "commit"];
15094
15102
  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.";
15095
- 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.";
15103
+ 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.";
15104
+ var RESULT_NOT_PROJECT_FIELDS = [
15105
+ ...RESULT_RECORD_FIELDS.filter((field) => !RESULT_PROJECT_FIELDS.includes(field)),
15106
+ "retract",
15107
+ "reason"
15108
+ ];
15109
+ 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;
15096
15110
  var DEPLOY_REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
15097
15111
  var DEPLOY_PROGRAM = /^[a-z0-9-]{1,64}$/;
15098
15112
  var DEPLOY_COMMIT = /^[0-9a-f]{40}$/;
@@ -15128,6 +15142,20 @@ function deployProblem(value) {
15128
15142
  }
15129
15143
  function resultProblem(value) {
15130
15144
  const input = value;
15145
+ if (input["project"] !== undefined) {
15146
+ const others = RESULT_NOT_PROJECT_FIELDS.filter((field) => input[field] !== undefined);
15147
+ if (others.length > 0) {
15148
+ return `${RESULT_PROJECT_RULE} This call also carries ${others.join(", ")}.`;
15149
+ }
15150
+ const missing = RESULT_PROJECT_REQUIRED.filter((field) => input[field] === undefined);
15151
+ if (missing.length > 0) {
15152
+ return `a CI job's result needs ${missing.join(", ")}. ${RESULT_PROJECT_RULE}`;
15153
+ }
15154
+ return;
15155
+ }
15156
+ if (input["verdict"] === "could_not_run") {
15157
+ return "verdict could_not_run goes with project alone: a role's result of a check of a Verification document is pass or fail.";
15158
+ }
15131
15159
  const carried = RESULT_RECORD_FIELDS.filter((field) => input[field] !== undefined);
15132
15160
  if (typeof input.retract === "string") {
15133
15161
  const reason = input.reason;
@@ -15148,6 +15176,25 @@ function resultProblem(value) {
15148
15176
  }
15149
15177
  return;
15150
15178
  }
15179
+ 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.";
15180
+ function resultsProblem(value) {
15181
+ const input = value;
15182
+ if (input["issue"] === undefined === (input["project"] === undefined)) {
15183
+ return RESULTS_OWNER_RULE;
15184
+ }
15185
+ if (input["project"] !== undefined) {
15186
+ const issueOnly = ["at", "brief"].filter((field) => input[field] !== undefined);
15187
+ if (issueOnly.length > 0) {
15188
+ return `With project, the read takes commit, check and json alone, and this call also carries ${issueOnly.join(", ")}.`;
15189
+ }
15190
+ if (input["commit"] === undefined) {
15191
+ return "With project, the read needs commit, the 40-character lowercase hex commit whose results it prints.";
15192
+ }
15193
+ return;
15194
+ }
15195
+ const projectOnly = ["commit", "check", "json"].filter((field) => input[field] !== undefined);
15196
+ return projectOnly.length === 0 ? undefined : `With issue, the read takes at and brief alone, and this call also carries ${projectOnly.join(", ")}.`;
15197
+ }
15151
15198
  var SEARCH_QUERY_MAX = 1000;
15152
15199
  var SEARCH_QUERY_HINT = "search with a short phrase of a few words, not a passage";
15153
15200
  var SEARCH_KIND_DEPTH = 100;
@@ -15603,12 +15650,13 @@ var dispatchToolSpecs = [
15603
15650
  verdict: "pass",
15604
15651
  commit: "1111111111111111111111111111111111111111"
15605
15652
  },
15606
- 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,
15653
+ 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,
15607
15654
  arguments: (z) => ({
15608
15655
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
15609
- 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(),
15656
+ 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(),
15657
+ 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(),
15610
15658
  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(),
15611
- verdict: z.enum(["pass", "fail"]).describe("Whether the check passed.").optional(),
15659
+ 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(),
15612
15660
  commit: z.string().describe("The 40-character lowercase hex commit the check ran at.").optional(),
15613
15661
  surface: z.string().describe("Where a person reaches the change.").optional(),
15614
15662
  run: z.string().describe("The command that proved it.").optional(),
@@ -15666,13 +15714,21 @@ var dispatchToolSpecs = [
15666
15714
  {
15667
15715
  name: "dispatch_results",
15668
15716
  example: { issue: "DSP-1" },
15669
- 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,
15717
+ 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,
15670
15718
  arguments: (z) => ({
15671
- issue: z.string().describe(ISSUE_REFERENCE),
15719
+ issue: z.string().describe(ISSUE_REFERENCE).optional(),
15720
+ 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(),
15721
+ commit: z.string().describe("With project: the 40-character lowercase hex commit whose results the read prints.").optional(),
15722
+ check: z.string().describe("With project: the id of one check of the spec files, whose results alone the read prints.").optional(),
15672
15723
  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(),
15673
15724
  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(),
15674
- json: z.boolean().describe("Print the complete results wire answer as JSON.").optional()
15675
- })
15725
+ json: z.boolean().describe("Print the complete results wire answer as JSON; with project, the stored results, one in-toto statement each.").optional()
15726
+ }),
15727
+ validation: {
15728
+ check: (value) => resultsProblem(value) === undefined,
15729
+ message: RESULTS_OWNER_RULE,
15730
+ refusal: (value) => resultsProblem(value) ?? RESULTS_OWNER_RULE
15731
+ }
15676
15732
  },
15677
15733
  {
15678
15734
  name: "dispatch_artifact",
@@ -21096,6 +21152,18 @@ function parseProxyArgv(rest, cwd) {
21096
21152
  return { kind: "run", socket: path, dryRun, command };
21097
21153
  }
21098
21154
 
21155
+ // ../envoy-client/src/go-space.ts
21156
+ var GO_SPACE = goSpaceClass();
21157
+ function goSpaceClass() {
21158
+ const set = /^\^\[(.+)\]\*\$$/u.exec(goBlankPattern.source)?.[1];
21159
+ if (set === undefined) {
21160
+ throw new Error(`goBlankPattern (@legion/contracts/go-blank) is no longer one character class: ${goBlankPattern.source}`);
21161
+ }
21162
+ return set;
21163
+ }
21164
+ var goSpaceAtEnds = new RegExp(`^[${GO_SPACE}]+|[${GO_SPACE}]+$`, "gu");
21165
+ var pathNamesNothingPattern = new RegExp(`^[${GO_SPACE}]*[./]*[${GO_SPACE}]*$`, "u");
21166
+
21099
21167
  // ../envoy-client/src/dispatch-command.ts
21100
21168
  var COMMANDS_OUTSIDE_THE_SPECS = [
21101
21169
  { name: PROXY_COMMAND, sentence: PROXY_SENTENCE, help: proxyHelp },
@@ -21555,6 +21623,28 @@ function parseCommand(argv, io) {
21555
21623
  }
21556
21624
  }
21557
21625
  }
21626
+ for (const { field, noun, tools, path } of IDENTIFIER_FIELDS) {
21627
+ const given = args[field];
21628
+ if (tools !== undefined && !tools.includes(tool))
21629
+ continue;
21630
+ const flag = setBy.get(field);
21631
+ for (const value of Array.isArray(given) ? given : [given]) {
21632
+ if (typeof value !== "string")
21633
+ continue;
21634
+ let problem;
21635
+ if (value === "") {
21636
+ problem = `${flag} is empty, so the call names no ${noun}: a variable that gives it may be empty or unset`;
21637
+ } else if (goBlankPattern.test(value)) {
21638
+ problem = `${flag} is only white space, so the call names no ${noun}`;
21639
+ } else if (path === true && pathNamesNothingPattern.test(value)) {
21640
+ problem = `${flag} is "${value.replace(goSpaceAtEnds, "")}", only dots and slashes, so the call names no ${noun}`;
21641
+ }
21642
+ if (problem === undefined)
21643
+ continue;
21644
+ problems.push(problem);
21645
+ break;
21646
+ }
21647
+ }
21558
21648
  if (help)
21559
21649
  return { kind: "help", tool };
21560
21650
  if (problems.length > 0) {
@@ -21579,6 +21669,18 @@ function appendedItem(kind, flag, value, number) {
21579
21669
  return parsed === undefined ? undefined : { value: parsed };
21580
21670
  }
21581
21671
  var ISSUE_KEY2 = /^[A-Z][A-Z0-9]*-\d+$/;
21672
+ var IDENTIFIER_FIELDS = [
21673
+ { field: "issue", noun: "issue", path: true },
21674
+ { field: "project", noun: "project", path: true },
21675
+ { field: "artifact", noun: "document", path: true },
21676
+ { field: "check", noun: "check" },
21677
+ { field: "commit", noun: "commit" },
21678
+ { field: "at", noun: "commit" },
21679
+ { field: "retract", noun: "result", path: true },
21680
+ { field: "comment", noun: "comment", path: true },
21681
+ { field: "session", noun: "session", path: true },
21682
+ { field: "parent", noun: "parent", tools: ["dispatch_issues", "dispatch_issue"] }
21683
+ ];
21582
21684
  function quoteWord(value) {
21583
21685
  return BARE_WORD.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
21584
21686
  }
@@ -21949,7 +22051,7 @@ var POLICY_REFUSAL_PATTERNS = [
21949
22051
  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),
21950
22052
  policy("sessionInvalid", "the registration of %s names a session of %d bytes; %s", K8S_ACCOUNT, NUMBER, SESSION_RULE),
21951
22053
  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),
21952
- policy("claimMissing", "the subject token's workflow_ref is not <owner>/<name>/<path>@<ref> under its repository %s", REPOSITORY),
22054
+ 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),
21953
22055
  policy("noEntry", "no entry lists the workflow %s of %s on %s", WORKFLOW_PATH, REPOSITORY, GIT_REF),
21954
22056
  policy("claimMissing", "the subject token carries no email claim, so it names no account (ask for it with format=full)"),
21955
22057
  policy("noEntry", "no entry lists the Google account %s", EMAIL),
@@ -22901,6 +23003,275 @@ async function fileBearer(bearer, url, section, env, commands = "run") {
22901
23003
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
22902
23004
  }
22903
23005
 
23006
+ // ../envoy-client/src/dispatch-write-rows.ts
23007
+ var components = looseObject({
23008
+ mode: string2(),
23009
+ ids: array(string2()).nullish(),
23010
+ reason: string2().nullish()
23011
+ });
23012
+ var advice = looseObject({
23013
+ decision_blocks: number2().int().optional(),
23014
+ issue_status: string2().optional(),
23015
+ legion_managed_status: boolean2().optional(),
23016
+ session_writes_since_human: number2().int().optional(),
23017
+ your_open_asks: array(looseObject({ id: string2(), question: string2() })).nullable().optional(),
23018
+ unparsed_openers: looseObject({ count: number2().int(), examples: array(string2()).nullable() }).optional(),
23019
+ moved_approval_request: looseObject({
23020
+ ask_id: string2(),
23021
+ issue: string2().optional(),
23022
+ project: string2().optional(),
23023
+ documents: array(looseObject({
23024
+ artifact_id: string2(),
23025
+ name: string2(),
23026
+ primary: boolean2(),
23027
+ role: string2().optional(),
23028
+ requested_version: number2().int(),
23029
+ version: number2().int()
23030
+ })).nullable()
23031
+ }).optional(),
23032
+ superseded_approval: looseObject({
23033
+ version: number2().int(),
23034
+ approved_version: number2().int(),
23035
+ approved_by: string2(),
23036
+ design_gates: array(looseObject({ issue: string2(), step: string2() })).optional()
23037
+ }).optional()
23038
+ }).optional();
23039
+ var caughtAdvice = unknown().optional();
23040
+ var ask = {
23041
+ id: askFields.id,
23042
+ issue_key: askFields.issue_key,
23043
+ artifact_id: askFields.artifact_id
23044
+ };
23045
+ var askWrite = looseObject({
23046
+ ...ask,
23047
+ question: askFields.question,
23048
+ urgency: string2(),
23049
+ waiting_on_person: string2().optional(),
23050
+ advice: caughtAdvice
23051
+ });
23052
+ var documentComment = {
23053
+ id: commentFields.id,
23054
+ ask_waiting_on: string2().optional(),
23055
+ advice
23056
+ };
23057
+ var suggestion = looseObject({ id: commentFields.id });
23058
+ var {
23059
+ repo: repo2,
23060
+ branch,
23061
+ last_error,
23062
+ last_commit,
23063
+ last_sync_at,
23064
+ components: sourceComponents
23065
+ } = ArchitectureSourceSchema.unwrap().shape;
23066
+ var architectureSource = looseObject({
23067
+ repo: repo2,
23068
+ branch,
23069
+ last_error,
23070
+ last_commit,
23071
+ last_sync_at,
23072
+ components: sourceComponents
23073
+ });
23074
+ var pictureUpload = {
23075
+ artifact: looseObject({ slug: artifactFields.slug }),
23076
+ version: looseObject({ number: versionFields.number })
23077
+ };
23078
+ var uploadedDocument = {
23079
+ id: artifactFields.id,
23080
+ slug: artifactFields.slug,
23081
+ name: artifactFields.name,
23082
+ primary: artifactFields.primary.optional(),
23083
+ role: string2().optional(),
23084
+ issue_key: artifactFields.issue_key.optional()
23085
+ };
23086
+ var actor = InboundActorSchema;
23087
+ var STORE_NOTHING = new WeakSet;
23088
+ function storesNothing(row) {
23089
+ STORE_NOTHING.add(row);
23090
+ return row;
23091
+ }
23092
+ function rowStores(row) {
23093
+ return !STORE_NOTHING.has(row);
23094
+ }
23095
+ var advance = looseObject(issueFields.advances.unwrap().unwrap().element.unwrap().shape);
23096
+ var externalLink = looseObject(ExternalLinkSchema.unwrap().shape);
23097
+ var updatedIssue = looseObject({
23098
+ key: issueFields.key,
23099
+ status: issueFields.status,
23100
+ title: issueFields.title.optional(),
23101
+ priority: issueFields.priority.optional(),
23102
+ assignee: issueFields.assignee.optional(),
23103
+ route: issueFields.route.optional(),
23104
+ parent: issueFields.parent.optional(),
23105
+ components: components.optional(),
23106
+ repo: issueFields.repo.optional(),
23107
+ resolved_repo: issueFields.resolved_repo.optional(),
23108
+ labels: issueFields.labels.nullish(),
23109
+ blocked_by: issueFields.blocked_by.nullish(),
23110
+ advances: array(advance).nullable().optional(),
23111
+ external_links: array(externalLink).nullish(),
23112
+ advice
23113
+ });
23114
+ var WRITE_ROWS = {
23115
+ issue: looseObject({
23116
+ key: issueFields.key,
23117
+ title: issueFields.title,
23118
+ project: issueFields.project,
23119
+ assignee: issueFields.assignee.optional(),
23120
+ repo: issueFields.repo.optional(),
23121
+ advice: caughtAdvice
23122
+ }),
23123
+ markdownRoundTrip: storesNothing(looseObject({ markdown: string2() })),
23124
+ fileRoundTrip: storesNothing(looseObject({ markdown: string2() })),
23125
+ related: storesNothing(looseObject({ outcome: string2() })),
23126
+ updateIssue: updatedIssue,
23127
+ updateIssueComponents: updatedIssue.extend({ components }),
23128
+ claimIssue: looseObject({
23129
+ status: issueFields.status,
23130
+ claim: looseObject({ at: string2() }).nullable(),
23131
+ legion_managed_status: boolean2().optional()
23132
+ }),
23133
+ changeIssueStatus: looseObject({
23134
+ changed: array(looseObject({
23135
+ key: issueFields.key,
23136
+ status: issueFields.status,
23137
+ parent: string2().nullable()
23138
+ })).nullable(),
23139
+ issue: looseObject({
23140
+ status: issueFields.status,
23141
+ external_links: array(externalLink).nullish()
23142
+ })
23143
+ }),
23144
+ ask: askWrite,
23145
+ artifactAsk: askWrite,
23146
+ editAsk: looseObject({ ...ask, question: askFields.question }),
23147
+ resolveAsk: looseObject({
23148
+ ...ask,
23149
+ resolution: looseObject({ reason: string2() }).optional()
23150
+ }),
23151
+ createProject: looseObject({
23152
+ key: string2(),
23153
+ name: string2(),
23154
+ created_at: string2(),
23155
+ default_assignee: string2().optional()
23156
+ }),
23157
+ syncArchitectureSources: array(architectureSource),
23158
+ syncArchitectureSource: architectureSource,
23159
+ requestApproval: looseObject({
23160
+ version: number2().int(),
23161
+ coverage: array(string2()).nullish(),
23162
+ coverage_unread: boolean2().optional(),
23163
+ ask: looseObject({
23164
+ ...ask,
23165
+ question: askFields.question,
23166
+ waiting_on_person: string2().optional()
23167
+ }).nullable(),
23168
+ approval: looseObject({ by: looseObject({ id: string2() }).nullish() })
23169
+ }),
23170
+ planApprove: looseObject({ version: number2().int() }),
23171
+ recordDeploy: looseObject({
23172
+ deploy: looseObject({
23173
+ program: string2(),
23174
+ commit: string2(),
23175
+ deployed_at: string2(),
23176
+ source: string2(),
23177
+ url: string2(),
23178
+ recorded_by: actor
23179
+ })
23180
+ }),
23181
+ reviewArtifact: looseObject({
23182
+ version: number2().int(),
23183
+ state: string2(),
23184
+ ask_id: string2().nullable(),
23185
+ reason: string2().nullable(),
23186
+ actor
23187
+ }),
23188
+ recordResult: looseObject({
23189
+ line: string2(),
23190
+ result: looseObject({
23191
+ id: string2(),
23192
+ verdict: string2(),
23193
+ role: string2(),
23194
+ check_block_id: string2(),
23195
+ check_issue_key: string2(),
23196
+ commit_sha: string2()
23197
+ })
23198
+ }),
23199
+ dryRunResult: storesNothing(looseObject({ line: string2(), result: unknown() })),
23200
+ retractResult: looseObject({
23201
+ result_id: string2(),
23202
+ reason: string2(),
23203
+ created_at: string2(),
23204
+ actor
23205
+ }),
23206
+ recordSpecCheckResult: looseObject({
23207
+ id: string2(),
23208
+ seq: number2().int(),
23209
+ attestation: looseObject({
23210
+ predicate: looseObject({ check: string2(), verdict: string2() })
23211
+ })
23212
+ }),
23213
+ comment: looseObject({ ...documentComment, issue_key: commentFields.issue_key }),
23214
+ artifactComment: looseObject(documentComment),
23215
+ suggest: suggestion,
23216
+ artifactSuggest: suggestion,
23217
+ resolveComment: looseObject({
23218
+ id: commentFields.id,
23219
+ issue_key: commentFields.issue_key,
23220
+ artifact_id: commentFields.artifact_id
23221
+ }),
23222
+ editComment: looseObject({
23223
+ id: commentFields.id,
23224
+ issue_key: commentFields.issue_key,
23225
+ artifact_id: commentFields.artifact_id
23226
+ }),
23227
+ message: looseObject({ id: messageFields.id, advice }),
23228
+ editMessage: looseObject({ id: messageFields.id, issue_key: messageFields.issue_key }),
23229
+ agentMessage: looseObject({
23230
+ id: messageFields.id,
23231
+ deliveries: array(looseObject({ state: string2(), error: string2().nullish(), delivery: string2() })).nullish()
23232
+ }),
23233
+ messageReply: looseObject({
23234
+ id: messageFields.id,
23235
+ body: messageFields.body,
23236
+ in_reply_to: messageFields.in_reply_to.optional(),
23237
+ duplicate: boolean2().optional()
23238
+ }),
23239
+ deliveryReply: looseObject({}),
23240
+ acceptMessageDelivery: looseObject({
23241
+ message_id: string2(),
23242
+ body: string2(),
23243
+ delivery: string2()
23244
+ }),
23245
+ docEdit: looseObject({
23246
+ applied: number2().int(),
23247
+ version: looseObject({ number: versionFields.number }).nullable(),
23248
+ changed: boolean2().optional(),
23249
+ unchanged_ops: array(number2().int()).nullish(),
23250
+ lost_ops: array(number2().int()).nullish(),
23251
+ written: string2().optional(),
23252
+ token: string2().optional(),
23253
+ advice: caughtAdvice
23254
+ }),
23255
+ nameArtifactVersion: looseObject({}),
23256
+ writeHandoff: looseObject({
23257
+ id: string2(),
23258
+ issue_key: string2(),
23259
+ phase: string2(),
23260
+ version: number2().int()
23261
+ }),
23262
+ projectArtifact: looseObject({
23263
+ artifact: looseObject({ ...uploadedDocument, project: artifactFields.project }),
23264
+ version: pictureUpload.version,
23265
+ advice
23266
+ }),
23267
+ agentArtifact: looseObject(pictureUpload),
23268
+ artifact: looseObject({
23269
+ artifact: looseObject(uploadedDocument),
23270
+ version: pictureUpload.version,
23271
+ advice
23272
+ })
23273
+ };
23274
+
22904
23275
  // ../envoy-client/src/ask-answer.ts
22905
23276
  var HEAD_LENGTH = 120;
22906
23277
  function textHead(text, length = HEAD_LENGTH) {
@@ -23022,6 +23393,7 @@ class SentTokens {
23022
23393
  var landed = (action) => ({ state: "may-have-landed", action });
23023
23394
  var nothing = (action) => ({ state: "nothing-sent", action });
23024
23395
  var WRITE_TRANSITIONS = {
23396
+ "uncommitted-401": { "nothing-sent": landed("end"), "may-have-landed": landed("end") },
23025
23397
  applied: { "nothing-sent": nothing("settle"), "may-have-landed": landed("settle") },
23026
23398
  judged: { "nothing-sent": nothing("settle"), "may-have-landed": landed("settle") },
23027
23399
  unjudged: { "nothing-sent": nothing("end"), "may-have-landed": landed("end") },
@@ -23062,6 +23434,7 @@ var DISPATCH_URL_SETTING = "the configured Dispatch URL";
23062
23434
  class DispatchServiceError extends Error {
23063
23435
  code;
23064
23436
  status;
23437
+ retryAfterMs;
23065
23438
  name = "DispatchServiceError";
23066
23439
  fromDispatch = true;
23067
23440
  candidates;
@@ -23071,10 +23444,11 @@ class DispatchServiceError extends Error {
23071
23444
  changed;
23072
23445
  textRefusal;
23073
23446
  hint;
23074
- constructor(code, status, message, details = {}) {
23447
+ constructor(code, status, message, details = {}, retryAfterMs = null) {
23075
23448
  super(message);
23076
23449
  this.code = code;
23077
23450
  this.status = status;
23451
+ this.retryAfterMs = retryAfterMs;
23078
23452
  this.candidates = details.candidates;
23079
23453
  this.current = details.current;
23080
23454
  this.mismatches = details.mismatches;
@@ -23106,24 +23480,17 @@ class DispatchProxyRefusalError extends DispatchServiceError {
23106
23480
  fromDispatch = false;
23107
23481
  }
23108
23482
  var PROXY_CODE_FORM = /^[A-Z][A-Z0-9_]{0,63}$/;
23109
- function proxyTunnelAnswer(error) {
23110
- if (typeof error !== "object" || error === null)
23111
- return;
23112
- const { code, status, headers } = error;
23113
- if (code !== "ERR_PROXY_TUNNEL" || typeof status !== "number" || !(headers instanceof Headers)) {
23114
- return;
23115
- }
23116
- const proxyCode = headers.get(PROXY_CODE_HEADER) ?? "";
23117
- if (status < 400 || status > 599 || !PROXY_CODE_FORM.test(proxyCode))
23483
+ function proxyOwnAnswer(response) {
23484
+ const forwarded = response.headers.get(PROXY_FORWARDED_HEADER)?.trim().toLowerCase();
23485
+ const named = response.headers.get(PROXY_CODE_HEADER)?.trim() ?? "";
23486
+ if (forwarded !== "false" && forwarded !== "unknown" && named === "")
23118
23487
  return;
23119
- const forwarded = headers.get(PROXY_FORWARDED_HEADER);
23120
- return new Response(null, {
23121
- status,
23122
- headers: {
23123
- [PROXY_CODE_HEADER]: proxyCode,
23124
- ...forwarded === null ? {} : { [PROXY_FORWARDED_HEADER]: forwarded }
23125
- }
23126
- });
23488
+ return { code: named === "" ? `HTTP_${response.status}` : named, left: forwarded !== "false" };
23489
+ }
23490
+ function proxyEvent(status, left) {
23491
+ if (left)
23492
+ return "proxy-unsettled";
23493
+ return outage(status) ? "proxy-failed" : "proxy-refused";
23127
23494
  }
23128
23495
  var CREDENTIAL_ECHOED = "CREDENTIAL_ECHOED";
23129
23496
 
@@ -23144,6 +23511,8 @@ class DispatchWriteUnsettledError extends Error {
23144
23511
  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";
23145
23512
  if (last instanceof DispatchGatewayError) {
23146
23513
  answer = last.answer;
23514
+ if (last.status < 300)
23515
+ why = "the write may have reached Dispatch behind what answered it";
23147
23516
  } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
23148
23517
  answer = last.code;
23149
23518
  why = "Dispatch was still running an earlier attempt of the write";
@@ -23165,10 +23534,10 @@ class DispatchWriteLandedError extends Error {
23165
23534
  code;
23166
23535
  status;
23167
23536
  name = "DispatchWriteLandedError";
23168
- constructor(code, status, method, shownUrl) {
23537
+ constructor(code, status, method, shownUrl, options) {
23169
23538
  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";
23170
23539
  const request = `${method} ${shownUrl}`;
23171
- 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.");
23540
+ 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);
23172
23541
  this.code = code;
23173
23542
  this.status = status;
23174
23543
  }
@@ -23232,10 +23601,12 @@ class DispatchNoRouteError extends DispatchServiceError {
23232
23601
  class DispatchUnreachableError extends Error {
23233
23602
  reachedNothing;
23234
23603
  failure;
23604
+ code;
23235
23605
  constructor(message, reachedNothing, failure) {
23236
23606
  super(message);
23237
23607
  this.reachedNothing = reachedNothing;
23238
23608
  this.failure = failure;
23609
+ this.code = /^[A-Z][A-Z0-9_]*$/.test(failure) ? failure : undefined;
23239
23610
  }
23240
23611
  }
23241
23612
  function reviewNoRouteRefusal(baseUrl, route, version) {
@@ -23279,6 +23650,9 @@ function pauseFor(ms, signal) {
23279
23650
  signal.addEventListener("abort", stop, { once: true });
23280
23651
  return promise;
23281
23652
  }
23653
+ function keyEchoed(response, key) {
23654
+ return key !== "" && keyNamedBack(response) === key;
23655
+ }
23282
23656
  var STREAMED_BODY_MIN = 1 << 20;
23283
23657
  var STREAMED_BODY_CHUNK = 64 << 10;
23284
23658
  function attemptBody(body, headers, progress) {
@@ -23336,7 +23710,7 @@ function refusalIn(json) {
23336
23710
  };
23337
23711
  }
23338
23712
  var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
23339
- async function writeAnswer(response) {
23713
+ async function writeAnswer(response, echoed) {
23340
23714
  if (NULL_BODY_STATUSES.has(response.status)) {
23341
23715
  return {
23342
23716
  response,
@@ -23347,7 +23721,8 @@ async function writeAnswer(response) {
23347
23721
  code: undefined,
23348
23722
  error: undefined,
23349
23723
  replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
23350
- keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
23724
+ echoed,
23725
+ proxy: proxyOwnAnswer(response)
23351
23726
  };
23352
23727
  }
23353
23728
  const text = await response.text();
@@ -23363,25 +23738,23 @@ async function writeAnswer(response) {
23363
23738
  code: refusal?.code,
23364
23739
  error: refusal?.error,
23365
23740
  replayed: response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1",
23366
- keyEcho: response.headers.get(IDEMPOTENCY_KEY_HEADER) ?? undefined
23741
+ echoed,
23742
+ proxy: proxyOwnAnswer(response)
23367
23743
  };
23368
23744
  }
23369
23745
  function isStoredKeyStatus(status) {
23370
23746
  return status >= 400 && status < 500 && status !== 401 && !outage(status);
23371
23747
  }
23372
- function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
23748
+ function answerEvent(answer, canTellDeadToken) {
23373
23749
  const { status } = answer.response;
23374
- if (proxied && answer.response.headers.get(PROXY_CODE_HEADER) !== null) {
23375
- if (answer.response.headers.get(PROXY_FORWARDED_HEADER) !== "false")
23376
- return "proxy-unsettled";
23377
- return outage(status) ? "proxy-failed" : "proxy-refused";
23378
- }
23750
+ if (answer.proxy !== undefined)
23751
+ return proxyEvent(status, answer.proxy.left);
23379
23752
  if (status >= 200 && status < 300) {
23380
23753
  if (answer.notJson)
23381
23754
  return "foreign-2xx";
23382
23755
  if (answer.malformed)
23383
23756
  return "body-malformed";
23384
- return keyEchoed && answer.keyEcho !== requestKey ? "foreign-2xx" : "applied";
23757
+ return answer.echoed ? "applied" : "foreign-2xx";
23385
23758
  }
23386
23759
  if (status >= 300 && status < 400)
23387
23760
  return "redirect";
@@ -23391,15 +23764,21 @@ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken, proxied) {
23391
23764
  if (status === 404 && answer.code === "NOT_FOUND" && answer.error?.startsWith(NO_ROUTE_MESSAGE_PREFIX) === true) {
23392
23765
  return "no-route";
23393
23766
  }
23767
+ if (status === 401 && answer.echoed)
23768
+ return "uncommitted-401";
23769
+ if (tokenNotCheckedAnswer(status, answer.code))
23770
+ return "try-later";
23394
23771
  const textRefusal = answer.error !== undefined && answer.response.headers.has(TEXT_REFUSAL_HEADER);
23395
23772
  if (!textRefusal && retriesUnderKey(status, answer.code)) {
23396
23773
  if (status === 409)
23397
23774
  return "in-flight";
23398
23775
  return mayHaveReachedServer(status) ? "may-have-run" : "try-later";
23399
23776
  }
23777
+ if (!answer.echoed)
23778
+ return "unjudged";
23400
23779
  if (answer.replayed || answer.code === IDEMPOTENCY_KEY_COMMITTED)
23401
23780
  return "judged";
23402
- if (answer.keyEcho !== requestKey || !isStoredKeyStatus(status))
23781
+ if (!isStoredKeyStatus(status))
23403
23782
  return "unjudged";
23404
23783
  if (answer.code === IDEMPOTENCY_KEY_REUSED)
23405
23784
  return "judged";
@@ -23466,6 +23845,103 @@ function gatewayAdvice(method, status) {
23466
23845
  function gatewayClears(status) {
23467
23846
  return outage(status) || status >= 200 && status < 300;
23468
23847
  }
23848
+ var DISPATCH_ANSWER_LOST = "ANSWER_LOST";
23849
+
23850
+ class DispatchAnswerMissingError extends Error {
23851
+ status;
23852
+ name = "DispatchAnswerMissingError";
23853
+ code = DISPATCH_ANSWER_LOST;
23854
+ constructor(status, method, url, options) {
23855
+ 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);
23856
+ this.status = status;
23857
+ }
23858
+ }
23859
+
23860
+ class DispatchEmptyPathError extends Error {
23861
+ name = "DispatchEmptyPathError";
23862
+ constructor(path) {
23863
+ const route = path.map((segment) => segment === "" ? "{empty}" : pathNamesNothingPattern.test(segment) ? `{${JSON.stringify(segment)}}` : segment).join("/");
23864
+ 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`);
23865
+ }
23866
+ }
23867
+ var PROXY_TUNNEL_REFUSED = /: (\d{3}) ?(.*)$/;
23868
+
23869
+ class AirlockTunnelRefusedError extends Error {
23870
+ status;
23871
+ reason;
23872
+ proxyCode;
23873
+ name = "AirlockTunnelRefusedError";
23874
+ code = "AIRLOCK_TUNNEL_REFUSED";
23875
+ constructor(status, reason, proxyCode, options) {
23876
+ const said = status === 0 ? reason : `${status}${reason === "" ? "" : ` ${reason}`}`;
23877
+ super(`the airlock proxy refused the connection (${said}); nothing was sent to Dispatch`, options);
23878
+ this.status = status;
23879
+ this.reason = reason;
23880
+ this.proxyCode = proxyCode;
23881
+ }
23882
+ }
23883
+ function tunnelRefusal(error) {
23884
+ if (!(error instanceof Error) || Reflect.get(error, "code") !== "ERR_PROXY_TUNNEL") {
23885
+ return;
23886
+ }
23887
+ const headers = Reflect.get(error, "headers");
23888
+ const named = headers instanceof Headers ? headers.get(PROXY_CODE_HEADER)?.trim() ?? "" : "";
23889
+ const proxyCode = PROXY_CODE_FORM.test(named) ? named : undefined;
23890
+ const said = PROXY_TUNNEL_REFUSED.exec(error.message);
23891
+ return said === null ? new AirlockTunnelRefusedError(0, error.message, proxyCode, { cause: error }) : new AirlockTunnelRefusedError(Number(said[1]), said[2]?.trim() ?? "", proxyCode, {
23892
+ cause: error
23893
+ });
23894
+ }
23895
+
23896
+ class AirlockRefusedError extends Error {
23897
+ status;
23898
+ code;
23899
+ body;
23900
+ name = "AirlockRefusedError";
23901
+ constructor(status, code, body) {
23902
+ super(`the airlock proxy answered ${status} ${code} itself, and sent nothing on: ${body}`);
23903
+ this.status = status;
23904
+ this.code = code;
23905
+ this.body = body;
23906
+ }
23907
+ }
23908
+
23909
+ class AirlockOutcomeUnknownError extends Error {
23910
+ status;
23911
+ code;
23912
+ body;
23913
+ name = "AirlockOutcomeUnknownError";
23914
+ constructor(status, code, body) {
23915
+ super(`the airlock proxy answered ${status} ${code} itself after the write may have reached Dispatch: ${body}`);
23916
+ this.status = status;
23917
+ this.code = code;
23918
+ this.body = body;
23919
+ }
23920
+ }
23921
+ var TOKEN_NOT_CHECKED = {
23922
+ BROKER_TOKEN_RATE_LIMITED: 429,
23923
+ BROKER_UNAVAILABLE: 503
23924
+ };
23925
+ function tokenNotCheckedAnswer(status, code) {
23926
+ return code !== undefined && TOKEN_NOT_CHECKED[code] === status;
23927
+ }
23928
+ function tokenNotChecked(error) {
23929
+ return error instanceof DispatchServiceError && error.fromDispatch && tokenNotCheckedAnswer(error.status, error.code);
23930
+ }
23931
+ function writeOutcomeUnknown(error) {
23932
+ if (error instanceof DispatchWriteUnsettledError)
23933
+ return true;
23934
+ if (error instanceof DispatchGatewayError)
23935
+ return error.mayHaveReachedDispatch;
23936
+ if (error instanceof DispatchProxyRefusalError)
23937
+ return false;
23938
+ if (error instanceof DispatchServiceError)
23939
+ return error.status >= 500 && !tokenNotChecked(error);
23940
+ return false;
23941
+ }
23942
+ function keyNamedBack(response) {
23943
+ return (response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "").replace(/^"(.*)"$/, "$1");
23944
+ }
23469
23945
 
23470
23946
  class DispatchClient {
23471
23947
  fetchImpl;
@@ -23489,6 +23965,9 @@ class DispatchClient {
23489
23965
  try {
23490
23966
  return await fetchImpl(input, { ...init, redirect: "manual" });
23491
23967
  } catch (error) {
23968
+ const tunnel = tunnelRefusal(error);
23969
+ if (tunnel !== undefined)
23970
+ throw tunnel;
23492
23971
  if (error instanceof TypeError) {
23493
23972
  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));
23494
23973
  }
@@ -23507,7 +23986,7 @@ class DispatchClient {
23507
23986
  return this.#credential.secret();
23508
23987
  }
23509
23988
  async issue(input) {
23510
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "issues"], input);
23989
+ const answer = await this.#writeAnswer("POST", ["api", "v1", "issues"], WRITE_ROWS.issue, input);
23511
23990
  return { ...answer.payload, created: answer.status === 201 };
23512
23991
  }
23513
23992
  async resolveIssue(issueReference) {
@@ -23535,28 +24014,28 @@ class DispatchClient {
23535
24014
  async listIssueArtifacts(issue) {
23536
24015
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"]);
23537
24016
  }
23538
- async markdownRoundTrip(markdown, newDocument) {
23539
- return this.#roundTrip(["api", "v1", "markdown", "round-trip"], { markdown }, newDocument);
24017
+ async markdownRoundTrip(markdown, newDocument = false) {
24018
+ return this.#roundTrip(["api", "v1", "markdown", "round-trip"], WRITE_ROWS.markdownRoundTrip, { markdown }, newDocument);
23540
24019
  }
23541
- async fileRoundTrip(bytes, newDocument) {
24020
+ async fileRoundTrip(bytes, newDocument = false) {
23542
24021
  const file = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
23543
- return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], { file }, newDocument);
24022
+ return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], WRITE_ROWS.fileRoundTrip, { file }, newDocument);
23544
24023
  }
23545
- async#roundTrip(path, body, newDocument) {
23546
- const answer = await this.#writingNothing(path, newDocument ? { ...body, new_document: true } : body, { writes: false });
24024
+ async#roundTrip(path, row, body, newDocument) {
24025
+ const answer = await this.#writingNothing(path, row, newDocument ? { ...body, new_document: true } : body);
23547
24026
  return answer.markdown;
23548
24027
  }
23549
24028
  async listProjectArtifacts(project, unlinked = false) {
23550
24029
  return this.#json("GET", ["api", "v1", "projects", project, "artifacts"], undefined, unlinked ? { unlinked: "true" } : undefined);
23551
24030
  }
23552
24031
  async projectArtifact(project, input, key) {
23553
- return this.#upload(["api", "v1", "projects", project, "artifacts"], input, key);
24032
+ return this.#upload(["api", "v1", "projects", project, "artifacts"], input, WRITE_ROWS.projectArtifact, key);
23554
24033
  }
23555
24034
  async getProjectArtifact(project, slug) {
23556
24035
  return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug]);
23557
24036
  }
23558
24037
  async agentArtifact(sessionId, input) {
23559
- return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input);
24038
+ return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input, WRITE_ROWS.agentArtifact);
23560
24039
  }
23561
24040
  async getAgentArtifact(sessionId, slug) {
23562
24041
  return this.#json("GET", ["api", "v1", "agents", sessionId, "artifacts", slug]);
@@ -23577,24 +24056,24 @@ class DispatchClient {
23577
24056
  return this.#json("GET", path, undefined, request);
23578
24057
  }
23579
24058
  async related(project, input) {
23580
- return this.#writingNothing(["api", "v1", "projects", project, "related"], input);
24059
+ return this.#writingNothing(["api", "v1", "projects", project, "related"], WRITE_ROWS.related, input);
23581
24060
  }
23582
24061
  async getIssue(issue) {
23583
24062
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue)]);
23584
24063
  }
23585
24064
  async updateIssue(issue, input) {
23586
- return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
24065
+ return this.#write("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input.components === undefined ? WRITE_ROWS.updateIssue : WRITE_ROWS.updateIssueComponents, input);
23587
24066
  }
23588
24067
  async changeIssueStatus(issue, input) {
23589
24068
  const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "status-change"];
23590
24069
  try {
23591
- return await this.#json("POST", path, input);
24070
+ return await this.#write("POST", path, WRITE_ROWS.changeIssueStatus, input);
23592
24071
  } catch (error) {
23593
24072
  throw this.#refusalOfNoRoute(error, path, (route) => statusChangeNoRouteRefusal(this.#baseUrl, route));
23594
24073
  }
23595
24074
  }
23596
24075
  async claimIssue(issue, input = {}) {
23597
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
24076
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], WRITE_ROWS.claimIssue, input);
23598
24077
  }
23599
24078
  async releaseIssueClaim(issue, input = {}) {
23600
24079
  return this.#json("DELETE", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
@@ -23624,7 +24103,7 @@ class DispatchClient {
23624
24103
  return { issue, events };
23625
24104
  }
23626
24105
  async ask(issue, input) {
23627
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], input);
24106
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], WRITE_ROWS.ask, input);
23628
24107
  }
23629
24108
  async openAsks(sessionID, since) {
23630
24109
  return this.#json("GET", ["api", "v1", "asks", "open"], undefined, {
@@ -23669,7 +24148,7 @@ class DispatchClient {
23669
24148
  return this.#json("GET", ["api", "v1", "credential-requests"], undefined, { approver: "me" });
23670
24149
  }
23671
24150
  async createProject(input) {
23672
- return this.#json("POST", ["api", "v1", "projects"], input);
24151
+ return this.#write("POST", ["api", "v1", "projects"], WRITE_ROWS.createProject, input);
23673
24152
  }
23674
24153
  async listProjects() {
23675
24154
  return this.#json("GET", ["api", "v1", "projects"]);
@@ -23705,26 +24184,12 @@ class DispatchClient {
23705
24184
  }
23706
24185
  async syncArchitectureSources(project) {
23707
24186
  try {
23708
- return await this.#json("POST", [
23709
- "api",
23710
- "v1",
23711
- "projects",
23712
- project,
23713
- "architecture-sources",
23714
- "sync"
23715
- ]);
24187
+ return await this.#write("POST", ["api", "v1", "projects", project, "architecture-sources", "sync"], WRITE_ROWS.syncArchitectureSources);
23716
24188
  } catch (error) {
23717
24189
  if (!(error instanceof DispatchNoRouteError))
23718
24190
  throw error;
23719
24191
  }
23720
- const source = await this.#json("POST", [
23721
- "api",
23722
- "v1",
23723
- "projects",
23724
- project,
23725
- "architecture-source",
23726
- "sync"
23727
- ]);
24192
+ const source = await this.#write("POST", ["api", "v1", "projects", project, "architecture-source", "sync"], WRITE_ROWS.syncArchitectureSource);
23728
24193
  return [source];
23729
24194
  }
23730
24195
  async syncArchitectureSource(project, repo) {
@@ -23732,37 +24197,25 @@ class DispatchClient {
23732
24197
  if (!owner || !name || rest.length > 0) {
23733
24198
  throw new Error(`repository must be owner/name, got ${JSON.stringify(repo)}`);
23734
24199
  }
23735
- return this.#json("POST", [
23736
- "api",
23737
- "v1",
23738
- "projects",
23739
- project,
23740
- "architecture-sources",
23741
- owner,
23742
- name,
23743
- "sync"
23744
- ]);
24200
+ return this.#write("POST", ["api", "v1", "projects", project, "architecture-sources", owner, name, "sync"], WRITE_ROWS.syncArchitectureSource);
23745
24201
  }
23746
24202
  async resolveAsk(id, input) {
23747
- return this.#json("POST", ["api", "v1", "asks", id, "resolve"], input);
24203
+ return this.#write("POST", ["api", "v1", "asks", id, "resolve"], WRITE_ROWS.resolveAsk, input);
23748
24204
  }
23749
24205
  async requestApproval(artifactID, input) {
23750
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], input);
24206
+ const answer = await this.#writeAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], WRITE_ROWS.requestApproval, input);
23751
24207
  return { ...answer.payload, recorded: answer.status === 201 };
23752
24208
  }
23753
24209
  async planApprove(artifactID, input) {
23754
- return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
24210
+ return this.#write("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], WRITE_ROWS.planApprove, input);
23755
24211
  }
23756
24212
  async reviewArtifact(artifactID, version, input) {
23757
24213
  const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
23758
24214
  const body = { state: input.state, reason: input.reason };
23759
24215
  try {
23760
24216
  const route = await this.#credential.approveRoute?.(this.#credentialSignal(this.#signal));
23761
- if (route !== undefined) {
23762
- const via = this.#throughProxy(route, this.#url(path));
23763
- return (await this.#jsonAnswer("POST", path, body, { via })).payload;
23764
- }
23765
- return await this.#json("POST", path, body);
24217
+ const via = route === undefined ? undefined : this.#throughProxy(route, this.#url(path));
24218
+ return await this.#write("POST", path, WRITE_ROWS.reviewArtifact, body, { via });
23766
24219
  } catch (error) {
23767
24220
  throw this.#refusalOfNoRoute(error, path, (route) => reviewNoRouteRefusal(this.#baseUrl, route, version));
23768
24221
  }
@@ -23783,12 +24236,12 @@ class DispatchClient {
23783
24236
  return { credential, init: { proxy: proxy.toString(), tls: { ca: route.caCertificate } } };
23784
24237
  }
23785
24238
  async recordResult(issue, input) {
23786
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
24239
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], WRITE_ROWS.recordResult, input);
23787
24240
  }
23788
24241
  async dryRunResult(issue, input) {
23789
24242
  const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "results", "dry-run"];
23790
24243
  try {
23791
- return await this.#writingNothing(path, input, { writes: false });
24244
+ return await this.#writingNothing(path, WRITE_ROWS.dryRunResult, input);
23792
24245
  } catch (error) {
23793
24246
  throw this.#refusalOfNoRoute(error, path, (route) => resultDryRunNoRouteRefusal(this.#baseUrl, route));
23794
24247
  }
@@ -23797,19 +24250,19 @@ class DispatchClient {
23797
24250
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], undefined, at === undefined ? undefined : { at });
23798
24251
  }
23799
24252
  async recordDeploy(input) {
23800
- return this.#json("POST", ["api", "v1", "deploys"], input);
24253
+ return this.#write("POST", ["api", "v1", "deploys"], WRITE_ROWS.recordDeploy, input);
23801
24254
  }
23802
24255
  async deploys(repo) {
23803
24256
  return this.#json("GET", ["api", "v1", "deploys"], undefined, { repo });
23804
24257
  }
23805
24258
  async retractResult(resultID, input) {
23806
- return this.#json("POST", ["api", "v1", "results", resultID, "retract"], input);
24259
+ return this.#write("POST", ["api", "v1", "results", resultID, "retract"], WRITE_ROWS.retractResult, input);
23807
24260
  }
23808
24261
  async editAsk(id, input) {
23809
- return this.#json("PATCH", ["api", "v1", "asks", id], input);
24262
+ return this.#write("PATCH", ["api", "v1", "asks", id], WRITE_ROWS.editAsk, input);
23810
24263
  }
23811
24264
  async comment(issue, input) {
23812
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], input);
24265
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], WRITE_ROWS.comment, input);
23813
24266
  }
23814
24267
  async listIssueAsks(issue, state) {
23815
24268
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], undefined, state === undefined ? undefined : { state });
@@ -23818,11 +24271,11 @@ class DispatchClient {
23818
24271
  return this.#json("GET", ["api", "v1", "artifacts", id, "asks"], undefined, state === undefined ? undefined : { state });
23819
24272
  }
23820
24273
  async artifactAsk(id, input) {
23821
- return this.#json("POST", ["api", "v1", "artifacts", id, "asks"], input);
24274
+ return this.#write("POST", ["api", "v1", "artifacts", id, "asks"], WRITE_ROWS.artifactAsk, input);
23822
24275
  }
23823
24276
  async suggest(issue, input) {
23824
24277
  const { replace_with, ...comment } = input;
23825
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], {
24278
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], WRITE_ROWS.suggest, {
23826
24279
  ...comment,
23827
24280
  suggestion: { replace_with }
23828
24281
  });
@@ -23831,27 +24284,27 @@ class DispatchClient {
23831
24284
  return this.#json("GET", ["api", "v1", "artifacts", id, "comments"]);
23832
24285
  }
23833
24286
  async artifactComment(id, input) {
23834
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], input);
24287
+ return this.#write("POST", ["api", "v1", "artifacts", id, "comments"], WRITE_ROWS.artifactComment, input);
23835
24288
  }
23836
24289
  async artifactSuggest(id, input) {
23837
24290
  const { replace_with, ...comment } = input;
23838
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], {
24291
+ return this.#write("POST", ["api", "v1", "artifacts", id, "comments"], WRITE_ROWS.artifactSuggest, {
23839
24292
  ...comment,
23840
24293
  suggestion: { replace_with }
23841
24294
  });
23842
24295
  }
23843
24296
  async message(issue, input) {
23844
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
24297
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], WRITE_ROWS.message, input);
23845
24298
  }
23846
24299
  async agentMessage(sessionId, input) {
23847
- return this.#json("POST", ["api", "v1", "agents", sessionId, "messages"], input);
24300
+ return this.#write("POST", ["api", "v1", "agents", sessionId, "messages"], WRITE_ROWS.agentMessage, input);
23848
24301
  }
23849
24302
  async messageReply(id, input, options = {}) {
23850
- return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
24303
+ return this.#write("POST", ["api", "v1", "messages", id, "reply"], WRITE_ROWS.messageReply, input, { query: options.followUp === true ? { follow_up: "true" } : undefined });
23851
24304
  }
23852
24305
  async deliveryReply(resource, id, input, options = {}) {
23853
24306
  const collection = resource === "message" ? "messages" : "comments";
23854
- await this.#json("POST", ["api", "v1", collection, id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
24307
+ await this.#write("POST", ["api", "v1", collection, id, "reply"], WRITE_ROWS.deliveryReply, input, { query: options.followUp === true ? { follow_up: "true" } : undefined });
23855
24308
  }
23856
24309
  async getMessage(issue, id) {
23857
24310
  return this.#json("GET", [
@@ -23867,7 +24320,7 @@ class DispatchClient {
23867
24320
  return this.#json("GET", ["api", "v1", "messages", id], undefined, session === undefined ? undefined : { session });
23868
24321
  }
23869
24322
  async editMessage(id, input) {
23870
- return this.#json("PATCH", ["api", "v1", "messages", id], input);
24323
+ return this.#write("PATCH", ["api", "v1", "messages", id], WRITE_ROWS.editMessage, input);
23871
24324
  }
23872
24325
  async deleteMessage(id, actor) {
23873
24326
  return this.#json("DELETE", ["api", "v1", "messages", id], { actor });
@@ -23879,10 +24332,10 @@ class DispatchClient {
23879
24332
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"]);
23880
24333
  }
23881
24334
  async acceptMessageDelivery(id, attempt, input) {
23882
- return this.#json("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], input);
24335
+ return this.#write("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], WRITE_ROWS.acceptMessageDelivery, input);
23883
24336
  }
23884
24337
  async artifact(issue, input) {
23885
- return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input);
24338
+ return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input, WRITE_ROWS.artifact);
23886
24339
  }
23887
24340
  async getArtifact(id) {
23888
24341
  return this.#json("GET", ["api", "v1", "artifacts", id]);
@@ -23924,10 +24377,12 @@ class DispatchClient {
23924
24377
  return this.#json("GET", ["api", "v1", "messages", id, "blocks"], undefined, session === undefined ? undefined : { session });
23925
24378
  }
23926
24379
  async docEdit(id, input, key) {
23927
- return this.#json("POST", ["api", "v1", "artifacts", id, "edits"], input, undefined, undefined, key);
24380
+ return this.#write("POST", ["api", "v1", "artifacts", id, "edits"], WRITE_ROWS.docEdit, input, {
24381
+ key
24382
+ });
23928
24383
  }
23929
24384
  async nameArtifactVersion(id, input) {
23930
- return this.#json("POST", ["api", "v1", "artifacts", id, "versions"], input);
24385
+ return this.#write("POST", ["api", "v1", "artifacts", id, "versions"], WRITE_ROWS.nameArtifactVersion, input);
23931
24386
  }
23932
24387
  async getArtifactEvents(id, after = 0, limit = 200) {
23933
24388
  return this.#json("GET", ["api", "v1", "artifacts", id, "events"], undefined, { after, limit });
@@ -23948,10 +24403,12 @@ class DispatchClient {
23948
24403
  return this.#json("GET", ["api", "v1", "comments", id]);
23949
24404
  }
23950
24405
  async resolveComment(id, actor) {
23951
- return this.#json("POST", ["api", "v1", "comments", id, "resolve"], { actor });
24406
+ return this.#write("POST", ["api", "v1", "comments", id, "resolve"], WRITE_ROWS.resolveComment, {
24407
+ actor
24408
+ });
23952
24409
  }
23953
24410
  async editComment(id, input) {
23954
- return this.#json("PATCH", ["api", "v1", "comments", id], input);
24411
+ return this.#write("PATCH", ["api", "v1", "comments", id], WRITE_ROWS.editComment, input);
23955
24412
  }
23956
24413
  async deleteComment(id, actor) {
23957
24414
  return this.#json("DELETE", ["api", "v1", "comments", id], { actor });
@@ -23963,7 +24420,7 @@ class DispatchClient {
23963
24420
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"]);
23964
24421
  }
23965
24422
  async writeHandoff(issue, phase, input) {
23966
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs", phase], input);
24423
+ return this.#write("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs", phase], WRITE_ROWS.writeHandoff, input);
23967
24424
  }
23968
24425
  async listHandoffs(issue) {
23969
24426
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "handoffs"]);
@@ -23998,6 +24455,60 @@ class DispatchClient {
23998
24455
  ...query.since === undefined ? {} : { since: query.since }
23999
24456
  });
24000
24457
  }
24458
+ #writePayload(method, url, answer, write) {
24459
+ const stores = rowStores(write.row);
24460
+ if (!answer.response.ok) {
24461
+ if (!stores && answer.echoed && answer.code === IDEMPOTENCY_KEY_COMMITTED)
24462
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
24463
+ return this.#payloadOf(method, url, answer);
24464
+ }
24465
+ if (NULL_BODY_STATUSES.has(answer.response.status) && !stores)
24466
+ return this.#payloadOf(method, url, answer);
24467
+ const value = answer.json?.value;
24468
+ const replayed = answer.response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1";
24469
+ if (answerNotKept(answer.response.status, replayed, value)) {
24470
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text, undefined, IDEMPOTENCY_ANSWER_NOT_KEPT);
24471
+ }
24472
+ const parsed = write.row.safeParse(value);
24473
+ if (!parsed.success)
24474
+ throw this.#missingWriteAnswer(method, url, answer.response, write, answer.text, parsed.error);
24475
+ return value;
24476
+ }
24477
+ #missingWriteAnswer(method, url, response, write, text, cause, code = DISPATCH_ANSWER_LOST) {
24478
+ const shown = requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING);
24479
+ if (!rowStores(write.row))
24480
+ return code === IDEMPOTENCY_ANSWER_NOT_KEPT && keyEchoed(response, write.key) ? new DispatchAnswerNotKeptError(response.status, method, shown) : new DispatchAnswerMissingError(response.status, method, shown, { cause });
24481
+ if (keyEchoed(response, write.key))
24482
+ return new DispatchWriteLandedError(code, response.status, method, shown, { cause });
24483
+ const names = keyNamedBack(response) === "" ? "naming no key back" : "naming another request's key back";
24484
+ return new DispatchWriteUnsettledError(this.#gatewayError(method, url, response, text, "the write's answer", {
24485
+ advice: "the write may have reached Dispatch behind what answered it",
24486
+ also: `${names}, `
24487
+ }), write.progress.sent, write.key);
24488
+ }
24489
+ async#writeAnswer(method, path, row, body, options = {}) {
24490
+ const url = this.#url(path, options.query);
24491
+ const write = this.#writeCall(method, url, row, options.key);
24492
+ const answer = await this.#sendWrite(method, url, body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" }, "application/json", undefined, write, options.via);
24493
+ return {
24494
+ status: answer.response.status,
24495
+ payload: this.#writePayload(method, url, answer, write)
24496
+ };
24497
+ }
24498
+ async#write(method, path, row, body, options = {}) {
24499
+ return (await this.#writeAnswer(method, path, row, body, options)).payload;
24500
+ }
24501
+ async specCheckResults(project, commit, check) {
24502
+ return this.#json("GET", ["api", "v1", "projects", project, "results"], undefined, {
24503
+ commit,
24504
+ check
24505
+ });
24506
+ }
24507
+ async recordSpecCheckResult(project, input) {
24508
+ const { commit, check, verdict, observed } = input;
24509
+ const body = { commit, check, verdict, observed };
24510
+ return this.#write("POST", ["api", "v1", "projects", project, "results"], WRITE_ROWS.recordSpecCheckResult, body);
24511
+ }
24001
24512
  async#resolveIssue(issueReference) {
24002
24513
  if (!issueReference.includes("#"))
24003
24514
  return issueReference;
@@ -24015,21 +24526,12 @@ class DispatchClient {
24015
24526
  throw error;
24016
24527
  }
24017
24528
  }
24018
- async#json(method, path, body, query, signal, key) {
24019
- return (await this.#jsonAnswer(method, path, body, { query, signal, key })).payload;
24020
- }
24021
- async#jsonAnswer(method, path, body, options = {}) {
24022
- const { query, signal, key, writes = true, via } = options;
24529
+ async#json(method, path, body, query, signal) {
24023
24530
  const url = this.#url(path, query);
24024
24531
  const encoded = body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" };
24025
- const write = this.#writeCall(method, url, key, writes);
24026
- if (write !== undefined) {
24027
- const answer = await this.#write(method, url, encoded, "application/json", signal, write, via);
24028
- return { status: answer.response.status, payload: this.#payloadOf(method, url, answer) };
24029
- }
24030
24532
  return this.#noRoute(async () => {
24031
24533
  const { answer: response } = await this.#send(method, url, encoded, undefined, signal);
24032
- return { status: response.status, payload: await this.#response(method, url, response) };
24534
+ return this.#response(method, url, response);
24033
24535
  }, signal);
24034
24536
  }
24035
24537
  async#noRoute(attempt, signal) {
@@ -24046,19 +24548,17 @@ class DispatchClient {
24046
24548
  return error;
24047
24549
  return refuse(`POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`);
24048
24550
  }
24049
- #writeCall(method, url, key, writes = true) {
24050
- if (method !== "POST" && method !== "PATCH")
24051
- return;
24551
+ #writeCall(method, url, row, key) {
24052
24552
  return {
24053
24553
  key: key ?? crypto.randomUUID(),
24054
24554
  request: `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`,
24055
- writes,
24056
- progress: { sent: 0, running: false, keyEchoed: false }
24555
+ row,
24556
+ progress: { sent: 0, running: false }
24057
24557
  };
24058
24558
  }
24059
- async#upload(path, input, key) {
24559
+ async#upload(path, input, row, key) {
24060
24560
  if (input.file === undefined) {
24061
- return this.#json("POST", path, input, undefined, undefined, key);
24561
+ return this.#write("POST", path, row, input, { key });
24062
24562
  }
24063
24563
  const form = new FormData;
24064
24564
  form.set("name", input.name);
@@ -24069,31 +24569,24 @@ class DispatchClient {
24069
24569
  if (input.actor !== undefined)
24070
24570
  form.set("actor", JSON.stringify(input.actor));
24071
24571
  form.set("file", input.file, input.name);
24072
- return this.#form("POST", path, form, key);
24572
+ return this.#form(path, form, row, key);
24073
24573
  }
24074
- async#form(method, path, form, callerKey) {
24574
+ async#form(path, form, row, key) {
24075
24575
  const url = this.#url(path);
24076
24576
  const encoded = new Response(form);
24077
24577
  const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
24078
24578
  const body = { content: new Uint8Array(await encoded.arrayBuffer()), type };
24079
- const write = this.#writeCall(method, url, callerKey);
24080
- if (write !== undefined) {
24081
- const answer = await this.#write(method, url, body, "application/json", undefined, write);
24082
- return this.#payloadOf(method, url, answer);
24083
- }
24084
- return this.#noRoute(async () => this.#response(method, url, (await this.#send(method, url, body)).answer));
24579
+ const write = this.#writeCall("POST", url, row, key);
24580
+ const answer = await this.#sendWrite("POST", url, body, "application/json", undefined, write);
24581
+ return this.#writePayload("POST", url, answer, write);
24085
24582
  }
24086
- async#writingNothing(path, body, options = {}) {
24583
+ async#writingNothing(path, row, body) {
24087
24584
  for (let keys = 1;; keys++) {
24088
24585
  try {
24089
- return (await this.#jsonAnswer("POST", path, body, options)).payload;
24586
+ return await this.#write("POST", path, row, body);
24090
24587
  } catch (error) {
24091
- if (!(error instanceof DispatchWriteLandedError) || error.code !== IDEMPOTENCY_ANSWER_NOT_KEPT) {
24588
+ if (!(error instanceof DispatchAnswerNotKeptError) || keys === 2)
24092
24589
  throw error;
24093
- }
24094
- if (keys === 2) {
24095
- throw new DispatchAnswerNotKeptError(error.status, "POST", requestForText(this.#baseUrl, this.#url(path), DISPATCH_URL_SETTING));
24096
- }
24097
24590
  }
24098
24591
  }
24099
24592
  }
@@ -24165,9 +24658,10 @@ class DispatchClient {
24165
24658
  });
24166
24659
  return { answer, presented };
24167
24660
  }
24168
- async#write(method, url, body, accept, signal, write, via) {
24661
+ async#sendWrite(method, url, body, accept, signal, write, via) {
24169
24662
  const limit = signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]);
24170
24663
  const { key, progress } = write;
24664
+ const stores = rowStores(write.row);
24171
24665
  const credential = via?.credential ?? this.#credential;
24172
24666
  const headers = { Accept: accept, [IDEMPOTENCY_KEY_HEADER]: key };
24173
24667
  if (body !== undefined)
@@ -24214,18 +24708,17 @@ class DispatchClient {
24214
24708
  response = await this.#attempt(url, method, { ...headers, ...presented }, body, silenceMs, limit, via?.init);
24215
24709
  } catch (error) {
24216
24710
  return {
24217
- event: stoppedEvent(limit, true, error) ?? (error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
24711
+ event: stoppedEvent(limit, true, error) ?? (error instanceof AirlockTunnelRefusedError ? proxyEvent(error.status, false) : error instanceof WriteAttemptSilent ? "silence" : error instanceof DispatchUnreachableError && error.reachedNothing ? "unreached" : "reset"),
24218
24712
  failure: error,
24219
24713
  presented,
24220
24714
  sent
24221
24715
  };
24222
24716
  }
24717
+ const echoed = keyEchoed(response, key);
24223
24718
  const heard = { retryAfterMs: retryAfterMs(response.headers) };
24224
- if (response.headers.get(IDEMPOTENCY_KEY_HEADER) === key)
24225
- progress.keyEchoed = true;
24226
24719
  let answer;
24227
24720
  try {
24228
- answer = await writeAnswer(response);
24721
+ answer = await writeAnswer(response, echoed);
24229
24722
  } catch (error) {
24230
24723
  const stop = stoppedEvent(limit, true, error);
24231
24724
  return {
@@ -24237,7 +24730,7 @@ class DispatchClient {
24237
24730
  };
24238
24731
  }
24239
24732
  return {
24240
- event: answerEvent(answer, write.key, progress.keyEchoed, credential.stale !== undefined && !deadTokenTold, via !== undefined),
24733
+ event: answerEvent(answer, credential.stale !== undefined && !deadTokenTold),
24241
24734
  answer,
24242
24735
  presented,
24243
24736
  sent,
@@ -24255,13 +24748,14 @@ class DispatchClient {
24255
24748
  return result;
24256
24749
  };
24257
24750
  const waitStopped = (error) => ({
24751
+ ...state === "nothing-sent" && error instanceof Error && error.name === "TimeoutError" ? last : {},
24258
24752
  event: stoppedEvent(limit, false, error) ?? "cancelled",
24259
24753
  failure: error
24260
24754
  });
24261
24755
  let last = await next();
24262
24756
  let event = last.event;
24263
24757
  for (;; ) {
24264
- const step = writeStep(state, event, write.writes);
24758
+ const step = writeStep(state, event, stores);
24265
24759
  state = step.state;
24266
24760
  if ((event === "silence" || event === "in-flight") && !upload)
24267
24761
  progress.running = true;
@@ -24353,9 +24847,6 @@ class DispatchClient {
24353
24847
  } catch (error) {
24354
24848
  if (cut.signal.aborted && !limit.aborted)
24355
24849
  throw cut.signal.reason;
24356
- const refused = transport === undefined ? undefined : proxyTunnelAnswer(error);
24357
- if (refused !== undefined)
24358
- return refused;
24359
24850
  throw error;
24360
24851
  } finally {
24361
24852
  answered = true;
@@ -24364,15 +24855,22 @@ class DispatchClient {
24364
24855
  }
24365
24856
  async#endWrite(method, url, state, event, answer, failure, write, routeSpent, via) {
24366
24857
  const { request, progress } = write;
24858
+ if (answer?.response.status === 409 && answer.code === IDEMPOTENCY_KEY_COMMITTED && !answer.echoed) {
24859
+ return this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
24860
+ }
24367
24861
  let own = failure;
24368
- const proxyCode = via === undefined ? null : answer?.response.headers.get(PROXY_CODE_HEADER);
24369
- if (via !== undefined && answer !== undefined && typeof proxyCode === "string") {
24370
- own = this.#proxyRefusal(request, via, answer, proxyCode, state, event);
24862
+ if (answer?.proxy !== undefined) {
24863
+ own = via === undefined ? this.#airlockAnswer(answer, answer.proxy) : this.#proxyRefusal(request, via, answer.response.status, answer.proxy.code, answer.text, state, event);
24864
+ } else if (via !== undefined && failure instanceof AirlockTunnelRefusedError) {
24865
+ own = this.#proxyRefusal(request, via, failure.status, failure.proxyCode ?? failure.code, "", state, event);
24371
24866
  } else if (via !== undefined && failure instanceof DispatchUnreachableError) {
24372
24867
  own = this.#proxyUnreachable(via, failure, state);
24373
24868
  } else if (answer?.response.ok === true) {
24869
+ if (!answer.echoed || !rowStores(write.row)) {
24870
+ return this.#missingWriteAnswer(method, url, answer.response, write, answer.text);
24871
+ }
24374
24872
  const { status } = answer.response;
24375
- 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`);
24873
+ 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`);
24376
24874
  } else if (answer !== undefined) {
24377
24875
  own = event === "no-route" && routeSpent ? new DispatchNoRouteError : this.#payloadOrError(method, url, answer);
24378
24876
  }
@@ -24380,7 +24878,7 @@ class DispatchClient {
24380
24878
  return own;
24381
24879
  const last = own instanceof Error ? own : new Error(String(own));
24382
24880
  let unanswered;
24383
- if (answer === undefined) {
24881
+ if (answer === undefined || answer.proxy !== undefined) {
24384
24882
  switch (event) {
24385
24883
  case "silence":
24386
24884
  unanswered = `${request} ${last.message}`;
@@ -24410,14 +24908,21 @@ class DispatchClient {
24410
24908
  const again = state === "nothing-sent" ? " The review can be sent again once the broker answers." : "";
24411
24909
  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);
24412
24910
  }
24413
- #proxyRefusal(request, via, answer, code, state, event) {
24414
- const { status } = answer.response;
24415
- const said = excerpt(answer.text, this.#sent.with(this.token));
24911
+ #proxyRefusal(request, via, status, code, text, state, event) {
24912
+ const said = excerpt(text, this.#sent.with(this.token));
24416
24913
  const by = `${request} was answered ${status} ${code} by Cipher's proxy at ${originOf(via.init.proxy)}${said === "" ? "" : ` (${JSON.stringify(said)})`}`;
24417
24914
  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.`;
24418
24915
  return new DispatchProxyRefusalError(code, status, message);
24419
24916
  }
24917
+ #airlockAnswer(answer, proxy) {
24918
+ const body = excerpt(answer.text, this.#sent.with(this.token));
24919
+ const { status } = answer.response;
24920
+ return proxy.left ? new AirlockOutcomeUnknownError(status, proxy.code, body) : new AirlockRefusedError(status, proxy.code, body);
24921
+ }
24420
24922
  #url(path, query) {
24923
+ if (path.some((segment) => pathNamesNothingPattern.test(segment))) {
24924
+ throw new DispatchEmptyPathError(path);
24925
+ }
24421
24926
  const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
24422
24927
  if (query) {
24423
24928
  for (const [name, value] of Object.entries(query)) {
@@ -24447,7 +24952,7 @@ class DispatchClient {
24447
24952
  throw new DispatchServiceError(refusal.code ?? `HTTP_${response.status}`, response.status, refusal.error, {
24448
24953
  ...refusal,
24449
24954
  textRefusal: response.headers.has(TEXT_REFUSAL_HEADER)
24450
- });
24955
+ }, retryAfterMs(response.headers) || null);
24451
24956
  }
24452
24957
  throw this.#gatewayError(method, url, response, text, "Dispatch's error JSON");
24453
24958
  }
@@ -24467,7 +24972,7 @@ class DispatchClient {
24467
24972
  return error;
24468
24973
  }
24469
24974
  }
24470
- #gatewayError(method, url, response, text, notWhat) {
24975
+ #gatewayError(method, url, response, text, notWhat, caller = {}) {
24471
24976
  const tokens = this.#sent.with(this.token);
24472
24977
  const body = bodyForText(text, tokens, notWhat);
24473
24978
  const reasonPhrase = excerpt(response.statusText, tokens);
@@ -24475,7 +24980,7 @@ class DispatchClient {
24475
24980
  const target = redirectOrigin(response, url, tokens);
24476
24981
  const redirected = target === undefined ? "" : ` (a redirect to ${target}, which this client does not follow)`;
24477
24982
  const request = `${method} ${requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING)}`;
24478
- return new DispatchGatewayError(response.status, `${request} answered ${response.status}${reason}${redirected} with ${body}, ${GATEWAY_PAGE}`, gatewayAdvice(method, response.status));
24983
+ return new DispatchGatewayError(response.status, `${request} answered ${response.status}${reason}${redirected} with ${body}, ${caller.also ?? ""}${GATEWAY_PAGE}`, caller.advice ?? gatewayAdvice(method, response.status));
24479
24984
  }
24480
24985
  }
24481
24986
 
@@ -24707,6 +25212,7 @@ var WRITE_ROUTES = [
24707
25212
  { method: "POST", pattern: "/api/v1/issues/{key}/results", commands: ["result"] },
24708
25213
  { method: "POST", pattern: "/api/v1/issues/{key}/results/dry-run", commands: ["result"] },
24709
25214
  { method: "POST", pattern: "/api/v1/results/{id}/retract", commands: ["result"] },
25215
+ { method: "POST", pattern: "/api/v1/projects/{key}/results", commands: ["result"] },
24710
25216
  { method: "POST", pattern: "/api/v1/deploys", commands: ["deploy"] },
24711
25217
  { method: "POST", pattern: "/api/v1/issues/{key}/handoffs/{phase}", commands: ["handoff-write"] },
24712
25218
  { method: "POST", pattern: "/api/v1/issues/{key}/artifacts", commands: ["artifact"] },
@@ -29316,6 +29822,16 @@ function brokerCredential(env, session, read) {
29316
29822
  };
29317
29823
  }
29318
29824
 
29825
+ // ../envoy-client/src/airlock-credential.ts
29826
+ var AIRLOCK_RESULTS_VAR = "DISPATCH_RESULTS_TOKEN";
29827
+ function airlockCredential(placeholder) {
29828
+ return {
29829
+ scheme: "DPoP",
29830
+ headers: () => ({ Authorization: `DPoP ${placeholder}` }),
29831
+ secret: () => placeholder
29832
+ };
29833
+ }
29834
+
29319
29835
  // ../envoy-client/src/file-token-credential.ts
29320
29836
  import { readFileSync as readFileSync3 } from "fs";
29321
29837
  var TOKEN_FILE_VAR = "DISPATCH_BROKER_TOKEN_FILE";
@@ -29448,6 +29964,26 @@ async function dispatchUrl(env, config) {
29448
29964
  const target = await dispatchTarget(env, config);
29449
29965
  return target.enabled ? target.url : undefined;
29450
29966
  }
29967
+ function ownIdentityDispatch(env) {
29968
+ const url = nonEmpty(env.DISPATCH_URL);
29969
+ if (url === undefined) {
29970
+ return offWithError("DISPATCH_URL is not set: a CI job's write reads Dispatch's server from it alone");
29971
+ }
29972
+ if (httpUrl2(url) === undefined)
29973
+ return offWithError("DISPATCH_URL must be an http or https URL");
29974
+ const placeholder = nonEmpty(env[AIRLOCK_RESULTS_VAR]);
29975
+ if (placeholder === undefined) {
29976
+ 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`);
29977
+ }
29978
+ if (!sendable(placeholder)) {
29979
+ 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`);
29980
+ }
29981
+ return {
29982
+ enabled: true,
29983
+ url: withoutTrailingSlashes(url),
29984
+ credential: airlockCredential(placeholder)
29985
+ };
29986
+ }
29451
29987
  var BESIDE_TOKEN_FILES = [
29452
29988
  "DISPATCH_TOKEN_BROKER",
29453
29989
  "DISPATCH_TOKEN_BROKER_READ",
@@ -30797,6 +31333,40 @@ function notMadeLine(reason, context, searchQuery) {
30797
31333
  return `No related-item check was made: ${reason}. Search before you rely on this being new: dispatch search --project ${context.project}${query}`;
30798
31334
  }
30799
31335
 
31336
+ // ../envoy-client/src/runner-log.ts
31337
+ var ESCAPED = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/gu;
31338
+ var JSON_ESCAPED = /[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;
31339
+ var SHORT_ESCAPES = {
31340
+ "\x07": "\\a",
31341
+ "\b": "\\b",
31342
+ "\f": "\\f",
31343
+ "\n": "\\n",
31344
+ "\r": "\\r",
31345
+ "\t": "\\t",
31346
+ "\v": "\\v"
31347
+ };
31348
+ function hex3(value, digits) {
31349
+ return value.toString(16).padStart(digits, "0");
31350
+ }
31351
+ function goEscape(character) {
31352
+ const short = SHORT_ESCAPES[character];
31353
+ if (short !== undefined)
31354
+ return short;
31355
+ const point = character.codePointAt(0) ?? 0;
31356
+ if (point < 32 || point === 127)
31357
+ return `\\x${hex3(point, 2)}`;
31358
+ return point > 65535 ? `\\U${hex3(point, 8)}` : `\\u${hex3(point, 4)}`;
31359
+ }
31360
+ function printable2(text) {
31361
+ return text.replace(ESCAPED, goEscape).replaceAll("##[", "##\\x5b");
31362
+ }
31363
+ function printableLine(text) {
31364
+ return printable2(text).replace(/^(\s*):(?=:)/u, "$1\\x3a");
31365
+ }
31366
+ function printableJson(json) {
31367
+ return json.replace(JSON_ESCAPED, (character) => Array.from({ length: character.length }, (_, unit) => `\\u${hex3(character.charCodeAt(unit), 4)}`).join("")).replaceAll("##[", "##\\u005b");
31368
+ }
31369
+
30800
31370
  // ../envoy-client/src/dispatch-commands/advice.ts
30801
31371
  var triageAdviceShown = new Set;
30802
31372
  function adviceMemory() {
@@ -30907,6 +31477,31 @@ async function otherAdviceLines(render) {
30907
31477
  }
30908
31478
  }
30909
31479
 
31480
+ // ../envoy-client/src/dispatch-commands/observed-text.ts
31481
+ function lengthOfFirst(text, count) {
31482
+ let at = 0;
31483
+ for (let seen = 0;seen < count && at < text.length; seen += 1) {
31484
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
31485
+ }
31486
+ return at < text.length ? at : undefined;
31487
+ }
31488
+ function startOfLast(text, count) {
31489
+ let at = text.length;
31490
+ for (let seen = 0;seen < count && at > 0; seen += 1) {
31491
+ const low = text.charCodeAt(at - 1);
31492
+ const high = at > 1 ? text.charCodeAt(at - 2) : 0;
31493
+ at -= low >= 56320 && low <= 57343 && high >= 55296 && high <= 56319 ? 2 : 1;
31494
+ }
31495
+ return at;
31496
+ }
31497
+ function observedAsKept(observed) {
31498
+ const text = observed.replaceAll("\x00", "\uFFFD");
31499
+ if (lengthOfFirst(text, SPEC_CHECK_OBSERVED_MAX) === undefined)
31500
+ return text;
31501
+ const start = text.slice(0, lengthOfFirst(text, SPEC_CHECK_OBSERVED_START));
31502
+ return `${start}${SPEC_CHECK_OBSERVED_CUT_NOTE}${text.slice(startOfLast(text, SPEC_CHECK_OBSERVED_END))}`;
31503
+ }
31504
+
30910
31505
  // ../envoy-client/src/human-edit.ts
30911
31506
  function humanEditHead(edit) {
30912
31507
  const editors = edit.editors ?? [];
@@ -36127,11 +36722,54 @@ async function issuesCommand(context) {
36127
36722
  };
36128
36723
  }
36129
36724
  function dryRunAsksDispatch(tool, args) {
36130
- const { retract } = args;
36131
- return tool === "dispatch_result" && retract === undefined;
36725
+ const { retract, project } = args;
36726
+ return tool === "dispatch_result" && retract === undefined && project === undefined;
36727
+ }
36728
+ async function specCheckResultCommand(client, args) {
36729
+ const project = stringArg(args, "project");
36730
+ const observed = optionalString(args, "observed");
36731
+ const stored = await client.recordSpecCheckResult(project, {
36732
+ commit: stringArg(args, "commit"),
36733
+ check: stringArg(args, "check"),
36734
+ verdict: stringArg(args, "verdict"),
36735
+ ...observed === undefined ? {} : { observed: observedAsKept(observed) }
36736
+ });
36737
+ const { predicate } = stored.attestation;
36738
+ return {
36739
+ text: JSON.stringify(stored, null, 2),
36740
+ details: {
36741
+ project,
36742
+ result: stored.id,
36743
+ seq: stored.seq,
36744
+ check: predicate.check,
36745
+ verdict: predicate.verdict
36746
+ }
36747
+ };
36748
+ }
36749
+ function specCheckResultLine(result) {
36750
+ const { predicate, subject } = result.attestation;
36751
+ const leg = predicate.leg === "" ? "no leg" : `leg ${printable2(predicate.leg)}`;
36752
+ const commit = subject?.[0]?.digest?.["gitCommit"] ?? "an unnamed commit";
36753
+ return `- #${result.seq} ${printable2(predicate.check)}: ${printable2(predicate.verdict)}. Job ${printable2(predicate.job)}, ${leg}, run ${printable2(predicate.run.run_id)} attempt ${predicate.run.attempt}, commit ${printable2(commit)}.`;
36754
+ }
36755
+ async function specCheckResultsCommand(client, args) {
36756
+ const project = stringArg(args, "project");
36757
+ const commit = stringArg(args, "commit");
36758
+ const check = optionalString(args, "check");
36759
+ const results = (await client.specCheckResults(project, commit, check)).results ?? [];
36760
+ const what = check === undefined ? project : `check ${printable2(check)} of ${project}`;
36761
+ const text = optionalBoolean(args, "json") === true ? printableJson(JSON.stringify(results, null, 2)) : results.length === 0 ? `No result of ${what} is stored at ${printable2(commit)}.` : [
36762
+ `Results of ${what} at ${printable2(commit)}, newest first:`,
36763
+ ...results.map(specCheckResultLine)
36764
+ ].join(`
36765
+ `);
36766
+ return { text, details: { project, commit, results: results.length } };
36132
36767
  }
36133
36768
  async function resultCommand(context) {
36134
36769
  const { args, client, actor } = context;
36770
+ if (optionalString(args, "project") !== undefined) {
36771
+ return await specCheckResultCommand(client, args);
36772
+ }
36135
36773
  const retract = optionalString(args, "retract");
36136
36774
  if (retract !== undefined) {
36137
36775
  const retraction = await client.retractResult(retract, {
@@ -36203,6 +36841,9 @@ ${recorded.line}`,
36203
36841
  }
36204
36842
  async function resultsCommand(context) {
36205
36843
  const { args, client } = context;
36844
+ if (optionalString(args, "project") !== undefined) {
36845
+ return await specCheckResultsCommand(client, args);
36846
+ }
36206
36847
  const issue = stringArg(args, "issue");
36207
36848
  const at = optionalString(args, "at");
36208
36849
  const brief = optionalBoolean(args, "brief") === true;
@@ -36225,440 +36866,61 @@ async function resultsCommand(context) {
36225
36866
  };
36226
36867
  }
36227
36868
 
36228
- // ../envoy-client/src/dispatch-commands/login.ts
36229
- import { hostname as hostname4 } from "os";
36230
- function parseLogin(argv) {
36231
- let device = false;
36232
- let person;
36233
- for (let at = 0;at < argv.length; at += 1) {
36234
- const word = argv[at];
36235
- if (word === "--help" || word === "-h")
36236
- return { kind: "help" };
36237
- if (word === "--device") {
36238
- device = true;
36239
- } else if (word === "--person") {
36240
- const next = argv[at + 1];
36241
- if (next === undefined)
36242
- return { kind: "refused", problem: "--person needs an address" };
36243
- person = next;
36244
- at += 1;
36245
- } else if (word.startsWith("--person=")) {
36246
- person = word.slice("--person=".length);
36247
- } else {
36248
- return { kind: "refused", problem: `unknown argument ${JSON.stringify(word)}` };
36869
+ // ../envoy-client/src/dispatch-commands/command-context.ts
36870
+ function toolActor(origin, input) {
36871
+ return {
36872
+ kind: "session",
36873
+ id: input.sessionId ?? "unknown",
36874
+ origin: {
36875
+ ...origin,
36876
+ host: input.host,
36877
+ ...input.sessionTitle === undefined ? {} : { session_title: input.sessionTitle }
36249
36878
  }
36250
- }
36251
- return { kind: "login", device, person };
36879
+ };
36252
36880
  }
36253
- async function loginCommand(argv, env, io) {
36254
- const refuse = (problem, code) => {
36255
- io.print(`dispatch login was not called: ${problem}`);
36256
- return code;
36257
- };
36258
- const parsed = parseLogin(argv);
36259
- if (parsed.kind === "help") {
36260
- io.print(loginHelp());
36261
- return OK;
36262
- }
36263
- const tokenFiles = tokenFilesSet(env);
36264
- if (tokenFiles !== undefined) {
36265
- const beside = settingsBesideTokenFiles(env);
36266
- return refuse(`${tokenFiles}, and the token files are the dispatch command's only Dispatch credential, which trades nothing at the secrets broker; a device login asks the broker and keeps a login in a file, so it does not run beside them${beside.length === 0 ? "" : `: ${beside.join("; ")}`}. Run dispatch login in a shell that sets neither token file.`, USAGE);
36267
- }
36268
- if (parsed.kind === "refused")
36269
- return refuse(`${parsed.problem}. Run dispatch login --help.`, USAGE);
36270
- if (!parsed.device) {
36271
- return refuse("it logs a machine in with the broker's device grant alone, so --device is required. Run dispatch login --help.", USAGE);
36272
- }
36273
- const person = (parsed.person ?? env[PERSON_VAR] ?? "").trim();
36274
- if (!person.includes("@")) {
36275
- return refuse(`name the person who approves this machine, by the address they sign in to Dispatch with: --person <address>, or ${PERSON_VAR}.`, USAGE);
36276
- }
36277
- const brokerUrl = (env[BROKER_URL_VAR] ?? "").trim();
36278
- if (!isHttpUrl(brokerUrl)) {
36279
- return refuse(`${BROKER_URL_VAR} ${brokerUrl === "" ? "names no secrets broker" : "is not an http or https URL"}, so there is no broker to log this machine in at.`, USAGE);
36280
- }
36281
- let path;
36282
- try {
36283
- deviceLoginBroker(brokerUrl);
36284
- path = deviceLoginFile(env);
36285
- await deviceLoginPlace(path);
36286
- } catch (error) {
36287
- return refuse(messageFor(error), USAGE);
36288
- }
36289
- const host = deviceLoginHost(hostname4());
36290
- try {
36291
- const started = await startDeviceLogin({
36292
- brokerUrl,
36293
- person,
36294
- host,
36295
- fetch: io.fetchImpl
36296
- });
36297
- io.print([
36298
- `dispatch login: to log this machine (${host}) in at the secrets broker at ${urlForText(started.brokerUrl, BROKER_URL_VAR)}, ${person} approves it:`,
36299
- ` open ${started.verificationUriComplete ?? started.verificationUri}`,
36300
- ` and enter the code ${started.userCode}`,
36301
- `dispatch login: the code is good until ${started.expiresAt.toISOString()}; waiting for the approval.`
36302
- ].join(`
36303
- `));
36304
- const login = await finishDeviceLogin(started, { path, fetch: io.fetchImpl, sleep: io.sleep });
36305
- const lines = [
36306
- `dispatch login: approved. This machine's device login is kept in ${DEVICE_LOGIN_FILE_NAMED}; its launcher credential ${login.credentialId} lasts until ${login.expiresAt.toISOString()}, and each refresh moves that on.`
36307
- ];
36308
- if (login.lockLeft !== "") {
36309
- lines.push(`dispatch login: the login is kept, but ${login.lockLeft}.`);
36310
- }
36311
- if (login.replaced !== "" && login.replaced !== login.credentialId) {
36312
- lines.push(`dispatch login: the earlier login of this machine, launcher credential ${login.replaced}, stays live until it lapses or is revoked, and a copy of its file still works; revoke it in Machine logins on ${started.verificationUri}.`);
36313
- }
36314
- if ((env[IDENTITY_VAR] ?? "").trim() !== IDENTITY_DEVICE_LOGIN) {
36315
- lines.push(`dispatch login: set ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} in the environment of this machine's sessions, so they trade this login.`);
36316
- }
36317
- io.print(lines.join(`
36318
- `));
36319
- return OK;
36320
- } catch (error) {
36321
- io.print(`dispatch login: ${messageFor(error)}`);
36322
- return REFUSED;
36323
- }
36324
- }
36325
-
36326
- // ../envoy-client/src/dispatch-commands/stored-text.ts
36327
- import { resolve as resolvePath2 } from "path";
36328
-
36329
- // ../envoy-client/src/dispatch-commands/stored-spelling.ts
36330
- function headedOpener(line) {
36331
- for (let at = 0;at < line.length; at += Math.max(1, runOf(line, at, ":"))) {
36332
- const brace = typedFenceBrace(line, at);
36333
- if (brace === -1)
36334
- continue;
36335
- const opener = typedOpenerAt(line, at);
36336
- return opener === undefined ? undefined : { ...opener, head: line.slice(0, brace + 1) };
36337
- }
36338
- return;
36339
- }
36340
- function attributesByName(attributes) {
36341
- const byName = new Map(attributes.map((attribute) => [attribute.name, attribute.text]));
36342
- return byName.size === attributes.length ? byName : undefined;
36343
- }
36344
- function inStoredOrder(given, stored) {
36345
- const written = attributesByName(given.attributes);
36346
- if (written === undefined || attributesByName(stored.attributes) === undefined || stored.attributes.length !== given.attributes.length) {
36347
- return;
36348
- }
36349
- let line = `${given.head}${given.gaps[0] ?? ""}`;
36350
- for (const [index, attribute] of stored.attributes.entries()) {
36351
- const text = written.get(attribute.name);
36352
- if (text === undefined)
36353
- return;
36354
- line += `${text}${given.gaps[index + 1] ?? ""}`;
36355
- }
36356
- return `${line}}`;
36357
- }
36358
- function onlyReordered(given, held, stored) {
36359
- return given !== undefined && stored !== undefined && inStoredOrder(given, stored) === held;
36360
- }
36361
- function reorderedBlockLine(line, opener) {
36362
- const named = `${opener.name} block${opener.id === undefined ? "" : ` ${opener.id}`}`;
36363
- const order = opener.attributes.map((attribute) => attribute.name).join(", ");
36364
- return `This upload put the attributes of ${named} (line ${line}) in the order Dispatch stores: ${order}.`;
36365
- }
36366
- function attributesReordered(given, stored) {
36367
- const written = withoutFinalLineFeed(given).split(`
36368
- `);
36369
- const holds = withoutFinalLineFeed(stored).split(`
36370
- `);
36371
- if (written.length !== holds.length)
36372
- return;
36373
- const lines = [];
36374
- for (const [index, held] of holds.entries()) {
36375
- const wrote = written[index];
36376
- if (wrote === held)
36377
- continue;
36378
- const opener = headedOpener(held);
36379
- if (wrote === undefined || opener === undefined || !onlyReordered(headedOpener(wrote), held, opener)) {
36380
- return;
36381
- }
36382
- lines.push(reorderedBlockLine(index + 1, opener));
36383
- }
36384
- return lines;
36385
- }
36386
- var STORED_LINE_QUOTED = 200;
36387
- function quotedStoredLine(characters, from) {
36388
- const shown = characters.slice(from, from + STORED_LINE_QUOTED);
36389
- const quote = JSON.stringify(shown.join(""));
36390
- const cutAfter = from + shown.length < characters.length;
36391
- if (from === 0 && !cutAfter)
36392
- return quote;
36393
- const cut = from === 0 ? "after" : cutAfter ? "before and after" : "before the last";
36394
- return `${quote} (cut ${cut} ${shown.length} of its ${characters.length} characters)`;
36395
- }
36396
- function lineWords(line, opener) {
36397
- const plain = (text) => (text.match(/\s+|\S+/g) ?? []).map((word) => ({ text: word, attribute: false }));
36398
- if (opener === undefined)
36399
- return plain(line);
36400
- const words = plain(opener.head);
36401
- for (const [index, gap] of opener.gaps.entries()) {
36402
- if (gap !== "")
36403
- words.push({ text: gap, attribute: false });
36404
- const attribute = opener.attributes[index];
36405
- if (attribute !== undefined)
36406
- words.push({ text: attribute.text, attribute: true });
36407
- }
36408
- words.push({ text: "}", attribute: false });
36409
- return words;
36410
- }
36411
- function wordText(word, from = 0, characters = Array.from(word.text)) {
36412
- if (word.attribute)
36413
- return `the attribute ${word.text}`;
36414
- return `${/\S/.test(word.text) ? "the word" : "the space"} ${quotedStoredLine(characters, from)}`;
36415
- }
36416
- function wordDifference(written, holds) {
36417
- let before = 0;
36418
- for (let index = 0;index < Math.max(written.length, holds.length); index += 1) {
36419
- const given = written[index];
36420
- const stored = holds[index];
36421
- if (given !== undefined && stored !== undefined && given.text === stored.text) {
36422
- before += Array.from(given.text).length;
36423
- continue;
36424
- }
36425
- if (given === undefined && stored !== undefined) {
36426
- return `ends after character ${before}, where Dispatch goes on with ${wordText(stored)}`;
36427
- }
36428
- if (given !== undefined && stored === undefined) {
36429
- return `reads ${wordText(given)} at character ${before + 1}, where Dispatch ends the line`;
36430
- }
36431
- if (given !== undefined && stored !== undefined) {
36432
- const wrote = Array.from(given.text);
36433
- const held = Array.from(stored.text);
36434
- let from = 0;
36435
- if (!given.attribute && !stored.attribute && Math.max(wrote.length, held.length) > STORED_LINE_QUOTED) {
36436
- while (from < wrote.length && wrote[from] === held[from])
36437
- from += 1;
36438
- const tail = Math.max(0, from - STORED_LINE_QUOTED);
36439
- if (from === wrote.length) {
36440
- return `ends ${wordText(given, tail, wrote)} after character ${before + from}, where Dispatch goes on with ${wordText(stored, from, held)}`;
36441
- }
36442
- if (from === held.length) {
36443
- return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch ends ${wordText(stored, tail, held)}`;
36444
- }
36445
- }
36446
- return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch stores ${wordText(stored, from, held)}`;
36447
- }
36448
- }
36449
- return "differs from the line Dispatch stores";
36450
- }
36451
- function attributeDifference(line, given, stored) {
36452
- const written = attributesByName(given.attributes);
36453
- if (written === undefined)
36454
- return;
36455
- for (const attribute of stored.attributes) {
36456
- const text = written.get(attribute.name);
36457
- if (text === undefined)
36458
- return `Dispatch adds the attribute ${attribute.text} to line ${line}`;
36459
- if (text !== attribute.text) {
36460
- return `line ${line} holds the attribute ${text}, which Dispatch stores as ${attribute.text}`;
36461
- }
36462
- }
36463
- const held = new Set(stored.attributes.map((attribute) => attribute.name));
36464
- const dropped = given.attributes.find((attribute) => !held.has(attribute.name));
36465
- return dropped === undefined ? undefined : `line ${line} holds the attribute ${dropped.text}, which Dispatch drops`;
36466
- }
36467
- function lineDifference(line, wrote, given, held, stored) {
36468
- if (given === undefined || stored === undefined) {
36469
- return `line ${line} ${wordDifference(lineWords(wrote, undefined), lineWords(held, undefined))}`;
36470
- }
36471
- const attribute = attributeDifference(line, given, stored);
36472
- if (attribute !== undefined)
36473
- return attribute;
36474
- const reordered = inStoredOrder(given, stored);
36475
- if (reordered !== undefined && reordered !== wrote) {
36476
- const words = lineWords(reordered, headedOpener(reordered));
36477
- return `line ${line}, with its attributes put in the order Dispatch stores, ${wordDifference(words, lineWords(held, stored))}`;
36478
- }
36479
- return `line ${line} ${wordDifference(lineWords(wrote, given), lineWords(held, stored))}`;
36480
- }
36481
- function firstStoredDifference(given, stored) {
36482
- const written = given.split(`
36483
- `);
36484
- const holds = stored.split(`
36485
- `);
36486
- for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
36487
- const wrote = written[line];
36488
- const held = holds[line];
36489
- if (wrote === held)
36490
- continue;
36491
- if (wrote === undefined && held !== undefined) {
36492
- return `the store writes a line ${line + 1}, ${quotedStoredLine(Array.from(held), 0)}`;
36493
- }
36494
- if (held === undefined && wrote !== undefined) {
36495
- return `the store drops line ${line + 1}, ${quotedStoredLine(Array.from(wrote), 0)}`;
36496
- }
36497
- if (wrote !== undefined && held !== undefined) {
36498
- const givenOpener = headedOpener(wrote);
36499
- const storedOpener = headedOpener(held);
36500
- if (onlyReordered(givenOpener, held, storedOpener))
36501
- continue;
36502
- return lineDifference(line + 1, wrote, givenOpener, held, storedOpener);
36503
- }
36504
- }
36505
- return "the stored text differs from the text given";
36506
- }
36507
- var STORED_TEXT_PRINTED = 2000;
36508
- function storedTextPrinted(stored) {
36509
- if (stored.length <= STORED_TEXT_PRINTED)
36510
- return { text: stored, cut: "" };
36511
- const head = stored.slice(0, STORED_TEXT_PRINTED);
36512
- const lastLineFeed = head.lastIndexOf(`
36513
- `);
36514
- const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
36515
- return {
36516
- text,
36517
- cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
36518
- };
36519
- }
36520
- function storedTextProblem(given, stored, name) {
36521
- const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
36522
- const printed = storedTextPrinted(stored);
36523
- return [
36524
- `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
36525
- ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
36526
- `${printed.cut}
36527
- --- the text Dispatch stores ---
36528
- ${printed.text}`,
36529
- "--- end of the text Dispatch stores ---"
36530
- ].join("");
36531
- }
36532
- function withoutFinalLineFeed(text) {
36533
- return text.endsWith(`
36534
- `) ? text.slice(0, -1) : text;
36535
- }
36536
- function storedUpload(given, stored, name) {
36537
- if (withoutFinalLineFeed(stored) === withoutFinalLineFeed(given)) {
36538
- return { sent: given, reordered: [] };
36539
- }
36540
- const reordered = attributesReordered(given, stored);
36541
- return reordered === undefined ? { refusal: storedTextProblem(given, stored, name) } : { sent: stored, reordered };
36542
- }
36543
-
36544
- // ../envoy-client/src/dispatch-commands/stored-text.ts
36545
- var MARKDOWN_ROUND_TRIP = "POST /api/v1/markdown/round-trip";
36546
- var FILE_ROUND_TRIP = "POST /api/v1/markdown/file-round-trip";
36547
- function storedTextCheckFailed(failed) {
36548
- const again = failed.error instanceof DispatchAnswerNotKeptError ? "Send the upload again, which asks it under a new key." : "Send the upload again once that call is answered.";
36549
- return new Error(`Dispatch could not say how it would store this text, so nothing was uploaded: ${failed.failure}. ${again}`, { cause: failed.error });
36550
- }
36551
- function roundTripRouteAbsent(error) {
36552
- return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
36553
- }
36554
- function documentTooLarge(measured) {
36555
- const bytes = typeof measured === "number" ? measured : typeof measured === "string" ? utf8Bytes(measured) : measured.byteLength;
36556
- return bytes > MARKDOWN_DOCUMENT_MAX_BYTES ? new Error(`CAP_EXCEEDED: ${MARKDOWN_DOCUMENT_TOO_LARGE}`) : undefined;
36557
- }
36558
- function documentBytesRefusal(field, bytes) {
36559
- return documentTooLarge(bytes) ?? unstorableBytes(field, bytes);
36560
- }
36561
- function documentFieldRefusal(field, text) {
36562
- return Buffer.byteLength(text, "utf8") > MARKDOWN_DOCUMENT_MAX_BYTES || text.includes("\x00") ? documentBytesRefusal(field, fileTextBytes(text)) : undefined;
36563
- }
36564
- function uploadedFile(cwd, path) {
36565
- return Bun.file(resolvePath2(cwd, path));
36566
- }
36567
- async function documentFileRead(file, held) {
36568
- if (file.type.split(";", 1)[0]?.trim().toLowerCase() !== "text/markdown") {
36569
- return { kind: "passed", bytes: undefined };
36570
- }
36571
- let bytes = held;
36572
- if (bytes === undefined) {
36573
- const stats = await file.stat().catch(() => {
36574
- return;
36575
- });
36576
- if (stats !== undefined && !stats.isFile() && !stats.isDirectory()) {
36577
- return { kind: "passed", bytes: undefined };
36578
- }
36579
- const tooLarge = stats === undefined ? undefined : documentTooLarge(stats.size);
36580
- if (tooLarge !== undefined)
36581
- return { kind: "refused", refusal: tooLarge };
36582
- try {
36583
- bytes = await file.bytes();
36584
- } catch (error) {
36585
- return { kind: "unread", error };
36586
- }
36587
- }
36588
- const refusal = documentBytesRefusal("file", bytes);
36589
- return refusal === undefined ? { kind: "passed", bytes } : { kind: "refused", refusal };
36590
- }
36591
- async function documentFileBytes(file, held) {
36592
- const read = await documentFileRead(file, held);
36593
- if (read.kind === "refused")
36594
- throw read.refusal;
36595
- if (read.kind === "unread")
36596
- throw read.error;
36597
- return read.bytes;
36598
- }
36599
- function unchecked(answer) {
36600
- return { kind: "unchecked", failure: answer.failure, routeAbsent: answer.routeAbsent };
36601
- }
36602
- async function askRoundTrip(client, route, ask) {
36603
- const dispatch = client();
36604
- try {
36605
- return { kind: "stored", stored: await ask(dispatch) };
36606
- } catch (error) {
36607
- const routeAbsent = roundTripRouteAbsent(error);
36608
- if (!routeAbsent && error instanceof DispatchServiceError && error.textRefusal) {
36609
- return { kind: "refused", refusal: error };
36610
- }
36611
- return {
36612
- kind: "unanswered",
36613
- failure: error instanceof DispatchAnswerNotKeptError ? `${route} wrote nothing, and Dispatch kept no copy of its answer (${error.code})` : `${route} failed with ${messageFor(error)}`,
36614
- error,
36615
- routeAbsent
36616
- };
36617
- }
36618
- }
36619
- async function storedTextCheck(client, tool, name, content, force) {
36620
- const tooLarge = documentTooLarge(content);
36621
- if (tooLarge !== undefined)
36622
- return { kind: "refused", refusal: tooLarge };
36623
- if (content === "")
36624
- return { kind: "kept" };
36625
- const answer = await askRoundTrip(client, MARKDOWN_ROUND_TRIP, (dispatch) => dispatch.markdownRoundTrip(content, !force));
36626
- const blank = goBlankPattern.test(content);
36627
- switch (answer.kind) {
36628
- case "refused":
36629
- return answer;
36630
- case "unanswered":
36631
- return blank || answer.routeAbsent ? unchecked(answer) : { kind: "failed", failure: answer.failure, error: answer.error };
36632
- case "stored": {
36633
- if (blank)
36634
- return { kind: "kept" };
36635
- const upload = storedUpload(content, answer.stored, name);
36636
- if ("refusal" in upload) {
36637
- return { kind: "refused", refusal: new ToolInputError(tool, [upload.refusal]) };
36638
- }
36639
- return upload.reordered.length === 0 ? { kind: "kept" } : { kind: "reordered", sent: upload.sent, lines: upload.reordered };
36640
- }
36641
- }
36642
- }
36643
- async function storedFileCheck(client, bytes, force) {
36644
- const answer = await askRoundTrip(client, FILE_ROUND_TRIP, (dispatch) => dispatch.fileRoundTrip(bytes, !force));
36645
- switch (answer.kind) {
36646
- case "stored":
36647
- return { kind: "kept" };
36648
- case "refused":
36649
- return answer;
36650
- case "unanswered":
36651
- return unchecked(answer);
36652
- }
36653
- }
36654
- function artifactTextCheck(upload) {
36655
- const { tool, name, content, bytes, force } = upload;
36656
- if (content !== undefined) {
36657
- return () => storedTextCheck(upload.textClient, tool, name, content, force);
36881
+ async function commandContext(session) {
36882
+ const { input, ownerArguments, pictures } = session;
36883
+ const actor = toolActor(await resolveOrigin(input.env ?? process.env, input.exec ?? defaultExec, input.cwd), input);
36884
+ const client = session.newClient();
36885
+ const { owner, documentOwner, resolveDocument } = await documentTargets(client, ownerArguments);
36886
+ const issueArgument = optionalString(input.args, "issue");
36887
+ const refText = optionalString(ownerArguments.args, "ref");
36888
+ if (input.tool !== "dispatch_ask" && owner?.kind === "issue" && issueArgument !== undefined && refText !== undefined && ownerArguments.ref?.owner.kind === "issue" && owner.issue !== ownerArguments.ref.owner.issue) {
36889
+ throw new ToolInputError(input.tool, [
36890
+ `issue ${issueArgument} and ref ${refText} name two owners; --ref ${refText} alone acts on ${ownerArguments.ref.owner.issue}, and --issue ${issueArgument} alone acts on ${owner.issue}`
36891
+ ]);
36658
36892
  }
36659
- if (bytes !== undefined)
36660
- return () => storedFileCheck(upload.fileClient, bytes, force);
36661
- return;
36893
+ const issue = () => {
36894
+ if (owner?.kind !== "issue")
36895
+ throw new Error("issue is required");
36896
+ return owner.issue;
36897
+ };
36898
+ const postWithPictures = (text, owner, upload) => textWithPictures(text, pictures, owner, (picture) => upload(picture).catch((error) => {
36899
+ if (!(error instanceof DispatchWriteLandedError))
36900
+ throw error;
36901
+ throw new Error(`${error.message} That was a picture uploaded before this call's own write, so nothing else was written: run the call again, which uploads it as its next version.`, { cause: error });
36902
+ }), actor);
36903
+ const writePictures = (resolved, text) => {
36904
+ if (resolved?.owner.kind === "project") {
36905
+ const { project } = resolved.owner;
36906
+ return postWithPictures(text, project, (upload) => client.projectArtifact(project, upload));
36907
+ }
36908
+ const issueKey = issue();
36909
+ return postWithPictures(text, issueKey, (upload) => client.artifact(issueKey, upload));
36910
+ };
36911
+ const { hostSession } = session;
36912
+ return {
36913
+ ...session,
36914
+ client,
36915
+ actor,
36916
+ owner,
36917
+ documentOwner,
36918
+ resolveDocument,
36919
+ issue,
36920
+ postWithPictures,
36921
+ writePictures,
36922
+ shown: hostSession ? shownPictures(hostSession) : undefined
36923
+ };
36662
36924
  }
36663
36925
 
36664
36926
  // ../envoy-client/src/dispatch-commands/render-item.ts
@@ -37092,546 +37354,884 @@ async function resolveAskArgument(tool, args, client, sessionId) {
37092
37354
  const document = await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true });
37093
37355
  return document.artifact.id;
37094
37356
  });
37095
- return { id: resolved, read };
37357
+ return { id: resolved, read };
37358
+ }
37359
+ async function openAsksCommand(context) {
37360
+ const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
37361
+ const client = dispatchClient();
37362
+ const project = optionalString(ownerArguments.args, "project");
37363
+ if (project !== undefined) {
37364
+ const response = await client.openAsksForProject(project);
37365
+ return { text: formatOpenAsksSummary(response, linkBase, project), details: { ...response } };
37366
+ }
37367
+ const sessionId = input.sessionId?.trim();
37368
+ if (!sessionId)
37369
+ throw new Error("host session id is required for dispatch open-asks");
37370
+ const response = await client.openAsks(sessionId);
37371
+ return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
37372
+ }
37373
+ async function askCommand(context) {
37374
+ const {
37375
+ args,
37376
+ client,
37377
+ actor,
37378
+ input,
37379
+ linkBase,
37380
+ documentOwner,
37381
+ resolveDocument,
37382
+ writePictures,
37383
+ issue
37384
+ } = context;
37385
+ const anchorArgs = asObject(args.anchor);
37386
+ const owner = documentOwner();
37387
+ const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
37388
+ const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
37389
+ const options = args.options;
37390
+ const multiple = optionalBoolean(args, "multiple");
37391
+ const urgency = askUrgency(args);
37392
+ const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
37393
+ const question = await writePictures(resolved, askQuestionWithRef(args));
37394
+ const askInput = {
37395
+ question,
37396
+ ...Array.isArray(options) ? { options } : {},
37397
+ ...multiple === undefined ? {} : { multiple },
37398
+ ...urgency === undefined ? {} : { urgency },
37399
+ ...anchored === undefined ? {} : { anchor: anchored },
37400
+ actor
37401
+ };
37402
+ const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
37403
+ const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
37404
+ const checkLines = relatedCheckLines(ask.advice?.suggestions, {
37405
+ project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
37406
+ text: stringArg(args, "question"),
37407
+ linkBase
37408
+ });
37409
+ const reviewLines = await otherAdviceLines(() => standingReviewLines(ask.advice));
37410
+ const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
37411
+ const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
37412
+ const asked = waitsOnPerson(ask);
37413
+ return {
37414
+ text: [
37415
+ `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
37416
+ ...checkLines,
37417
+ ...reviewLines,
37418
+ ...declinedLines,
37419
+ await followsAsk(askOwner, input.subscriptions),
37420
+ ...adviceLines
37421
+ ].join(`
37422
+ `),
37423
+ details: {
37424
+ ...await followedAskDetails(client, ask, resolved?.artifact),
37425
+ ...ask.advice === undefined ? {} : { advice: ask.advice }
37426
+ }
37427
+ };
37428
+ }
37429
+ async function editAskCommand(context) {
37430
+ const { args, client, actor, input } = context;
37431
+ const question = optionalString(args, "question");
37432
+ const options = args.options;
37433
+ const multiple = optionalBoolean(args, "multiple");
37434
+ const urgency = askUrgency(args);
37435
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
37436
+ const ask = await client.editAsk(id, {
37437
+ ...question === undefined ? {} : { question },
37438
+ ...Array.isArray(options) ? { options } : {},
37439
+ ...multiple === undefined ? {} : { multiple },
37440
+ ...urgency === undefined ? {} : { urgency },
37441
+ actor
37442
+ });
37443
+ return {
37444
+ text: `Ask edited: ${ask.question}`,
37445
+ details: await askOwnerDetails(client, ask)
37446
+ };
37447
+ }
37448
+ async function resolveAskCommand(context) {
37449
+ const { args, client, actor, input } = context;
37450
+ const kind = stringArg(args, "kind");
37451
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
37452
+ const ask = await client.resolveAsk(id, {
37453
+ kind,
37454
+ reason: stringArg(args, "reason"),
37455
+ actor
37456
+ });
37457
+ if (ask.resolution === undefined)
37458
+ throw new Error("resolved ask is missing its resolution");
37459
+ return {
37460
+ text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
37461
+ details: await askOwnerDetails(client, ask)
37462
+ };
37463
+ }
37464
+ async function followCommand(context) {
37465
+ const { args, client, actor, input } = context;
37466
+ const sessionId = input.sessionId?.trim();
37467
+ if (!sessionId)
37468
+ throw new Error("host session id is required for dispatch follow");
37469
+ const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
37470
+ const action = stringArg(args, "action");
37471
+ if (action === "unfollow") {
37472
+ await client.unfollowAsk(ask, sessionId, actor);
37473
+ return { text: `Unfollowed ask ${ask}.`, details: { ask } };
37474
+ }
37475
+ const read = refRead ?? await client.getAsk(ask);
37476
+ await client.followAsk(ask, sessionId, actor);
37477
+ return {
37478
+ text: `Following ask ${ask}: its answer and replies reach this session directly.`,
37479
+ details: await followedAskDetails(client, read.ask)
37480
+ };
37481
+ }
37482
+
37483
+ // ../envoy-client/src/dispatch-commands/conversation.ts
37484
+ async function resolveCommentArgument(tool, reference, client) {
37485
+ const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
37486
+ if (ref === null)
37487
+ return { id: reference };
37488
+ let id = reference;
37489
+ let document;
37490
+ if (ref.owner.kind === "issue") {
37491
+ const issueKey = ref.owner.issue;
37492
+ id = await resolveIdPrefix(tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
37493
+ } else {
37494
+ const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
37495
+ document = artifact;
37496
+ id = await resolveIdPrefix(tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
37497
+ }
37498
+ const read = await client.getComment(id).catch(async (error) => {
37499
+ throw await refuseMissingOfRef(error, "comment", id, ref.owner, refOwnerName(ref), readRefOwner(client, ref.owner, async () => document));
37500
+ });
37501
+ await refuseItemOffRef(tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
37502
+ return { id, ...document === undefined ? {} : { document } };
37503
+ }
37504
+ async function resolveMessageArgument(tool, argument, reference, client, session) {
37505
+ const named = messageArgumentId(reference);
37506
+ if (named === undefined)
37507
+ throw new ToolInputError(tool, [messageArgumentProblem(argument)]);
37508
+ const ref = named.ref;
37509
+ if (ref === undefined)
37510
+ return named.id;
37511
+ const issueKey = ref.owner.issue;
37512
+ const id = await resolveIdPrefix(tool, "message", named.id, issueKey, async () => (await client.issueMessages(issueKey)).flatMap((thread) => [
37513
+ thread.message,
37514
+ ...thread.replies ?? []
37515
+ ]));
37516
+ const read = await client.getMessageThread(id, session === "" ? undefined : session).catch(async (error) => {
37517
+ throw await refuseMissingOfRef(error, "message", id, ref.owner, issueKey, () => client.getIssue(issueKey));
37518
+ });
37519
+ await refuseItemOffRef(tool, "message", ref, reference, { id, issue_key: read.message.issue_key }, async () => "");
37520
+ return id;
37521
+ }
37522
+ function messageIssueKey(message) {
37523
+ if (message.issue_key === null)
37524
+ throw new Error("the corrected message names no issue");
37525
+ return message.issue_key;
37526
+ }
37527
+ async function resolveCommentCommand(context) {
37528
+ const { args, client, actor, input } = context;
37529
+ const reference = stringArg(args, "comment");
37530
+ const { id, document } = await resolveCommentArgument(input.tool, reference, client);
37531
+ const comment = await client.resolveComment(id, actor).catch((error) => {
37532
+ throw refuseMissingPost(error, { kind: "comment", id });
37533
+ });
37534
+ const { label, details } = await commentOwnerResult(client, comment, document);
37535
+ return { text: `Resolved comment ${comment.id} on ${label}.`, details };
37536
+ }
37537
+ async function editCommentCommand(context) {
37538
+ const { args, client, actor, input, configUrl } = context;
37539
+ const reference = stringArg(args, "comment");
37540
+ const { id, document } = await resolveCommentArgument(input.tool, reference, client);
37541
+ const comment = await throughPostCorrections(input.tool, configUrl, client.editComment(id, { body: stringArg(args, "body"), actor }), { kind: "comment", id });
37542
+ const { label, details } = await commentOwnerResult(client, comment, document);
37543
+ return { text: `Edited comment ${comment.id} on ${label}.`, details };
37544
+ }
37545
+ var DELETED_MESSAGE_READS = "No read of it gives its body again; the events of a reply's creation and of each edit of the " + "reply written before the delete keep the preview of it they carried.";
37546
+ var DELETED_COMMENT_READS = "No read of it gives its body again; the events of a reply's creation and of each edit of the " + "reply written before the delete keep the preview of it they carried, and the document's " + "events written before the delete keep the name an accepted suggestion gave its version.";
37547
+ async function throughDelete(context, call, post) {
37548
+ try {
37549
+ return await throughPostCorrections(context.input.tool, context.configUrl, call, post);
37550
+ } catch (error) {
37551
+ if (dispatchAnswered(error, 409) && error.code === "DELETE_CONTENDED") {
37552
+ throw refusalWithCode(error, `${post.kind} ${post.id} stands: run the same dispatch delete-${post.kind} command again`);
37553
+ }
37554
+ throw error;
37555
+ }
37556
+ }
37557
+ async function deleteCommentCommand(context) {
37558
+ const { args, client, actor, input } = context;
37559
+ const reference = stringArg(args, "comment");
37560
+ const { id, document } = await resolveCommentArgument(input.tool, reference, client);
37561
+ const comment = await throughDelete(context, client.deleteComment(id, actor), {
37562
+ kind: "comment",
37563
+ id
37564
+ });
37565
+ const { label, details } = await commentOwnerResult(client, comment, document);
37566
+ return {
37567
+ text: `Deleted comment ${comment.id} on ${label}. ${DELETED_COMMENT_READS}`,
37568
+ details
37569
+ };
37096
37570
  }
37097
- async function openAsksCommand(context) {
37098
- const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
37099
- const client = dispatchClient();
37100
- const project = optionalString(ownerArguments.args, "project");
37101
- if (project !== undefined) {
37102
- const response = await client.openAsksForProject(project);
37103
- return { text: formatOpenAsksSummary(response, linkBase, project), details: { ...response } };
37104
- }
37105
- const sessionId = input.sessionId?.trim();
37106
- if (!sessionId)
37107
- throw new Error("host session id is required for dispatch open-asks");
37108
- const response = await client.openAsks(sessionId);
37109
- return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
37571
+ async function editMessageCommand(context) {
37572
+ const { args, client, actor, input, configUrl, hostSession } = context;
37573
+ const id = await resolveMessageArgument(input.tool, "message", stringArg(args, "message"), client, hostSession);
37574
+ const message = await throughPostCorrections(input.tool, configUrl, client.editMessage(id, { body: stringArg(args, "body"), actor }), { kind: "message", id });
37575
+ const issue = messageIssueKey(message);
37576
+ return {
37577
+ text: `Edited message ${message.id} on ${issue}.`,
37578
+ details: { issue, message: message.id }
37579
+ };
37110
37580
  }
37111
- async function askCommand(context) {
37112
- const {
37113
- args,
37114
- client,
37115
- actor,
37116
- input,
37117
- linkBase,
37118
- documentOwner,
37119
- resolveDocument,
37120
- writePictures,
37121
- issue
37122
- } = context;
37123
- const anchorArgs = asObject(args.anchor);
37581
+ async function deleteMessageCommand(context) {
37582
+ const { args, client, actor, input, hostSession } = context;
37583
+ const id = await resolveMessageArgument(input.tool, "message", stringArg(args, "message"), client, hostSession);
37584
+ const message = await throughDelete(context, client.deleteMessage(id, actor), {
37585
+ kind: "message",
37586
+ id
37587
+ });
37588
+ const issue = messageIssueKey(message);
37589
+ return {
37590
+ text: `Deleted message ${message.id} on ${issue}. ${DELETED_MESSAGE_READS}`,
37591
+ details: { issue, message: message.id }
37592
+ };
37593
+ }
37594
+ async function commentCommand(context) {
37595
+ const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
37596
+ const artifactReference = optionalString(args, "artifact");
37124
37597
  const owner = documentOwner();
37125
- const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
37126
37598
  const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
37127
- const options = args.options;
37128
- const multiple = optionalBoolean(args, "multiple");
37129
- const urgency = askUrgency(args);
37130
- const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
37131
- const question = await writePictures(resolved, askQuestionWithRef(args));
37132
- const askInput = {
37133
- question,
37134
- ...Array.isArray(options) ? { options } : {},
37135
- ...multiple === undefined ? {} : { multiple },
37136
- ...urgency === undefined ? {} : { urgency },
37599
+ const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
37600
+ const replyTo = itemReplyTo(args, "reply_to");
37601
+ const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
37602
+ const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
37603
+ const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
37604
+ const requestedTurn = optionalString(args, "turn");
37605
+ const mentions = optionalStringArray(args, "mentions");
37606
+ const body = await writePictures(resolved, stringArg(args, "body"));
37607
+ const commentInput = {
37608
+ body,
37137
37609
  ...anchored === undefined ? {} : { anchor: anchored },
37610
+ ...replyTo === undefined ? {} : { reply_to: replyTo.id },
37611
+ ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
37612
+ ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
37613
+ ...requestedTurn === undefined ? {} : { turn: requestedTurn },
37614
+ ...mentions === undefined ? {} : { mentions: mentions.map((target) => ({ target })) },
37138
37615
  actor
37139
37616
  };
37140
- const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
37141
- const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
37142
- const checkLines = relatedCheckLines(ask.advice?.suggestions, {
37143
- project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
37144
- text: stringArg(args, "question"),
37145
- linkBase
37617
+ const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
37618
+ const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
37619
+ const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
37620
+ const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
37621
+ isAskReply: replyToAsk !== undefined,
37622
+ replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
37146
37623
  });
37147
- const reviewLines = await otherAdviceLines(() => standingReviewLines(ask.advice));
37148
- const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
37149
- const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
37150
- const asked = waitsOnPerson(ask);
37624
+ if (replyToAsk !== undefined) {
37625
+ const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
37626
+ const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
37627
+ return {
37628
+ text: [
37629
+ `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
37630
+ ...moved === undefined ? [] : [moved],
37631
+ ...adviceLines
37632
+ ].join(`
37633
+ `),
37634
+ details: {
37635
+ ...commentDetails,
37636
+ ask: replyToAsk,
37637
+ follows: { ask: replyToAsk },
37638
+ ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
37639
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
37640
+ }
37641
+ };
37642
+ }
37151
37643
  return {
37152
37644
  text: [
37153
- `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
37154
- ...checkLines,
37155
- ...reviewLines,
37156
- ...declinedLines,
37157
- await followsAsk(askOwner, input.subscriptions),
37645
+ `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
37158
37646
  ...adviceLines
37159
37647
  ].join(`
37160
37648
  `),
37161
37649
  details: {
37162
- ...await followedAskDetails(client, ask, resolved?.artifact),
37163
- ...ask.advice === undefined ? {} : { advice: ask.advice }
37650
+ ...commentDetails,
37651
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
37164
37652
  }
37165
37653
  };
37166
37654
  }
37167
- async function editAskCommand(context) {
37168
- const { args, client, actor, input } = context;
37169
- const question = optionalString(args, "question");
37170
- const options = args.options;
37171
- const multiple = optionalBoolean(args, "multiple");
37172
- const urgency = askUrgency(args);
37173
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
37174
- const ask = await client.editAsk(id, {
37175
- ...question === undefined ? {} : { question },
37176
- ...Array.isArray(options) ? { options } : {},
37177
- ...multiple === undefined ? {} : { multiple },
37178
- ...urgency === undefined ? {} : { urgency },
37655
+ async function suggestCommand(context) {
37656
+ const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
37657
+ const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
37658
+ const anchored = anchor(resolved.artifact, args);
37659
+ if (anchored === undefined)
37660
+ throw new Error("quote is required");
37661
+ const body = optionalString(args, "body");
37662
+ const suggestionInput = {
37663
+ ...body === undefined ? {} : { body },
37664
+ anchor: anchored,
37665
+ replace_with: stringArg(args, "replace_with"),
37666
+ actor
37667
+ };
37668
+ const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
37669
+ return {
37670
+ text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
37671
+ details: writeResultDetails(resolved, { comment: comment.id })
37672
+ };
37673
+ }
37674
+ function conversationReadBack(messageId) {
37675
+ return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
37676
+ }
37677
+ async function messageCommand(context) {
37678
+ const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
37679
+ const target = messageInReplyTo(args);
37680
+ const inReplyTo = target?.id;
37681
+ const written = stringArg(args, "body");
37682
+ if (owner === null && inReplyTo !== undefined) {
37683
+ let body = written;
37684
+ if (pictures.length > 0) {
37685
+ const sessionId = input.sessionId?.trim();
37686
+ if (!sessionId) {
37687
+ throw new Error("host session id is required to send pictures in a direct-message reply");
37688
+ }
37689
+ body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
37690
+ }
37691
+ const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
37692
+ if (reply.duplicate === true && reply.body === body) {
37693
+ return {
37694
+ text: `Dispatch already has this exact text in the conversation (message ${reply.id}); ` + "nothing new was posted. Send different text if you have more to say.",
37695
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
37696
+ };
37697
+ }
37698
+ if (reply.body !== body) {
37699
+ return {
37700
+ text: `Message ${inReplyTo} was already answered by message ${reply.id}; Dispatch kept ` + "that reply and posted nothing. Wait for their next message rather than answering " + "this one again.",
37701
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
37702
+ };
37703
+ }
37704
+ const readBack = conversationReadBack(inReplyTo);
37705
+ const parent = reply.in_reply_to ?? undefined;
37706
+ const follows = parent === inReplyTo ? undefined : parent;
37707
+ return {
37708
+ text: follows === undefined ? `Replied to message ${inReplyTo} with message ${reply.id}. ${readBack}` : `Replied to message ${inReplyTo} with message ${reply.id}, a follow-up threaded ` + `under your reply ${follows}. ${readBack}`,
37709
+ details: {
37710
+ message: reply.id,
37711
+ in_reply_to: inReplyTo,
37712
+ posted: true,
37713
+ ...follows === undefined ? {} : { follows }
37714
+ }
37715
+ };
37716
+ }
37717
+ const issueKey = issue();
37718
+ const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
37719
+ const message = await client.message(issueKey, {
37720
+ body,
37721
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
37722
+ ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
37179
37723
  actor
37180
37724
  });
37725
+ const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
37726
+ const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
37727
+ return {
37728
+ text: [
37729
+ `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
37730
+ ...adviceLines
37731
+ ].join(`
37732
+ `),
37733
+ details: {
37734
+ issue: issueKey,
37735
+ message: message.id,
37736
+ ...message.advice === undefined ? {} : { advice: message.advice }
37737
+ }
37738
+ };
37739
+ }
37740
+ function arrivalText(attempt) {
37741
+ if (attempt === undefined)
37742
+ return "Dispatch recorded no delivery attempt for it";
37743
+ if (attempt.state === "failed") {
37744
+ return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
37745
+ }
37746
+ if (attempt.state === "pending")
37747
+ return "its delivery is still on its way";
37748
+ if (attempt.state === "queued") {
37749
+ return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
37750
+ }
37751
+ return `it reached that session as ${attempt.delivery}`;
37752
+ }
37753
+ async function sendToAgentCommand(context) {
37754
+ const { args, client } = context;
37755
+ const session = stringArg(args, "session");
37756
+ const inReplyTo = optionalString(args, "in_reply_to");
37757
+ const message = await client.agentMessage(session, {
37758
+ body: stringArg(args, "body"),
37759
+ delivery: stringArg(args, "delivery"),
37760
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
37761
+ });
37762
+ const attempt = message.deliveries?.at(-1);
37763
+ const readBack = conversationReadBack(message.id);
37764
+ const arrival = arrivalText(attempt);
37181
37765
  return {
37182
- text: `Ask edited: ${ask.question}`,
37183
- details: await askOwnerDetails(client, ask)
37766
+ text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
37767
+ details: {
37768
+ session,
37769
+ message: message.id,
37770
+ ...attempt === undefined ? {} : { delivery: attempt.state },
37771
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
37772
+ }
37184
37773
  };
37185
37774
  }
37186
- async function resolveAskCommand(context) {
37187
- const { args, client, actor, input } = context;
37188
- const kind = stringArg(args, "kind");
37189
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
37190
- const ask = await client.resolveAsk(id, {
37191
- kind,
37192
- reason: stringArg(args, "reason"),
37193
- actor
37194
- });
37195
- if (ask.resolution === undefined)
37196
- throw new Error("resolved ask is missing its resolution");
37775
+
37776
+ // ../envoy-client/src/dispatch-commands/deploy.ts
37777
+ function deployText(deploy) {
37778
+ const link = deploy.url === "" ? "" : ` ${deploy.url}`;
37779
+ return `${deploy.program}: ${deploy.commit} since ${deploy.deployed_at} (source: ${deploy.source}, recorded by ${actorText(deploy.recorded_by)}).${link}`;
37780
+ }
37781
+ async function deployCommand(context) {
37782
+ const { args, client } = context;
37783
+ const input = {
37784
+ repo: stringArg(args, "repo"),
37785
+ program: stringArg(args, "program"),
37786
+ commit: stringArg(args, "commit"),
37787
+ ...defined("deployed_at", optionalString(args, "deployed_at")),
37788
+ ...defined("url", optionalString(args, "url"))
37789
+ };
37790
+ const result = await client.recordDeploy(input);
37197
37791
  return {
37198
- text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
37199
- details: await askOwnerDetails(client, ask)
37792
+ text: optionalBoolean(args, "json") === true ? JSON.stringify(result, null, 2) : deployText(result.deploy),
37793
+ details: { repo: input.repo, deploy: result.deploy }
37200
37794
  };
37201
37795
  }
37202
- async function followCommand(context) {
37203
- const { args, client, actor, input } = context;
37204
- const sessionId = input.sessionId?.trim();
37205
- if (!sessionId)
37206
- throw new Error("host session id is required for dispatch follow");
37207
- const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
37208
- const action = stringArg(args, "action");
37209
- if (action === "unfollow") {
37210
- await client.unfollowAsk(ask, sessionId, actor);
37211
- return { text: `Unfollowed ask ${ask}.`, details: { ask } };
37212
- }
37213
- const read = refRead ?? await client.getAsk(ask);
37214
- await client.followAsk(ask, sessionId, actor);
37796
+ async function deploysCommand(context) {
37797
+ const { args, client } = context;
37798
+ const result = await client.deploys(stringArg(args, "repo"));
37799
+ const deploys = result.deploys ?? [];
37215
37800
  return {
37216
- text: `Following ask ${ask}: its answer and replies reach this session directly.`,
37217
- details: await followedAskDetails(client, read.ask)
37801
+ text: optionalBoolean(args, "json") === true ? JSON.stringify(result, null, 2) : deploys.length === 0 ? `Dispatch holds no deploys for ${result.repo}.` : deploys.map(deployText).join(`
37802
+ `),
37803
+ details: { repo: result.repo, deploys }
37218
37804
  };
37219
37805
  }
37220
37806
 
37221
- // ../envoy-client/src/dispatch-commands/conversation.ts
37222
- async function resolveCommentArgument(tool, reference, client) {
37223
- const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
37224
- if (ref === null)
37225
- return { id: reference };
37226
- let id = reference;
37227
- let document;
37228
- if (ref.owner.kind === "issue") {
37229
- const issueKey = ref.owner.issue;
37230
- id = await resolveIdPrefix(tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
37231
- } else {
37232
- const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
37233
- document = artifact;
37234
- id = await resolveIdPrefix(tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
37235
- }
37236
- const read = await client.getComment(id).catch(async (error) => {
37237
- throw await refuseMissingOfRef(error, "comment", id, ref.owner, refOwnerName(ref), readRefOwner(client, ref.owner, async () => document));
37238
- });
37239
- await refuseItemOffRef(tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
37240
- return { id, ...document === undefined ? {} : { document } };
37807
+ // ../envoy-client/src/dispatch-commands/documents.ts
37808
+ import { resolve as resolvePath3 } from "path";
37809
+
37810
+ // ../envoy-client/src/dispatch-commands/open-decision-blocks.ts
37811
+ async function blockAsks(client, resolved, state) {
37812
+ const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
37813
+ return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
37241
37814
  }
37242
- async function resolveMessageArgument(tool, argument, reference, client, session) {
37243
- const named = messageArgumentId(reference);
37244
- if (named === undefined)
37245
- throw new ToolInputError(tool, [messageArgumentProblem(argument)]);
37246
- const ref = named.ref;
37247
- if (ref === undefined)
37248
- return named.id;
37249
- const issueKey = ref.owner.issue;
37250
- const id = await resolveIdPrefix(tool, "message", named.id, issueKey, async () => (await client.issueMessages(issueKey)).flatMap((thread) => [
37251
- thread.message,
37252
- ...thread.replies ?? []
37253
- ]));
37254
- const read = await client.getMessageThread(id, session === "" ? undefined : session).catch(async (error) => {
37255
- throw await refuseMissingOfRef(error, "message", id, ref.owner, issueKey, () => client.getIssue(issueKey));
37815
+ var OPEN_BLOCK_ASK_THE_HUMAN = "Tell the human which block is open and ask them to answer it or to waive it. Once it is answered, it settles into a version on its own in about two seconds.";
37816
+ var OPEN_BLOCK_WAIVED = "If they waive it, close the block with dispatch resolve-ask (--kind resolved, their words as the --reason)";
37817
+ async function refuseOpenDecisionBlocks(client, resolved, refusal) {
37818
+ const artifact = resolved.artifact;
37819
+ const latest = artifact.approval?.latest_version;
37820
+ if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
37821
+ return;
37822
+ const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
37823
+ if (blocks.length === 0)
37824
+ return;
37825
+ const [documentAsks, version] = await Promise.all([
37826
+ blockAsks(client, resolved),
37827
+ client.docRead(artifact.id, latest)
37828
+ ]);
37829
+ const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
37830
+ const lines = version.markdown.split(`
37831
+ `);
37832
+ const stillOpen = (named, state) => state === "answered" ? `${named}, answered but still open in version ${latest}: it settles into a version on its own in about two seconds; wait for that version` : `${named}, ${state} but still open in version ${latest}: write the decision into the text with dispatch doc-edit, which writes a version that carries it`;
37833
+ const open = blocks.flatMap((block) => {
37834
+ const ask = asks.get(block.id);
37835
+ const id = typedBlockIdAttribute(block.id);
37836
+ const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
37837
+ const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
37838
+ const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
37839
+ if (states.length === 0)
37840
+ return [`${named}, which version ${latest} does not hold yet`];
37841
+ if (!states.includes("open") && states.some((state) => state !== undefined))
37842
+ return [];
37843
+ if (ask !== undefined)
37844
+ return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
37845
+ const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
37846
+ const sourceId = attribute("copied_from");
37847
+ const document = attribute("copied_from_document");
37848
+ if (sourceId === undefined || document === undefined) {
37849
+ return [`${named}, whose ask Dispatch has not opened yet`];
37850
+ }
37851
+ const source = parseDispatchRef(document);
37852
+ const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
37853
+ const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
37854
+ return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
37256
37855
  });
37257
- await refuseItemOffRef(tool, "message", ref, reference, { id, issue_key: read.message.issue_key }, async () => "");
37258
- return id;
37856
+ if (open.length === 0)
37857
+ return;
37858
+ const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
37859
+ throw new Error([
37860
+ `${refusal.call} was not called: ${artifact.name} (version ${latest}) has ${count}. ${refusal.effect}`,
37861
+ ...open.map((line) => `- ${line}`),
37862
+ refusal.remedy
37863
+ ].join(`
37864
+ `));
37259
37865
  }
37260
- function messageIssueKey(message) {
37261
- if (message.issue_key === null)
37262
- throw new Error("the corrected message names no issue");
37263
- return message.issue_key;
37866
+ async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
37867
+ const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
37868
+ if (removing.length === 0)
37869
+ return;
37870
+ const artifact = resolved.artifact;
37871
+ const blocks = await client.artifactBlocks(artifact.id);
37872
+ const askBlocks = blocks.filter((block) => block.type === "ask");
37873
+ const removed = new Set;
37874
+ for (const operation of removing) {
37875
+ const target = blocks.find((block) => block.id === operation.block);
37876
+ if (target === undefined)
37877
+ continue;
37878
+ for (const block of askBlocks) {
37879
+ if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
37880
+ removed.add(block.id);
37881
+ }
37882
+ }
37883
+ }
37884
+ if (removed.size === 0)
37885
+ return;
37886
+ const asks = await blockAsks(client, resolved, "open");
37887
+ const open = asks.filter((ask) => removed.has(ask.block_id));
37888
+ if (open.length === 0)
37889
+ return;
37890
+ const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
37891
+ throw new Error([
37892
+ `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
37893
+ ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
37894
+ "A decision block leaves the document once its ask is answered or resolved. Until then, reword it with replace, relocate it with move, or change its question, options, urgency or multiple with dispatch edit-ask if you asked it; each keeps it."
37895
+ ].join(`
37896
+ `));
37264
37897
  }
37265
- async function resolveCommentCommand(context) {
37266
- const { args, client, actor, input } = context;
37267
- const reference = stringArg(args, "comment");
37268
- const { id, document } = await resolveCommentArgument(input.tool, reference, client);
37269
- const comment = await client.resolveComment(id, actor).catch((error) => {
37270
- throw refuseMissingPost(error, { kind: "comment", id });
37271
- });
37272
- const { label, details } = await commentOwnerResult(client, comment, document);
37273
- return { text: `Resolved comment ${comment.id} on ${label}.`, details };
37898
+
37899
+ // ../envoy-client/src/dispatch-commands/stored-text.ts
37900
+ import { resolve as resolvePath2 } from "path";
37901
+
37902
+ // ../envoy-client/src/dispatch-commands/stored-spelling.ts
37903
+ function headedOpener(line) {
37904
+ for (let at = 0;at < line.length; at += Math.max(1, runOf(line, at, ":"))) {
37905
+ const brace = typedFenceBrace(line, at);
37906
+ if (brace === -1)
37907
+ continue;
37908
+ const opener = typedOpenerAt(line, at);
37909
+ return opener === undefined ? undefined : { ...opener, head: line.slice(0, brace + 1) };
37910
+ }
37911
+ return;
37274
37912
  }
37275
- async function editCommentCommand(context) {
37276
- const { args, client, actor, input, configUrl } = context;
37277
- const reference = stringArg(args, "comment");
37278
- const { id, document } = await resolveCommentArgument(input.tool, reference, client);
37279
- const comment = await throughPostCorrections(input.tool, configUrl, client.editComment(id, { body: stringArg(args, "body"), actor }), { kind: "comment", id });
37280
- const { label, details } = await commentOwnerResult(client, comment, document);
37281
- return { text: `Edited comment ${comment.id} on ${label}.`, details };
37913
+ function attributesByName(attributes) {
37914
+ const byName = new Map(attributes.map((attribute) => [attribute.name, attribute.text]));
37915
+ return byName.size === attributes.length ? byName : undefined;
37282
37916
  }
37283
- var DELETED_MESSAGE_READS = "No read of it gives its body again; the events of a reply's creation and of each edit of the " + "reply written before the delete keep the preview of it they carried.";
37284
- var DELETED_COMMENT_READS = "No read of it gives its body again; the events of a reply's creation and of each edit of the " + "reply written before the delete keep the preview of it they carried, and the document's " + "events written before the delete keep the name an accepted suggestion gave its version.";
37285
- async function throughDelete(context, call, post) {
37286
- try {
37287
- return await throughPostCorrections(context.input.tool, context.configUrl, call, post);
37288
- } catch (error) {
37289
- if (dispatchAnswered(error, 409) && error.code === "DELETE_CONTENDED") {
37290
- throw refusalWithCode(error, `${post.kind} ${post.id} stands: run the same dispatch delete-${post.kind} command again`);
37291
- }
37292
- throw error;
37917
+ function inStoredOrder(given, stored) {
37918
+ const written = attributesByName(given.attributes);
37919
+ if (written === undefined || attributesByName(stored.attributes) === undefined || stored.attributes.length !== given.attributes.length) {
37920
+ return;
37293
37921
  }
37922
+ let line = `${given.head}${given.gaps[0] ?? ""}`;
37923
+ for (const [index, attribute] of stored.attributes.entries()) {
37924
+ const text = written.get(attribute.name);
37925
+ if (text === undefined)
37926
+ return;
37927
+ line += `${text}${given.gaps[index + 1] ?? ""}`;
37928
+ }
37929
+ return `${line}}`;
37294
37930
  }
37295
- async function deleteCommentCommand(context) {
37296
- const { args, client, actor, input } = context;
37297
- const reference = stringArg(args, "comment");
37298
- const { id, document } = await resolveCommentArgument(input.tool, reference, client);
37299
- const comment = await throughDelete(context, client.deleteComment(id, actor), {
37300
- kind: "comment",
37301
- id
37302
- });
37303
- const { label, details } = await commentOwnerResult(client, comment, document);
37304
- return {
37305
- text: `Deleted comment ${comment.id} on ${label}. ${DELETED_COMMENT_READS}`,
37306
- details
37307
- };
37308
- }
37309
- async function editMessageCommand(context) {
37310
- const { args, client, actor, input, configUrl, hostSession } = context;
37311
- const id = await resolveMessageArgument(input.tool, "message", stringArg(args, "message"), client, hostSession);
37312
- const message = await throughPostCorrections(input.tool, configUrl, client.editMessage(id, { body: stringArg(args, "body"), actor }), { kind: "message", id });
37313
- const issue = messageIssueKey(message);
37314
- return {
37315
- text: `Edited message ${message.id} on ${issue}.`,
37316
- details: { issue, message: message.id }
37317
- };
37931
+ function onlyReordered(given, held, stored) {
37932
+ return given !== undefined && stored !== undefined && inStoredOrder(given, stored) === held;
37318
37933
  }
37319
- async function deleteMessageCommand(context) {
37320
- const { args, client, actor, input, hostSession } = context;
37321
- const id = await resolveMessageArgument(input.tool, "message", stringArg(args, "message"), client, hostSession);
37322
- const message = await throughDelete(context, client.deleteMessage(id, actor), {
37323
- kind: "message",
37324
- id
37325
- });
37326
- const issue = messageIssueKey(message);
37327
- return {
37328
- text: `Deleted message ${message.id} on ${issue}. ${DELETED_MESSAGE_READS}`,
37329
- details: { issue, message: message.id }
37330
- };
37934
+ function reorderedBlockLine(line, opener) {
37935
+ const named = `${opener.name} block${opener.id === undefined ? "" : ` ${opener.id}`}`;
37936
+ const order = opener.attributes.map((attribute) => attribute.name).join(", ");
37937
+ return `This upload put the attributes of ${named} (line ${line}) in the order Dispatch stores: ${order}.`;
37331
37938
  }
37332
- async function commentCommand(context) {
37333
- const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
37334
- const artifactReference = optionalString(args, "artifact");
37335
- const owner = documentOwner();
37336
- const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
37337
- const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
37338
- const replyTo = itemReplyTo(args, "reply_to");
37339
- const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
37340
- const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
37341
- const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
37342
- const requestedTurn = optionalString(args, "turn");
37343
- const mentions = optionalStringArray(args, "mentions");
37344
- const body = await writePictures(resolved, stringArg(args, "body"));
37345
- const commentInput = {
37346
- body,
37347
- ...anchored === undefined ? {} : { anchor: anchored },
37348
- ...replyTo === undefined ? {} : { reply_to: replyTo.id },
37349
- ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
37350
- ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
37351
- ...requestedTurn === undefined ? {} : { turn: requestedTurn },
37352
- ...mentions === undefined ? {} : { mentions: mentions.map((target) => ({ target })) },
37353
- actor
37354
- };
37355
- const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
37356
- const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
37357
- const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
37358
- const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
37359
- isAskReply: replyToAsk !== undefined,
37360
- replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
37361
- });
37362
- if (replyToAsk !== undefined) {
37363
- const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
37364
- const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
37365
- return {
37366
- text: [
37367
- `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
37368
- ...moved === undefined ? [] : [moved],
37369
- ...adviceLines
37370
- ].join(`
37371
- `),
37372
- details: {
37373
- ...commentDetails,
37374
- ask: replyToAsk,
37375
- follows: { ask: replyToAsk },
37376
- ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
37377
- ...comment.advice === undefined ? {} : { advice: comment.advice }
37378
- }
37379
- };
37380
- }
37381
- return {
37382
- text: [
37383
- `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
37384
- ...adviceLines
37385
- ].join(`
37386
- `),
37387
- details: {
37388
- ...commentDetails,
37389
- ...comment.advice === undefined ? {} : { advice: comment.advice }
37939
+ function attributesReordered(given, stored) {
37940
+ const written = withoutFinalLineFeed(given).split(`
37941
+ `);
37942
+ const holds = withoutFinalLineFeed(stored).split(`
37943
+ `);
37944
+ if (written.length !== holds.length)
37945
+ return;
37946
+ const lines = [];
37947
+ for (const [index, held] of holds.entries()) {
37948
+ const wrote = written[index];
37949
+ if (wrote === held)
37950
+ continue;
37951
+ const opener = headedOpener(held);
37952
+ if (wrote === undefined || opener === undefined || !onlyReordered(headedOpener(wrote), held, opener)) {
37953
+ return;
37390
37954
  }
37391
- };
37955
+ lines.push(reorderedBlockLine(index + 1, opener));
37956
+ }
37957
+ return lines;
37392
37958
  }
37393
- async function suggestCommand(context) {
37394
- const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
37395
- const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
37396
- const anchored = anchor(resolved.artifact, args);
37397
- if (anchored === undefined)
37398
- throw new Error("quote is required");
37399
- const body = optionalString(args, "body");
37400
- const suggestionInput = {
37401
- ...body === undefined ? {} : { body },
37402
- anchor: anchored,
37403
- replace_with: stringArg(args, "replace_with"),
37404
- actor
37405
- };
37406
- const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
37407
- return {
37408
- text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
37409
- details: writeResultDetails(resolved, { comment: comment.id })
37410
- };
37959
+ var STORED_LINE_QUOTED = 200;
37960
+ function quotedStoredLine(characters, from) {
37961
+ const shown = characters.slice(from, from + STORED_LINE_QUOTED);
37962
+ const quote = JSON.stringify(shown.join(""));
37963
+ const cutAfter = from + shown.length < characters.length;
37964
+ if (from === 0 && !cutAfter)
37965
+ return quote;
37966
+ const cut = from === 0 ? "after" : cutAfter ? "before and after" : "before the last";
37967
+ return `${quote} (cut ${cut} ${shown.length} of its ${characters.length} characters)`;
37411
37968
  }
37412
- function conversationReadBack(messageId) {
37413
- return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
37969
+ function lineWords(line, opener) {
37970
+ const plain = (text) => (text.match(/\s+|\S+/g) ?? []).map((word) => ({ text: word, attribute: false }));
37971
+ if (opener === undefined)
37972
+ return plain(line);
37973
+ const words = plain(opener.head);
37974
+ for (const [index, gap] of opener.gaps.entries()) {
37975
+ if (gap !== "")
37976
+ words.push({ text: gap, attribute: false });
37977
+ const attribute = opener.attributes[index];
37978
+ if (attribute !== undefined)
37979
+ words.push({ text: attribute.text, attribute: true });
37980
+ }
37981
+ words.push({ text: "}", attribute: false });
37982
+ return words;
37414
37983
  }
37415
- async function messageCommand(context) {
37416
- const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
37417
- const target = messageInReplyTo(args);
37418
- const inReplyTo = target?.id;
37419
- const written = stringArg(args, "body");
37420
- if (owner === null && inReplyTo !== undefined) {
37421
- let body = written;
37422
- if (pictures.length > 0) {
37423
- const sessionId = input.sessionId?.trim();
37424
- if (!sessionId) {
37425
- throw new Error("host session id is required to send pictures in a direct-message reply");
37426
- }
37427
- body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
37984
+ function wordText(word, from = 0, characters = Array.from(word.text)) {
37985
+ if (word.attribute)
37986
+ return `the attribute ${word.text}`;
37987
+ return `${/\S/.test(word.text) ? "the word" : "the space"} ${quotedStoredLine(characters, from)}`;
37988
+ }
37989
+ function wordDifference(written, holds) {
37990
+ let before = 0;
37991
+ for (let index = 0;index < Math.max(written.length, holds.length); index += 1) {
37992
+ const given = written[index];
37993
+ const stored = holds[index];
37994
+ if (given !== undefined && stored !== undefined && given.text === stored.text) {
37995
+ before += Array.from(given.text).length;
37996
+ continue;
37428
37997
  }
37429
- const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
37430
- if (reply.duplicate === true && reply.body === body) {
37431
- return {
37432
- text: `Dispatch already has this exact text in the conversation (message ${reply.id}); ` + "nothing new was posted. Send different text if you have more to say.",
37433
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
37434
- };
37998
+ if (given === undefined && stored !== undefined) {
37999
+ return `ends after character ${before}, where Dispatch goes on with ${wordText(stored)}`;
37435
38000
  }
37436
- if (reply.body !== body) {
37437
- return {
37438
- text: `Message ${inReplyTo} was already answered by message ${reply.id}; Dispatch kept ` + "that reply and posted nothing. Wait for their next message rather than answering " + "this one again.",
37439
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
37440
- };
38001
+ if (given !== undefined && stored === undefined) {
38002
+ return `reads ${wordText(given)} at character ${before + 1}, where Dispatch ends the line`;
37441
38003
  }
37442
- const readBack = conversationReadBack(inReplyTo);
37443
- const parent = reply.in_reply_to ?? undefined;
37444
- const follows = parent === inReplyTo ? undefined : parent;
37445
- return {
37446
- text: follows === undefined ? `Replied to message ${inReplyTo} with message ${reply.id}. ${readBack}` : `Replied to message ${inReplyTo} with message ${reply.id}, a follow-up threaded ` + `under your reply ${follows}. ${readBack}`,
37447
- details: {
37448
- message: reply.id,
37449
- in_reply_to: inReplyTo,
37450
- posted: true,
37451
- ...follows === undefined ? {} : { follows }
38004
+ if (given !== undefined && stored !== undefined) {
38005
+ const wrote = Array.from(given.text);
38006
+ const held = Array.from(stored.text);
38007
+ let from = 0;
38008
+ if (!given.attribute && !stored.attribute && Math.max(wrote.length, held.length) > STORED_LINE_QUOTED) {
38009
+ while (from < wrote.length && wrote[from] === held[from])
38010
+ from += 1;
38011
+ const tail = Math.max(0, from - STORED_LINE_QUOTED);
38012
+ if (from === wrote.length) {
38013
+ return `ends ${wordText(given, tail, wrote)} after character ${before + from}, where Dispatch goes on with ${wordText(stored, from, held)}`;
38014
+ }
38015
+ if (from === held.length) {
38016
+ return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch ends ${wordText(stored, tail, held)}`;
38017
+ }
37452
38018
  }
37453
- };
38019
+ return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch stores ${wordText(stored, from, held)}`;
38020
+ }
37454
38021
  }
37455
- const issueKey = issue();
37456
- const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
37457
- const message = await client.message(issueKey, {
37458
- body,
37459
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
37460
- ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
37461
- actor
37462
- });
37463
- const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
37464
- const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
37465
- return {
37466
- text: [
37467
- `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
37468
- ...adviceLines
37469
- ].join(`
37470
- `),
37471
- details: {
37472
- issue: issueKey,
37473
- message: message.id,
37474
- ...message.advice === undefined ? {} : { advice: message.advice }
38022
+ return "differs from the line Dispatch stores";
38023
+ }
38024
+ function attributeDifference(line, given, stored) {
38025
+ const written = attributesByName(given.attributes);
38026
+ if (written === undefined)
38027
+ return;
38028
+ for (const attribute of stored.attributes) {
38029
+ const text = written.get(attribute.name);
38030
+ if (text === undefined)
38031
+ return `Dispatch adds the attribute ${attribute.text} to line ${line}`;
38032
+ if (text !== attribute.text) {
38033
+ return `line ${line} holds the attribute ${text}, which Dispatch stores as ${attribute.text}`;
37475
38034
  }
37476
- };
38035
+ }
38036
+ const held = new Set(stored.attributes.map((attribute) => attribute.name));
38037
+ const dropped = given.attributes.find((attribute) => !held.has(attribute.name));
38038
+ return dropped === undefined ? undefined : `line ${line} holds the attribute ${dropped.text}, which Dispatch drops`;
37477
38039
  }
37478
- function arrivalText(attempt) {
37479
- if (attempt === undefined)
37480
- return "Dispatch recorded no delivery attempt for it";
37481
- if (attempt.state === "failed") {
37482
- return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
38040
+ function lineDifference(line, wrote, given, held, stored) {
38041
+ if (given === undefined || stored === undefined) {
38042
+ return `line ${line} ${wordDifference(lineWords(wrote, undefined), lineWords(held, undefined))}`;
37483
38043
  }
37484
- if (attempt.state === "pending")
37485
- return "its delivery is still on its way";
37486
- if (attempt.state === "queued") {
37487
- return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
38044
+ const attribute = attributeDifference(line, given, stored);
38045
+ if (attribute !== undefined)
38046
+ return attribute;
38047
+ const reordered = inStoredOrder(given, stored);
38048
+ if (reordered !== undefined && reordered !== wrote) {
38049
+ const words = lineWords(reordered, headedOpener(reordered));
38050
+ return `line ${line}, with its attributes put in the order Dispatch stores, ${wordDifference(words, lineWords(held, stored))}`;
37488
38051
  }
37489
- return `it reached that session as ${attempt.delivery}`;
38052
+ return `line ${line} ${wordDifference(lineWords(wrote, given), lineWords(held, stored))}`;
37490
38053
  }
37491
- async function sendToAgentCommand(context) {
37492
- const { args, client } = context;
37493
- const session = stringArg(args, "session");
37494
- const inReplyTo = optionalString(args, "in_reply_to");
37495
- const message = await client.agentMessage(session, {
37496
- body: stringArg(args, "body"),
37497
- delivery: stringArg(args, "delivery"),
37498
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
37499
- });
37500
- const attempt = message.deliveries?.at(-1);
37501
- const readBack = conversationReadBack(message.id);
37502
- const arrival = arrivalText(attempt);
37503
- return {
37504
- text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
37505
- details: {
37506
- session,
37507
- message: message.id,
37508
- ...attempt === undefined ? {} : { delivery: attempt.state },
37509
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
38054
+ function firstStoredDifference(given, stored) {
38055
+ const written = given.split(`
38056
+ `);
38057
+ const holds = stored.split(`
38058
+ `);
38059
+ for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
38060
+ const wrote = written[line];
38061
+ const held = holds[line];
38062
+ if (wrote === held)
38063
+ continue;
38064
+ if (wrote === undefined && held !== undefined) {
38065
+ return `the store writes a line ${line + 1}, ${quotedStoredLine(Array.from(held), 0)}`;
37510
38066
  }
37511
- };
37512
- }
37513
-
37514
- // ../envoy-client/src/dispatch-commands/deploy.ts
37515
- function deployText(deploy) {
37516
- const link = deploy.url === "" ? "" : ` ${deploy.url}`;
37517
- return `${deploy.program}: ${deploy.commit} since ${deploy.deployed_at} (source: ${deploy.source}, recorded by ${actorText(deploy.recorded_by)}).${link}`;
38067
+ if (held === undefined && wrote !== undefined) {
38068
+ return `the store drops line ${line + 1}, ${quotedStoredLine(Array.from(wrote), 0)}`;
38069
+ }
38070
+ if (wrote !== undefined && held !== undefined) {
38071
+ const givenOpener = headedOpener(wrote);
38072
+ const storedOpener = headedOpener(held);
38073
+ if (onlyReordered(givenOpener, held, storedOpener))
38074
+ continue;
38075
+ return lineDifference(line + 1, wrote, givenOpener, held, storedOpener);
38076
+ }
38077
+ }
38078
+ return "the stored text differs from the text given";
37518
38079
  }
37519
- async function deployCommand(context) {
37520
- const { args, client } = context;
37521
- const input = {
37522
- repo: stringArg(args, "repo"),
37523
- program: stringArg(args, "program"),
37524
- commit: stringArg(args, "commit"),
37525
- ...defined("deployed_at", optionalString(args, "deployed_at")),
37526
- ...defined("url", optionalString(args, "url"))
37527
- };
37528
- const result = await client.recordDeploy(input);
38080
+ var STORED_TEXT_PRINTED = 2000;
38081
+ function storedTextPrinted(stored) {
38082
+ if (stored.length <= STORED_TEXT_PRINTED)
38083
+ return { text: stored, cut: "" };
38084
+ const head = stored.slice(0, STORED_TEXT_PRINTED);
38085
+ const lastLineFeed = head.lastIndexOf(`
38086
+ `);
38087
+ const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
37529
38088
  return {
37530
- text: optionalBoolean(args, "json") === true ? JSON.stringify(result, null, 2) : deployText(result.deploy),
37531
- details: { repo: input.repo, deploy: result.deploy }
38089
+ text,
38090
+ cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
37532
38091
  };
37533
38092
  }
37534
- async function deploysCommand(context) {
37535
- const { args, client } = context;
37536
- const result = await client.deploys(stringArg(args, "repo"));
37537
- const deploys = result.deploys ?? [];
37538
- return {
37539
- text: optionalBoolean(args, "json") === true ? JSON.stringify(result, null, 2) : deploys.length === 0 ? `Dispatch holds no deploys for ${result.repo}.` : deploys.map(deployText).join(`
37540
- `),
37541
- details: { repo: result.repo, deploys }
37542
- };
38093
+ function storedTextProblem(given, stored, name) {
38094
+ const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
38095
+ const printed = storedTextPrinted(stored);
38096
+ return [
38097
+ `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
38098
+ ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
38099
+ `${printed.cut}
38100
+ --- the text Dispatch stores ---
38101
+ ${printed.text}`,
38102
+ "--- end of the text Dispatch stores ---"
38103
+ ].join("");
38104
+ }
38105
+ function withoutFinalLineFeed(text) {
38106
+ return text.endsWith(`
38107
+ `) ? text.slice(0, -1) : text;
38108
+ }
38109
+ function storedUpload(given, stored, name) {
38110
+ if (withoutFinalLineFeed(stored) === withoutFinalLineFeed(given)) {
38111
+ return { sent: given, reordered: [] };
38112
+ }
38113
+ const reordered = attributesReordered(given, stored);
38114
+ return reordered === undefined ? { refusal: storedTextProblem(given, stored, name) } : { sent: stored, reordered };
37543
38115
  }
37544
38116
 
37545
- // ../envoy-client/src/dispatch-commands/documents.ts
37546
- import { resolve as resolvePath3 } from "path";
37547
-
37548
- // ../envoy-client/src/dispatch-commands/open-decision-blocks.ts
37549
- async function blockAsks(client, resolved, state) {
37550
- const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
37551
- return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
38117
+ // ../envoy-client/src/dispatch-commands/stored-text.ts
38118
+ var MARKDOWN_ROUND_TRIP = "POST /api/v1/markdown/round-trip";
38119
+ var FILE_ROUND_TRIP = "POST /api/v1/markdown/file-round-trip";
38120
+ function storedTextCheckFailed(failed) {
38121
+ const again = failed.error instanceof DispatchAnswerNotKeptError ? "Send the upload again, which asks it under a new key." : "Send the upload again once that call is answered.";
38122
+ return new Error(`Dispatch could not say how it would store this text, so nothing was uploaded: ${failed.failure}. ${again}`, { cause: failed.error });
37552
38123
  }
37553
- var OPEN_BLOCK_ASK_THE_HUMAN = "Tell the human which block is open and ask them to answer it or to waive it. Once it is answered, it settles into a version on its own in about two seconds.";
37554
- var OPEN_BLOCK_WAIVED = "If they waive it, close the block with dispatch resolve-ask (--kind resolved, their words as the --reason)";
37555
- async function refuseOpenDecisionBlocks(client, resolved, refusal) {
37556
- const artifact = resolved.artifact;
37557
- const latest = artifact.approval?.latest_version;
37558
- if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
37559
- return;
37560
- const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
37561
- if (blocks.length === 0)
37562
- return;
37563
- const [documentAsks, version] = await Promise.all([
37564
- blockAsks(client, resolved),
37565
- client.docRead(artifact.id, latest)
37566
- ]);
37567
- const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
37568
- const lines = version.markdown.split(`
37569
- `);
37570
- const stillOpen = (named, state) => state === "answered" ? `${named}, answered but still open in version ${latest}: it settles into a version on its own in about two seconds; wait for that version` : `${named}, ${state} but still open in version ${latest}: write the decision into the text with dispatch doc-edit, which writes a version that carries it`;
37571
- const open = blocks.flatMap((block) => {
37572
- const ask = asks.get(block.id);
37573
- const id = typedBlockIdAttribute(block.id);
37574
- const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
37575
- const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
37576
- const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
37577
- if (states.length === 0)
37578
- return [`${named}, which version ${latest} does not hold yet`];
37579
- if (!states.includes("open") && states.some((state) => state !== undefined))
37580
- return [];
37581
- if (ask !== undefined)
37582
- return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
37583
- const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
37584
- const sourceId = attribute("copied_from");
37585
- const document = attribute("copied_from_document");
37586
- if (sourceId === undefined || document === undefined) {
37587
- return [`${named}, whose ask Dispatch has not opened yet`];
38124
+ function roundTripRouteAbsent(error) {
38125
+ return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
38126
+ }
38127
+ function documentTooLarge(measured) {
38128
+ const bytes = typeof measured === "number" ? measured : typeof measured === "string" ? utf8Bytes(measured) : measured.byteLength;
38129
+ return bytes > MARKDOWN_DOCUMENT_MAX_BYTES ? new Error(`CAP_EXCEEDED: ${MARKDOWN_DOCUMENT_TOO_LARGE}`) : undefined;
38130
+ }
38131
+ function documentBytesRefusal(field, bytes) {
38132
+ return documentTooLarge(bytes) ?? unstorableBytes(field, bytes);
38133
+ }
38134
+ function documentFieldRefusal(field, text) {
38135
+ return Buffer.byteLength(text, "utf8") > MARKDOWN_DOCUMENT_MAX_BYTES || text.includes("\x00") ? documentBytesRefusal(field, fileTextBytes(text)) : undefined;
38136
+ }
38137
+ function uploadedFile(cwd, path) {
38138
+ return Bun.file(resolvePath2(cwd, path));
38139
+ }
38140
+ async function documentFileRead(file, held) {
38141
+ if (file.type.split(";", 1)[0]?.trim().toLowerCase() !== "text/markdown") {
38142
+ return { kind: "passed", bytes: undefined };
38143
+ }
38144
+ let bytes = held;
38145
+ if (bytes === undefined) {
38146
+ const stats = await file.stat().catch(() => {
38147
+ return;
38148
+ });
38149
+ if (stats !== undefined && !stats.isFile() && !stats.isDirectory()) {
38150
+ return { kind: "passed", bytes: undefined };
37588
38151
  }
37589
- const source = parseDispatchRef(document);
37590
- const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
37591
- const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
37592
- return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
37593
- });
37594
- if (open.length === 0)
37595
- return;
37596
- const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
37597
- throw new Error([
37598
- `${refusal.call} was not called: ${artifact.name} (version ${latest}) has ${count}. ${refusal.effect}`,
37599
- ...open.map((line) => `- ${line}`),
37600
- refusal.remedy
37601
- ].join(`
37602
- `));
38152
+ const tooLarge = stats === undefined ? undefined : documentTooLarge(stats.size);
38153
+ if (tooLarge !== undefined)
38154
+ return { kind: "refused", refusal: tooLarge };
38155
+ try {
38156
+ bytes = await file.bytes();
38157
+ } catch (error) {
38158
+ return { kind: "unread", error };
38159
+ }
38160
+ }
38161
+ const refusal = documentBytesRefusal("file", bytes);
38162
+ return refusal === undefined ? { kind: "passed", bytes } : { kind: "refused", refusal };
37603
38163
  }
37604
- async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
37605
- const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
37606
- if (removing.length === 0)
37607
- return;
37608
- const artifact = resolved.artifact;
37609
- const blocks = await client.artifactBlocks(artifact.id);
37610
- const askBlocks = blocks.filter((block) => block.type === "ask");
37611
- const removed = new Set;
37612
- for (const operation of removing) {
37613
- const target = blocks.find((block) => block.id === operation.block);
37614
- if (target === undefined)
37615
- continue;
37616
- for (const block of askBlocks) {
37617
- if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
37618
- removed.add(block.id);
38164
+ async function documentFileBytes(file, held) {
38165
+ const read = await documentFileRead(file, held);
38166
+ if (read.kind === "refused")
38167
+ throw read.refusal;
38168
+ if (read.kind === "unread")
38169
+ throw read.error;
38170
+ return read.bytes;
38171
+ }
38172
+ function unchecked(answer) {
38173
+ return { kind: "unchecked", failure: answer.failure, routeAbsent: answer.routeAbsent };
38174
+ }
38175
+ async function askRoundTrip(client, route, ask) {
38176
+ const dispatch = client();
38177
+ try {
38178
+ return { kind: "stored", stored: await ask(dispatch) };
38179
+ } catch (error) {
38180
+ const routeAbsent = roundTripRouteAbsent(error);
38181
+ if (!routeAbsent && error instanceof DispatchServiceError && error.textRefusal) {
38182
+ return { kind: "refused", refusal: error };
38183
+ }
38184
+ return {
38185
+ kind: "unanswered",
38186
+ 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(/\.$/, "")}`,
38187
+ error,
38188
+ routeAbsent
38189
+ };
38190
+ }
38191
+ }
38192
+ async function storedTextCheck(client, tool, name, content, force) {
38193
+ const tooLarge = documentTooLarge(content);
38194
+ if (tooLarge !== undefined)
38195
+ return { kind: "refused", refusal: tooLarge };
38196
+ if (content === "")
38197
+ return { kind: "kept" };
38198
+ const answer = await askRoundTrip(client, MARKDOWN_ROUND_TRIP, (dispatch) => dispatch.markdownRoundTrip(content, !force));
38199
+ const blank = goBlankPattern.test(content);
38200
+ switch (answer.kind) {
38201
+ case "refused":
38202
+ return answer;
38203
+ case "unanswered":
38204
+ return blank || answer.routeAbsent ? unchecked(answer) : { kind: "failed", failure: answer.failure, error: answer.error };
38205
+ case "stored": {
38206
+ if (blank)
38207
+ return { kind: "kept" };
38208
+ const upload = storedUpload(content, answer.stored, name);
38209
+ if ("refusal" in upload) {
38210
+ return { kind: "refused", refusal: new ToolInputError(tool, [upload.refusal]) };
37619
38211
  }
38212
+ return upload.reordered.length === 0 ? { kind: "kept" } : { kind: "reordered", sent: upload.sent, lines: upload.reordered };
37620
38213
  }
37621
38214
  }
37622
- if (removed.size === 0)
37623
- return;
37624
- const asks = await blockAsks(client, resolved, "open");
37625
- const open = asks.filter((ask) => removed.has(ask.block_id));
37626
- if (open.length === 0)
37627
- return;
37628
- const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
37629
- throw new Error([
37630
- `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
37631
- ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
37632
- "A decision block leaves the document once its ask is answered or resolved. Until then, reword it with replace, relocate it with move, or change its question, options, urgency or multiple with dispatch edit-ask if you asked it; each keeps it."
37633
- ].join(`
37634
- `));
38215
+ }
38216
+ async function storedFileCheck(client, bytes, force) {
38217
+ const answer = await askRoundTrip(client, FILE_ROUND_TRIP, (dispatch) => dispatch.fileRoundTrip(bytes, !force));
38218
+ switch (answer.kind) {
38219
+ case "stored":
38220
+ return { kind: "kept" };
38221
+ case "refused":
38222
+ return answer;
38223
+ case "unanswered":
38224
+ return unchecked(answer);
38225
+ }
38226
+ }
38227
+ function artifactTextCheck(upload) {
38228
+ const { tool, name, content, bytes, force } = upload;
38229
+ if (content !== undefined) {
38230
+ return () => storedTextCheck(upload.textClient, tool, name, content, force);
38231
+ }
38232
+ if (bytes !== undefined)
38233
+ return () => storedFileCheck(upload.fileClient, bytes, force);
38234
+ return;
37635
38235
  }
37636
38236
 
37637
38237
  // ../envoy-client/src/dispatch-commands/upload-checks.ts
@@ -39273,63 +39873,6 @@ var dispatchCommands = {
39273
39873
  dispatch_api: onSession(apiCommand),
39274
39874
  dispatch_inbox: onSession(inboxCommand)
39275
39875
  };
39276
-
39277
- // ../envoy-client/src/dispatch-commands/command-context.ts
39278
- function toolActor(origin, input) {
39279
- return {
39280
- kind: "session",
39281
- id: input.sessionId ?? "unknown",
39282
- origin: {
39283
- ...origin,
39284
- host: input.host,
39285
- ...input.sessionTitle === undefined ? {} : { session_title: input.sessionTitle }
39286
- }
39287
- };
39288
- }
39289
- async function commandContext(session) {
39290
- const { input, ownerArguments, pictures } = session;
39291
- const actor = toolActor(await resolveOrigin(input.env ?? process.env, input.exec ?? defaultExec, input.cwd), input);
39292
- const client = session.newClient();
39293
- const { owner, documentOwner, resolveDocument } = await documentTargets(client, ownerArguments);
39294
- const issueArgument = optionalString(input.args, "issue");
39295
- const refText = optionalString(ownerArguments.args, "ref");
39296
- if (input.tool !== "dispatch_ask" && owner?.kind === "issue" && issueArgument !== undefined && refText !== undefined && ownerArguments.ref?.owner.kind === "issue" && owner.issue !== ownerArguments.ref.owner.issue) {
39297
- throw new ToolInputError(input.tool, [
39298
- `issue ${issueArgument} and ref ${refText} name two owners; --ref ${refText} alone acts on ${ownerArguments.ref.owner.issue}, and --issue ${issueArgument} alone acts on ${owner.issue}`
39299
- ]);
39300
- }
39301
- const issue = () => {
39302
- if (owner?.kind !== "issue")
39303
- throw new Error("issue is required");
39304
- return owner.issue;
39305
- };
39306
- const postWithPictures = (text, owner, upload) => textWithPictures(text, pictures, owner, (picture) => upload(picture).catch((error) => {
39307
- if (!(error instanceof DispatchWriteLandedError))
39308
- throw error;
39309
- throw new Error(`${error.message} That was a picture uploaded before this call's own write, so nothing else was written: run the call again, which uploads it as its next version.`, { cause: error });
39310
- }), actor);
39311
- const writePictures = (resolved, text) => {
39312
- if (resolved?.owner.kind === "project") {
39313
- const { project } = resolved.owner;
39314
- return postWithPictures(text, project, (upload) => client.projectArtifact(project, upload));
39315
- }
39316
- const issueKey = issue();
39317
- return postWithPictures(text, issueKey, (upload) => client.artifact(issueKey, upload));
39318
- };
39319
- const { hostSession } = session;
39320
- return {
39321
- ...session,
39322
- client,
39323
- actor,
39324
- owner,
39325
- documentOwner,
39326
- resolveDocument,
39327
- issue,
39328
- postWithPictures,
39329
- writePictures,
39330
- shown: hostSession ? shownPictures(hostSession) : undefined
39331
- };
39332
- }
39333
39876
  // ../envoy-client/src/dispatch-execute.ts
39334
39877
  async function executeDispatchTool(input) {
39335
39878
  const checked = await checkDispatchCall({
@@ -39348,6 +39891,193 @@ async function executeDispatchTool(input) {
39348
39891
  return command.origin === "none" ? command.run(session) : command.run(await commandContext(session));
39349
39892
  }
39350
39893
 
39894
+ // ../envoy-client/src/dispatch-commands/job-result.ts
39895
+ function isJobResult(argv) {
39896
+ const [command, ...words] = argv;
39897
+ return command === "result" && words.some((word) => word === "--project" || word.startsWith("--project="));
39898
+ }
39899
+ function outcomeCode(error) {
39900
+ const last = error instanceof DispatchWriteUnsettledError ? error.last : error;
39901
+ const code = typeof last === "object" && last !== null ? Reflect.get(last, "code") : undefined;
39902
+ if (typeof code === "string" && code !== "")
39903
+ return code;
39904
+ return last instanceof Error ? last.name : String(last);
39905
+ }
39906
+ async function jobResultCommand(parsed, env, io, print, refuse) {
39907
+ const resolution = ownIdentityDispatch(env);
39908
+ const checked = await checkDispatchCall({
39909
+ tool: parsed.tool,
39910
+ args: parsed.args,
39911
+ cwd: io.cwd,
39912
+ env,
39913
+ serverUrls: resolution.enabled ? dispatchServerUrls(resolution) : []
39914
+ });
39915
+ if (checked.problems.length > 0) {
39916
+ return refuse(new ToolInputError(parsed.tool, checked.problems.map(printable2)).message, USAGE, parsed.tool);
39917
+ }
39918
+ if (parsed.dryRun) {
39919
+ print(printableJson(JSON.stringify(parsed.args, null, 2)));
39920
+ return OK;
39921
+ }
39922
+ if (!resolution.enabled) {
39923
+ return refuse(`dispatch: ${printable2(resolution.error ?? resolution.notice)}`, USAGE, parsed.tool);
39924
+ }
39925
+ const bound = io.resultBound ?? RESULT_BOUND;
39926
+ const ended = AbortSignal.timeout(bound.totalMs);
39927
+ const lastRound = performance.now() + bound.totalMs - bound.reserveMs;
39928
+ const client = new DispatchClient(resolution.url, resolution.credential, io.fetchImpl ?? fetch, {
39929
+ signal: ended,
39930
+ deadlineMs: bound.totalMs,
39931
+ writeRetry: {
39932
+ ...DISPATCH_WRITE_RETRY,
39933
+ withinMs: Math.min(DISPATCH_WRITE_RETRY.withinMs, bound.totalMs - bound.reserveMs),
39934
+ inFlightWithinMs: bound.totalMs - bound.reserveMs
39935
+ }
39936
+ });
39937
+ for (;; ) {
39938
+ try {
39939
+ print(printableJson((await specCheckResultCommand(client, checked.args)).text));
39940
+ return OK;
39941
+ } catch (error) {
39942
+ if (error instanceof DispatchWriteLandedError) {
39943
+ print(JSON.stringify({ landed_without_answer: error.code }));
39944
+ return OK;
39945
+ }
39946
+ if (writeOutcomeUnknown(error)) {
39947
+ return refuse(printableJson(JSON.stringify({ write_outcome_unknown: outcomeCode(error) })), REFUSED, parsed.tool);
39948
+ }
39949
+ if (error instanceof AirlockTunnelRefusedError) {
39950
+ return refuse(printableLine(`${error.code}: ${error.message}`), REFUSED, parsed.tool);
39951
+ }
39952
+ if (error instanceof AirlockRefusedError) {
39953
+ return refuse(printableLine(`${error.code}: ${error.body}; nothing was stored`), REFUSED, parsed.tool);
39954
+ }
39955
+ const turnedAway = notNow(error);
39956
+ if (turnedAway !== undefined) {
39957
+ if (performance.now() + turnedAway.waitMs <= lastRound && await sleep(turnedAway.waitMs, ended).then(() => true, () => false)) {
39958
+ continue;
39959
+ }
39960
+ return refuse(printableLine(`${turnedAway.why}, and the ${bound.totalMs / 1000} s this command may take leave no time to ask again: ${messageFor(error)}`), REFUSED, parsed.tool);
39961
+ }
39962
+ return refuse(printableLine(messageFor(error)), REFUSED, parsed.tool);
39963
+ }
39964
+ }
39965
+ }
39966
+ function notNow(error) {
39967
+ if (tokenNotChecked(error)) {
39968
+ return {
39969
+ why: "Dispatch's check of the job's token turned the write away",
39970
+ waitMs: error.retryAfterMs ?? NOT_NOW_STEP_MS
39971
+ };
39972
+ }
39973
+ return;
39974
+ }
39975
+ var NOT_NOW_STEP_MS = 1000;
39976
+ var RESERVE_MARGIN_MS = 2000;
39977
+ var DISPATCH_TOKEN_CHECK_WAIT_MS = 5000;
39978
+ var RESULT_BOUND = {
39979
+ totalMs: DISPATCH_TOOL_DEADLINE_MS,
39980
+ reserveMs: DISPATCH_TOKEN_CHECK_WAIT_MS + RESERVE_MARGIN_MS
39981
+ };
39982
+
39983
+ // ../envoy-client/src/dispatch-commands/login.ts
39984
+ import { hostname as hostname4 } from "os";
39985
+ function parseLogin(argv) {
39986
+ let device = false;
39987
+ let person;
39988
+ for (let at = 0;at < argv.length; at += 1) {
39989
+ const word = argv[at];
39990
+ if (word === "--help" || word === "-h")
39991
+ return { kind: "help" };
39992
+ if (word === "--device") {
39993
+ device = true;
39994
+ } else if (word === "--person") {
39995
+ const next = argv[at + 1];
39996
+ if (next === undefined)
39997
+ return { kind: "refused", problem: "--person needs an address" };
39998
+ person = next;
39999
+ at += 1;
40000
+ } else if (word.startsWith("--person=")) {
40001
+ person = word.slice("--person=".length);
40002
+ } else {
40003
+ return { kind: "refused", problem: `unknown argument ${JSON.stringify(word)}` };
40004
+ }
40005
+ }
40006
+ return { kind: "login", device, person };
40007
+ }
40008
+ async function loginCommand(argv, env, io) {
40009
+ const refuse = (problem, code) => {
40010
+ io.print(`dispatch login was not called: ${problem}`);
40011
+ return code;
40012
+ };
40013
+ const parsed = parseLogin(argv);
40014
+ if (parsed.kind === "help") {
40015
+ io.print(loginHelp());
40016
+ return OK;
40017
+ }
40018
+ const tokenFiles = tokenFilesSet(env);
40019
+ if (tokenFiles !== undefined) {
40020
+ const beside = settingsBesideTokenFiles(env);
40021
+ return refuse(`${tokenFiles}, and the token files are the dispatch command's only Dispatch credential, which trades nothing at the secrets broker; a device login asks the broker and keeps a login in a file, so it does not run beside them${beside.length === 0 ? "" : `: ${beside.join("; ")}`}. Run dispatch login in a shell that sets neither token file.`, USAGE);
40022
+ }
40023
+ if (parsed.kind === "refused")
40024
+ return refuse(`${parsed.problem}. Run dispatch login --help.`, USAGE);
40025
+ if (!parsed.device) {
40026
+ return refuse("it logs a machine in with the broker's device grant alone, so --device is required. Run dispatch login --help.", USAGE);
40027
+ }
40028
+ const person = (parsed.person ?? env[PERSON_VAR] ?? "").trim();
40029
+ if (!person.includes("@")) {
40030
+ return refuse(`name the person who approves this machine, by the address they sign in to Dispatch with: --person <address>, or ${PERSON_VAR}.`, USAGE);
40031
+ }
40032
+ const brokerUrl = (env[BROKER_URL_VAR] ?? "").trim();
40033
+ if (!isHttpUrl(brokerUrl)) {
40034
+ return refuse(`${BROKER_URL_VAR} ${brokerUrl === "" ? "names no secrets broker" : "is not an http or https URL"}, so there is no broker to log this machine in at.`, USAGE);
40035
+ }
40036
+ let path;
40037
+ try {
40038
+ deviceLoginBroker(brokerUrl);
40039
+ path = deviceLoginFile(env);
40040
+ await deviceLoginPlace(path);
40041
+ } catch (error) {
40042
+ return refuse(messageFor(error), USAGE);
40043
+ }
40044
+ const host = deviceLoginHost(hostname4());
40045
+ try {
40046
+ const started = await startDeviceLogin({
40047
+ brokerUrl,
40048
+ person,
40049
+ host,
40050
+ fetch: io.fetchImpl
40051
+ });
40052
+ io.print([
40053
+ `dispatch login: to log this machine (${host}) in at the secrets broker at ${urlForText(started.brokerUrl, BROKER_URL_VAR)}, ${person} approves it:`,
40054
+ ` open ${started.verificationUriComplete ?? started.verificationUri}`,
40055
+ ` and enter the code ${started.userCode}`,
40056
+ `dispatch login: the code is good until ${started.expiresAt.toISOString()}; waiting for the approval.`
40057
+ ].join(`
40058
+ `));
40059
+ const login = await finishDeviceLogin(started, { path, fetch: io.fetchImpl, sleep: io.sleep });
40060
+ const lines = [
40061
+ `dispatch login: approved. This machine's device login is kept in ${DEVICE_LOGIN_FILE_NAMED}; its launcher credential ${login.credentialId} lasts until ${login.expiresAt.toISOString()}, and each refresh moves that on.`
40062
+ ];
40063
+ if (login.lockLeft !== "") {
40064
+ lines.push(`dispatch login: the login is kept, but ${login.lockLeft}.`);
40065
+ }
40066
+ if (login.replaced !== "" && login.replaced !== login.credentialId) {
40067
+ lines.push(`dispatch login: the earlier login of this machine, launcher credential ${login.replaced}, stays live until it lapses or is revoked, and a copy of its file still works; revoke it in Machine logins on ${started.verificationUri}.`);
40068
+ }
40069
+ if ((env[IDENTITY_VAR] ?? "").trim() !== IDENTITY_DEVICE_LOGIN) {
40070
+ lines.push(`dispatch login: set ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} in the environment of this machine's sessions, so they trade this login.`);
40071
+ }
40072
+ io.print(lines.join(`
40073
+ `));
40074
+ return OK;
40075
+ } catch (error) {
40076
+ io.print(`dispatch login: ${messageFor(error)}`);
40077
+ return REFUSED;
40078
+ }
40079
+ }
40080
+
39351
40081
  // ../envoy-client/src/dispatch-proxy.ts
39352
40082
  import { lstatSync, rmSync as rmSync3 } from "fs";
39353
40083
  import {
@@ -40802,20 +41532,22 @@ async function runDispatchCli(argv, rawEnv, io) {
40802
41532
  if (argv[0] === PROXY_COMMAND) {
40803
41533
  return await runProxyCommand(argv.slice(1), env, rawEnv, io, ledgerHost);
40804
41534
  }
41535
+ const job = isJobResult(argv);
40805
41536
  let parsed;
40806
41537
  try {
40807
41538
  parsed = parseCommand(argv, io);
40808
41539
  } catch (error) {
40809
- return refuse(`dispatch: ${messageFor(error)}`, USAGE);
41540
+ return refuse(`dispatch: ${job ? printable2(messageFor(error)) : messageFor(error)}`, USAGE);
40810
41541
  }
40811
41542
  if (parsed.kind === "help") {
40812
41543
  print(parsed.tool === undefined ? commandsHelp() : commandHelp(parsed.tool));
40813
41544
  return OK;
40814
41545
  }
40815
41546
  if (parsed.kind === "refused") {
40816
- return parsed.tool === undefined ? refuse([`dispatch: ${parsed.problems.join(`
41547
+ const problems = job ? parsed.problems.map(printable2) : parsed.problems;
41548
+ return parsed.tool === undefined ? refuse([`dispatch: ${problems.join(`
40817
41549
  `)}`, "Run dispatch --help."].join(`
40818
- `), USAGE) : refuse(new ToolInputError(parsed.tool, parsed.problems, defined("aboutAFlag", parsed.aboutAFlag)).message, USAGE, parsed.tool);
41550
+ `), USAGE) : refuse(new ToolInputError(parsed.tool, problems, defined("aboutAFlag", parsed.aboutAFlag)).message, USAGE, parsed.tool);
40819
41551
  }
40820
41552
  const command = dispatchCommands[parsed.tool];
40821
41553
  const documentFields = command?.documentFields ?? [];
@@ -40841,6 +41573,8 @@ async function runDispatchCli(argv, rawEnv, io) {
40841
41573
  if (read.kind === "passed")
40842
41574
  pathBytes = read.bytes;
40843
41575
  }
41576
+ if (job)
41577
+ return await jobResultCommand(parsed, env, io, print, refuse);
40844
41578
  if (parsed.tool === "dispatch_api" && ledgerHost() === undefined) {
40845
41579
  const { problems, args } = await checkDispatchCall({
40846
41580
  tool: parsed.tool,