@sjawhar/claude-envoy 6.2.0 → 6.2.1

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
@@ -979,11 +979,8 @@ __export(exports_coerce, {
979
979
  string: () => string3
980
980
  });
981
981
 
982
- // ../envoy-client/bin/dispatch.ts
983
- import { readFileSync as readFileSync7 } from "fs";
984
-
985
982
  // ../envoy-client/src/dispatch-cli.ts
986
- import { closeSync as closeSync4, constants as constants4, fstatSync as fstatSync3, openSync as openSync4, readFileSync as readFileSync6 } from "fs";
983
+ import { closeSync as closeSync4, constants as constants4, fstatSync as fstatSync3, openSync as openSync4, readFileSync as readFileSync7 } from "fs";
987
984
 
988
985
  // ../envoy-client/src/askgate-marker.ts
989
986
  import { createHash, randomBytes } from "crypto";
@@ -14205,6 +14202,14 @@ var wholeIdPattern = /^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a
14205
14202
  function isIdPrefix(value) {
14206
14203
  return idPrefixPattern.test(value) && !wholeIdPattern.test(value);
14207
14204
  }
14205
+ function utf8Bytes(value) {
14206
+ let bytes = 0;
14207
+ for (const character of value) {
14208
+ const code = character.codePointAt(0) ?? 0;
14209
+ bytes += code < 128 ? 1 : code < 2048 ? 2 : code < 65536 ? 3 : 4;
14210
+ }
14211
+ return bytes;
14212
+ }
14208
14213
  var PLAIN_ISSUE_TABS = [
14209
14214
  "verification",
14210
14215
  "plan",
@@ -14467,6 +14472,9 @@ var ISSUE_LABEL_MAX = 40;
14467
14472
  var MAX_ISSUE_COMPONENTS = 50;
14468
14473
  var ISSUE_TITLE_MAX = 1000;
14469
14474
  var PROJECT_NAME_MAX = 80;
14475
+ var MARKDOWN_DOCUMENT_MAX_BYTES = 1 << 20;
14476
+ var MARKDOWN_DOCUMENT_TOO_LARGE = `a markdown document is at most ${MARKDOWN_DOCUMENT_MAX_BYTES / (1 << 20)} MiB; a larger file is stored as a binary artifact under another content type`;
14477
+ var TEXT_REFUSAL_HEADER = "Dispatch-Text-Refusal";
14470
14478
  var MAX_ISSUE_PAGE_LIMIT = 250;
14471
14479
  var DEFAULT_ISSUE_PAGE_LIMIT = 50;
14472
14480
  var DEFAULT_ISSUE_READ_EVENTS = 10;
@@ -14763,6 +14771,7 @@ function artifactKindConflictRule(held, upload) {
14763
14771
  return `This upload is a ${artifactKindWord(upload)}, and the name holds a ${artifactKindWord(held)}: Dispatch keeps one kind under one name, so this upload cannot be its next version, with force or without. Give the upload another name.`;
14764
14772
  }
14765
14773
  var ARTIFACT_STORED_TEXT_RULE = `content and content-file hold text Dispatch stores as Markdown, and a text the store would write under another spelling is refused. A typed block whose attributes differ from Dispatch's only in their order is not refused: the command uploads it with them in Dispatch's order and names each such block. A refusal names the first difference: a changed line by the attribute or the word that differs, a word of more than 200 characters by a window from its first character that differs, and a line the store adds or drops by a quote cut at 200 characters, each cut named. The refusal prints the text Dispatch stores: send that text. A name that does not end in .md or .markdown has a second way out, which keeps the text as it was written: send it as a file with ${PATH_KEEPS_BYTES}.`;
14774
+ var ARTIFACT_DOCUMENT_BYTES_ORDER = `in the order its upload refuses a Markdown file in: past ${MARKDOWN_DOCUMENT_MAX_BYTES / (1 << 20)} MiB with CAP_EXCEEDED, and otherwise at the first NUL character or byte that is not UTF-8, with NUL_CHARACTER or INVALID_UTF8, Dispatch's own refusal of it, naming the field (content, or file for path), the character and where it stands.`;
14766
14775
  var NAME_EXTENSION = /\.([^\s.]+)$/u;
14767
14776
  var MARKDOWN_EXTENSION = /^(md|markdown)$/i;
14768
14777
  function preconditionArgument(z) {
@@ -15550,6 +15559,7 @@ var dispatchToolSpecs = [
15550
15559
  },
15551
15560
  {
15552
15561
  name: "dispatch_result",
15562
+ dryRunHelp: "Checks the arguments as the call would and prints them as JSON. A record's dry run then asks Dispatch for the pull-request body line the record would print, and prints it; Dispatch records nothing. A retraction's dry run sends nothing.",
15553
15563
  example: {
15554
15564
  issue: "DSP-1",
15555
15565
  check: "k1",
@@ -15595,14 +15605,15 @@ var dispatchToolSpecs = [
15595
15605
  name: "dispatch_artifact",
15596
15606
  example: { issue: "DSP-1", name: "design.md", content: `# Design
15597
15607
  ` },
15598
- description: "Attach a local file or inline text as an issue artifact or project document, or make an empty document from its name alone. Do not use it to edit a live document; use " + "dispatch doc-edit instead. Never upload a document's own name to change it (spec.md replaces the spec whole); edit it with dispatch doc-edit. " + `${ARTIFACT_SOURCE_RULE} ` + `${ARTIFACT_NAME_EXISTS_RULE} A call that stores nothing - no path, and content absent or blank - is refused under a held name even with force and a token, so a title typed twice never empties the document that holds it; that refusal names no token, since no token makes such a call one Dispatch takes. ` + "A markdown document is at most 1 MiB and any other file at most 25 MiB. " + "An upload that replaces a document the owner already holds under that name says which version it replaces: precondition.document takes the document token dispatch doc-read prints as `Document token: sha256:\u2026`, and Dispatch checks it under the write's own lock. An upload that names none is taken for now without a check, since older dispatch commands cannot name one; name the token wherever the command can, because a later release refuses an upload naming none with 400 PRECONDITION_REQUIRED. A token behind the live document is refused with 409 PRECONDITION_FAILED. The refusal tells you to read the document again with dispatch doc-read, which prints the token the document carries now, and to upload again naming that token. An upload that replaces a file or a picture names the token of the version it replaces the same way, the `Document token:` line dispatch doc-read prints for its latest version, and any other token is refused with 409 PRECONDITION_FAILED; one naming none is taken unchecked. The command's refusal of a name the owner holds prints no token: for a file or a picture it names --force with the token your own dispatch doc-read printed, or --force alone where Dispatch states no token for the file, since such a Dispatch refuses a token on a file's upload; for an upload of another kind than the name holds (a declared Markdown upload is a document, PNG, JPEG, GIF or WebP bytes a picture, anything else a file) it names another name, since Dispatch refuses it under that name with 400 ARTIFACT_KIND_MISMATCH. A first upload under a name replaces no version, so it names none. " + `${ARTIFACT_CONTENT_NAME_RULE} ${ARTIFACT_STORED_TEXT_RULE} ` + "Markdown is also refused with 413 CAP_EXCEEDED when it makes more than 65,536 elements (a block weighs 3, and an empty list item, quote, footnote definition or typed block 3 more for the empty paragraph it holds; a table cell 4, a hard line break 3, an image 3, a piece of inline HTML 2, an autolink 2, a footnote reference 2; inline syntax, marks, lines of text and backslash escapes or character references 1 each), or when a new version would leave the document's stored markdown (what its text reads back as) longer than 1 MiB or making more than 65,536 elements, and longer or heavier than before; shorten it or split it across documents. " + "In a table row, write every | in a cell as \\|, in code too: a | after two backslashes ends the cell, and a row with more cells than its table is refused. " + "Markdown holding an ask block whose body breaks its content rule (one or more question paragraphs, then at most one bullet list of options, last) is refused with 400 INVALID_ASK_BLOCK; a new version of a document is held to it only for the asks it writes or changes. " + `${CI_CHECK_RULE} ` + `${OWNER_REFERENCE}`,
15608
+ dryRunHelp: `Before it asks Dispatch anything, and with Dispatch off too, it refuses with exit 1 a text past ${MARKDOWN_DOCUMENT_MAX_BYTES / (1 << 20)} MiB, or holding a NUL character or a byte that is not UTF-8, whether it is read from --content-file, from stdin (--content-file -) or from a --path file ending in .md or .markdown, a file Dispatch stores as a Markdown document, ${ARTIFACT_DOCUMENT_BYTES_ORDER} It refuses such a text once the flags are read, before it checks the arguments as the call would and before anything that needs Dispatch, as the call does. Then, for text given inline, read from --content-file or from stdin, it asks Dispatch how it would store the text (POST /api/v1/markdown/round-trip), and refuses, with the call's own refusal and exit code, a text that Dispatch would store under another spelling, but for typed blocks' attributes in another order, which the call uploads in Dispatch's order, or that the call refuses for the text alone: one past ${MARKDOWN_DOCUMENT_MAX_BYTES / (1 << 20)} MiB of UTF-8, which it refuses without asking, or one Dispatch refuses as its upload would, such as one making more elements than one write may, or holding markdown the parser refuses. For a Markdown --path file, it then sends Dispatch the file's bytes (POST /api/v1/markdown/file-round-trip), as the call does before it uploads them, and refuses, with the call's own refusal and exit code, what Dispatch refuses of them as their upload would, but never their spelling. Without force it also refuses what Dispatch refuses only of a new document, such as an ask block that breaks its content rule, a block id written twice, a check proved by CI that breaks its rules, or a rendering past the bytes one document holds; with force (--force), which may replace a document Dispatch judges by looser rules, it asks for none of those and checks the spelling Dispatch answers as for any text, so it passes with no warning a text the call can then refuse for one of those: under a name the owner does not hold, because the call uploads a new document; under a name the owner holds, because a replacement holds those rules for the blocks it adds or changes, and refuses a rendering that grows past the bytes one document holds over the version it replaces. It does not read whether the owner holds the name, which the call reads only after it checks the text: a text this check refuses is refused alike under a held name, and a text it passes the call without force still refuses under a held name, though the dry run passes it. Otherwise it prints the arguments as JSON. It stores nothing. For any other text but an empty one given inline, read from --content-file or from stdin, which it asks Dispatch nothing about and passes with no warning, when Dispatch cannot answer, or cannot check the text or the file, it says so on stderr and passes.`,
15609
+ description: "Attach a local file or inline text as an issue artifact or project document, or make an empty document from its name alone. Do not use it to edit a live document; use " + "dispatch doc-edit instead. Never upload a document's own name to change it (spec.md replaces the spec whole); edit it with dispatch doc-edit. " + `${ARTIFACT_SOURCE_RULE} ` + `${ARTIFACT_NAME_EXISTS_RULE} A call that stores nothing - no path, and content absent or blank - is refused under a held name even with force and a token, so a title typed twice never empties the document that holds it; that refusal names no token, since no token makes such a call one Dispatch takes. ` + `A markdown document is at most ${MARKDOWN_DOCUMENT_MAX_BYTES / (1 << 20)} MiB and any other file at most 25 MiB. ` + "An upload that replaces a document the owner already holds under that name says which version it replaces: precondition.document takes the document token dispatch doc-read prints as `Document token: sha256:\u2026`, and Dispatch checks it under the write's own lock. An upload that names none is taken for now without a check, since older dispatch commands cannot name one; name the token wherever the command can, because a later release refuses an upload naming none with 400 PRECONDITION_REQUIRED. A token behind the live document is refused with 409 PRECONDITION_FAILED. The refusal tells you to read the document again with dispatch doc-read, which prints the token the document carries now, and to upload again naming that token. An upload that replaces a file or a picture names the token of the version it replaces the same way, the `Document token:` line dispatch doc-read prints for its latest version, and any other token is refused with 409 PRECONDITION_FAILED; one naming none is taken unchecked. The command's refusal of a name the owner holds prints no token: for a file or a picture it names --force with the token your own dispatch doc-read printed, or --force alone where Dispatch states no token for the file, since such a Dispatch refuses a token on a file's upload; for an upload of another kind than the name holds (a declared Markdown upload is a document, PNG, JPEG, GIF or WebP bytes a picture, anything else a file) it names another name, since Dispatch refuses it under that name with 400 ARTIFACT_KIND_MISMATCH. A first upload under a name replaces no version, so it names none. " + `${ARTIFACT_CONTENT_NAME_RULE} ${ARTIFACT_STORED_TEXT_RULE} ` + `A text past ${MARKDOWN_DOCUMENT_MAX_BYTES / (1 << 20)} MiB, or holding a NUL character or a byte that is not UTF-8, read from content-file, from stdin or from a Markdown path file, is refused once the flags are read, before the arguments are checked and before anything that needs Dispatch, by the call and its dry run alike, with Dispatch on or off, ${ARTIFACT_DOCUMENT_BYTES_ORDER} ` + `Markdown is also refused with 413 CAP_EXCEEDED when it makes more than 65,536 elements (a block weighs 3, and an empty list item, quote, footnote definition or typed block 3 more for the empty paragraph it holds; a table cell 4, a hard line break 3, an image 3, a piece of inline HTML 2, an autolink 2, a footnote reference 2; inline syntax, marks, lines of text and backslash escapes or character references 1 each), or when a new version would leave the document's stored markdown (what its text reads back as) longer than ${MARKDOWN_DOCUMENT_MAX_BYTES / (1 << 20)} MiB or making more than 65,536 elements, and longer or heavier than before; shorten it or split it across documents. ` + "In a table row, write every | in a cell as \\|, in code too: a | after two backslashes ends the cell, and a row with more cells than its table is refused. " + "Markdown holding an ask block whose body breaks its content rule (one or more question paragraphs, then at most one bullet list of options, last) is refused with 400 INVALID_ASK_BLOCK; a new version of a document is held to it only for the asks it writes or changes. " + `${CI_CHECK_RULE} ` + `${OWNER_REFERENCE}`,
15599
15610
  arguments: (z) => ({
15600
15611
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
15601
15612
  project: z.string().describe("Project key for an unlinked document.").optional(),
15602
15613
  name: z.string().describe("Artifact filename shown in Dispatch."),
15603
15614
  path: z.string().describe("Local path to the file to upload.").optional(),
15604
15615
  content: z.string().describe("Inline text to store as a Markdown document, under a name ending in .md or .markdown or with no extension. The command refuses a text the store would write under another spelling, a CR LF or a lone carriage return among them, which Dispatch stores as a line feed. A missing line feed at the end is not such a text: Dispatch adds one, and the upload goes on. Nor is a typed block whose attributes differ only in their order: the upload puts them in Dispatch's order. The refusal names the first difference: a changed line by the attribute or the word that differs, a word of more than 200 characters by a window from its first character that differs, and a line the store adds or drops by a quote cut at 200 characters, each cut named. It prints the text Dispatch stores, which is the text to send.").optional(),
15605
- force: z.boolean().describe("Write the next version of a document the owner already holds under this name; without it the upload of a name that exists is refused.").optional(),
15616
+ force: z.boolean().describe("Write the next version of a document the owner already holds under this name; without it the upload of a name that exists is refused. The command checks the text first, so a text it refuses for the text alone gets that refusal, not this one.").optional(),
15606
15617
  precondition: uploadPreconditionArgument(z),
15607
15618
  summary: z.string().describe("Optional version summary.").optional()
15608
15619
  }),
@@ -20590,6 +20601,94 @@ function fenceColons(text) {
20590
20601
  return /^:+$/.test(trimmed) ? trimmed.length : 0;
20591
20602
  }
20592
20603
 
20604
+ // ../envoy-client/src/dispatch-file-text.ts
20605
+ import { isUtf8 } from "buffer";
20606
+ import { readFileSync as readFileSync2 } from "fs";
20607
+ var decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
20608
+ var encoder2 = new TextEncoder;
20609
+ function byteText(byte) {
20610
+ return `0x${byte.toString(16).toUpperCase().padStart(2, "0")}`;
20611
+ }
20612
+
20613
+ class NotUtf8Error extends Error {
20614
+ bytes;
20615
+ name = "NotUtf8Error";
20616
+ constructor(bytes) {
20617
+ super("the bytes are not UTF-8");
20618
+ this.bytes = bytes;
20619
+ }
20620
+ }
20621
+ function firstNotUtf8(bytes) {
20622
+ for (let at = 0;at < bytes.length; ) {
20623
+ const lead = bytes[at];
20624
+ if (lead < 128) {
20625
+ at += 1;
20626
+ continue;
20627
+ }
20628
+ let width;
20629
+ let low = 128;
20630
+ let high = 191;
20631
+ if (lead >= 194 && lead <= 223) {
20632
+ width = 2;
20633
+ } else if (lead >= 224 && lead <= 239) {
20634
+ width = 3;
20635
+ if (lead === 224)
20636
+ low = 160;
20637
+ if (lead === 237)
20638
+ high = 159;
20639
+ } else if (lead >= 240 && lead <= 244) {
20640
+ width = 4;
20641
+ if (lead === 240)
20642
+ low = 144;
20643
+ if (lead === 244)
20644
+ high = 143;
20645
+ } else {
20646
+ return at;
20647
+ }
20648
+ if (at + width > bytes.length)
20649
+ return at;
20650
+ const second = bytes[at + 1];
20651
+ if (second < low || second > high)
20652
+ return at;
20653
+ for (let next = at + 2;next < at + width; next += 1) {
20654
+ if ((bytes[next] & 192) !== 128)
20655
+ return at;
20656
+ }
20657
+ at += width;
20658
+ }
20659
+ return -1;
20660
+ }
20661
+ function firstUnstorable(bytes) {
20662
+ const notUtf8 = isUtf8(bytes) ? -1 : firstNotUtf8(bytes);
20663
+ const nul = bytes.indexOf(0);
20664
+ const at = nul !== -1 && (notUtf8 === -1 || nul < notUtf8) ? nul : notUtf8;
20665
+ if (at === -1)
20666
+ return;
20667
+ return { byte: bytes[at], character: decoder.decode(bytes.subarray(0, at)).length + 1 };
20668
+ }
20669
+ function unstorableBytes(field, bytes) {
20670
+ const first = firstUnstorable(bytes);
20671
+ if (first === undefined)
20672
+ return;
20673
+ const { byte, character } = first;
20674
+ return new Error(byte === 0 ? `NUL_CHARACTER: ${field} holds a NUL character (U+0000) at character ${character}, which Dispatch cannot store` : `INVALID_UTF8: ${field} holds a byte that is not UTF-8 (${byteText(byte)}) at character ${character}, which Dispatch cannot store`);
20675
+ }
20676
+ function utf8Text(bytes) {
20677
+ try {
20678
+ return decoder.decode(bytes);
20679
+ } catch (error) {
20680
+ if (isUtf8(bytes))
20681
+ throw error;
20682
+ throw new NotUtf8Error(bytes);
20683
+ }
20684
+ }
20685
+ function readFileText(path, readStdin = () => readFileSync2(0)) {
20686
+ return utf8Text(path === "-" ? readStdin() : readFileSync2(path));
20687
+ }
20688
+ function fileTextBytes(text) {
20689
+ return encoder2.encode(text);
20690
+ }
20691
+
20593
20692
  // ../envoy-client/src/dispatch-command.ts
20594
20693
  var PREFIXED_FLAGS = [
20595
20694
  {
@@ -20602,6 +20701,7 @@ var PREFIXED_FLAGS = [
20602
20701
  }
20603
20702
  ];
20604
20703
  var STDIN = "-";
20704
+ var FILE_BYTES_RULE = "Bytes that are not UTF-8 are refused in Dispatch's own words, and nothing is sent.";
20605
20705
  var BARE_WORD = /^[A-Za-z0-9_./:@%+=,-]+$/;
20606
20706
  var OPTION_SEPARATOR = ": ";
20607
20707
  var LOCAL_FILE_FIELD = { tool: "dispatch_artifact", field: "path" };
@@ -20644,7 +20744,7 @@ function surfaceFor(tool) {
20644
20744
  spec,
20645
20745
  command: commandName(spec.name),
20646
20746
  fields,
20647
- flags: flagTable(spec.name, fields)
20747
+ flags: flagTable(spec, fields)
20648
20748
  };
20649
20749
  surfaces.set(tool, surface);
20650
20750
  return surface;
@@ -20765,11 +20865,11 @@ function placeholder(info) {
20765
20865
  return info.kind.array === "string" ? "<text>" : "<n>";
20766
20866
  return "<text>";
20767
20867
  }
20768
- function flagTable(tool, fields) {
20868
+ function flagTable(spec, fields) {
20769
20869
  const flags = new Map;
20770
20870
  const add = (flag, entry) => {
20771
20871
  if (flags.has(flag))
20772
- throw new Error(`${tool}: two fields claim the flag ${flag}`);
20872
+ throw new Error(`${spec.name}: two fields claim the flag ${flag}`);
20773
20873
  flags.set(flag, entry);
20774
20874
  };
20775
20875
  for (const [field, info] of fields) {
@@ -20782,7 +20882,7 @@ function flagTable(tool, fields) {
20782
20882
  field,
20783
20883
  action: "file",
20784
20884
  value: "<path>",
20785
- text: `--${name} read from a file; - reads stdin.`
20885
+ text: `--${name} read from a file; - reads stdin. ${FILE_BYTES_RULE}`
20786
20886
  });
20787
20887
  } else if (kind === "number") {
20788
20888
  add(`--${name}`, { field, action: "set", value: "<n>", text: about });
@@ -20815,7 +20915,7 @@ function flagTable(tool, fields) {
20815
20915
  field,
20816
20916
  action: "json-file",
20817
20917
  value: "<path>",
20818
- text: `--${name}-json read from a file; - reads stdin.`
20918
+ text: `--${name}-json read from a file; - reads stdin. ${FILE_BYTES_RULE}`
20819
20919
  });
20820
20920
  } else {
20821
20921
  const none = kind.array === "number-or-null" ? " none is null." : "";
@@ -20826,10 +20926,10 @@ function flagTable(tool, fields) {
20826
20926
  text: `${about} One item per flag, repeated.${none}`.trim()
20827
20927
  });
20828
20928
  for (const prefixed of PREFIXED_FLAGS) {
20829
- if (prefixed.tool !== tool || prefixed.field !== field)
20929
+ if (prefixed.tool !== spec.name || prefixed.field !== field)
20830
20930
  continue;
20831
20931
  if (kind.array !== "string") {
20832
- throw new Error(`${tool}: ${prefixed.flag} needs ${field} to be a list of text`);
20932
+ throw new Error(`${spec.name}: ${prefixed.flag} needs ${field} to be a list of text`);
20833
20933
  }
20834
20934
  add(prefixed.flag, {
20835
20935
  field,
@@ -20851,7 +20951,7 @@ function flagTable(tool, fields) {
20851
20951
  add("--help", { action: "help", text: "Prints this help." });
20852
20952
  add("--dry-run", {
20853
20953
  action: "dry-run",
20854
- text: tool === "dispatch_result" ? "Checks the arguments as the call would and prints them as JSON. A record's dry run then asks Dispatch for the pull-request body line the record would print, and prints it; Dispatch records nothing. A retraction's dry run sends nothing." : "Checks the arguments as the call would, then prints them as JSON and sends nothing."
20954
+ text: spec.dryRunHelp ?? "Checks the arguments as the call would, then prints them as JSON and sends nothing."
20855
20955
  });
20856
20956
  return flags;
20857
20957
  }
@@ -20875,7 +20975,8 @@ function parseCommand(argv, io) {
20875
20975
  let help = false;
20876
20976
  let dryRun = false;
20877
20977
  let stdinFlag;
20878
- const read = (flag, path) => {
20978
+ let unstorable;
20979
+ const read = (flag, field, path) => {
20879
20980
  if (path === STDIN) {
20880
20981
  if (stdinFlag !== undefined) {
20881
20982
  problems.push(`${stdinFlag} and ${flag} both read stdin (-); only one flag can`);
@@ -20886,6 +20987,11 @@ function parseCommand(argv, io) {
20886
20987
  try {
20887
20988
  return io.readText(path);
20888
20989
  } catch (error) {
20990
+ if (error instanceof NotUtf8Error) {
20991
+ claim(field, flag, false);
20992
+ unstorable ??= { field, bytes: error.bytes };
20993
+ return;
20994
+ }
20889
20995
  problems.push(`${flag} could not read ${path === STDIN ? "stdin" : path}: ${messageFor(error)}`);
20890
20996
  return;
20891
20997
  }
@@ -20996,14 +21102,14 @@ function parseCommand(argv, io) {
20996
21102
  break;
20997
21103
  }
20998
21104
  case "file": {
20999
- const text = read(flag, value);
21105
+ const text = read(flag, field, value);
21000
21106
  if (text !== undefined && claim(field, flag, false))
21001
21107
  args[field] = text;
21002
21108
  break;
21003
21109
  }
21004
21110
  case "json":
21005
21111
  case "json-file": {
21006
- const text = action === "json" ? value : read(flag, value);
21112
+ const text = action === "json" ? value : read(flag, field, value);
21007
21113
  const parsed = text === undefined ? undefined : json(flag, text);
21008
21114
  if (parsed !== undefined && claim(field, flag, false))
21009
21115
  args[field] = parsed.value;
@@ -21039,6 +21145,8 @@ function parseCommand(argv, io) {
21039
21145
  if (problems.length > 0) {
21040
21146
  return problems.length === bareDashes.size ? { kind: "refused", tool, problems, aboutAFlag: false } : { kind: "refused", tool, problems };
21041
21147
  }
21148
+ if (unstorable !== undefined)
21149
+ return { kind: "unstorable", tool, ...unstorable };
21042
21150
  return { kind: "call", tool, args, dryRun };
21043
21151
  }
21044
21152
  function appendedItem(kind, flag, value, number) {
@@ -21138,7 +21246,7 @@ function commandsHelp() {
21138
21246
  return ` ${commandName(spec.name).padEnd(width)} ${sentence}`;
21139
21247
  }),
21140
21248
  "",
21141
- "Run dispatch <command> --help for its flags and an example; --dry-run checks a command's arguments as the call would and prints them as given, sending nothing, except that dispatch result's dry run of a record also prints the pull-request body line Dispatch would write for it, recording nothing.",
21249
+ "Run dispatch <command> --help for its flags and an example. --dry-run checks a command's arguments as the call would and prints them as given. It stores nothing. A command whose dry run asks Dispatch something past that check (dispatch artifact: how Dispatch would store its text; dispatch result: the pull-request body line the record would print) says so in its --help.",
21142
21250
  "",
21143
21251
  "dispatch login --device logs a machine with no identity of its own, such as a laptop, in at the secrets broker, once per machine; it is no Dispatch call, and needs no host or session (dispatch login --help).",
21144
21252
  ""
@@ -21355,13 +21463,13 @@ var customFetch = Symbol();
21355
21463
  var modifyAssertion = Symbol();
21356
21464
  var jweDecrypt = Symbol();
21357
21465
  var jwksCache = Symbol();
21358
- var encoder2 = new TextEncoder;
21359
- var decoder = new TextDecoder;
21466
+ var encoder3 = new TextEncoder;
21467
+ var decoder2 = new TextDecoder;
21360
21468
  function buf(input) {
21361
21469
  if (typeof input === "string") {
21362
- return encoder2.encode(input);
21470
+ return encoder3.encode(input);
21363
21471
  }
21364
- return decoder.decode(input);
21472
+ return decoder2.decode(input);
21365
21473
  }
21366
21474
  var encodeBase64Url;
21367
21475
  if (Uint8Array.prototype.toBase64) {
@@ -22229,8 +22337,8 @@ var _nodiscoverycheck = Symbol();
22229
22337
  var _expectedIssuer = Symbol();
22230
22338
 
22231
22339
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
22232
- var encoder3 = new TextEncoder;
22233
- var decoder2 = new TextDecoder;
22340
+ var encoder4 = new TextEncoder;
22341
+ var decoder3 = new TextDecoder;
22234
22342
  var strictDecoder = new TextDecoder("utf-8", { fatal: true });
22235
22343
  var MAX_INT32 = 2 ** 32;
22236
22344
  function concat(...buffers) {
@@ -22374,7 +22482,7 @@ var invalid = "The input to be decoded is not correctly encoded.";
22374
22482
  function decode3(input) {
22375
22483
  if (Uint8Array.fromBase64) {
22376
22484
  try {
22377
- return Uint8Array.fromBase64(typeof input === "string" ? input : decoder2.decode(input), {
22485
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder3.decode(input), {
22378
22486
  alphabet: "base64url"
22379
22487
  });
22380
22488
  } catch (cause) {
@@ -22383,7 +22491,7 @@ function decode3(input) {
22383
22491
  }
22384
22492
  let encoded = input;
22385
22493
  if (encoded instanceof Uint8Array) {
22386
- encoded = decoder2.decode(encoded);
22494
+ encoded = decoder3.decode(encoded);
22387
22495
  }
22388
22496
  if (encoded.includes("+") || encoded.includes("/")) {
22389
22497
  throw new TypeError(invalid);
@@ -22398,7 +22506,7 @@ function decode3(input) {
22398
22506
  function encode4(input) {
22399
22507
  let unencoded = input;
22400
22508
  if (typeof unencoded === "string") {
22401
- unencoded = encoder3.encode(unencoded);
22509
+ unencoded = encoder4.encode(unencoded);
22402
22510
  }
22403
22511
  if (Uint8Array.prototype.toBase64) {
22404
22512
  return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
@@ -22687,7 +22795,7 @@ class ClientError extends Error {
22687
22795
  Error.captureStackTrace?.(this, this.constructor);
22688
22796
  }
22689
22797
  }
22690
- var decoder3 = new TextDecoder;
22798
+ var decoder4 = new TextDecoder;
22691
22799
  function e(msg, cause, code) {
22692
22800
  return new ClientError(msg, { cause, code });
22693
22801
  }
@@ -24233,6 +24341,7 @@ class DispatchServiceError extends Error {
24233
24341
  mismatches;
24234
24342
  issues;
24235
24343
  changed;
24344
+ textRefusal;
24236
24345
  hint;
24237
24346
  constructor(code, status, message, details = {}) {
24238
24347
  super(message);
@@ -24243,6 +24352,7 @@ class DispatchServiceError extends Error {
24243
24352
  this.mismatches = details.mismatches;
24244
24353
  this.issues = details.issues;
24245
24354
  this.changed = details.changed;
24355
+ this.textRefusal = details.textRefusal ?? false;
24246
24356
  this.hint = details.hint;
24247
24357
  }
24248
24358
  }
@@ -24523,7 +24633,8 @@ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
24523
24633
  if (status === 404 && answer.code === "NOT_FOUND" && answer.error?.startsWith(NO_ROUTE_MESSAGE_PREFIX) === true) {
24524
24634
  return "no-route";
24525
24635
  }
24526
- if (retriesUnderKey(status, answer.code)) {
24636
+ const textRefusal = answer.error !== undefined && answer.response.headers.has(TEXT_REFUSAL_HEADER);
24637
+ if (!textRefusal && retriesUnderKey(status, answer.code)) {
24527
24638
  if (status === 409)
24528
24639
  return "in-flight";
24529
24640
  return status >= 500 ? "server-error" : "try-later";
@@ -24672,8 +24783,15 @@ class DispatchClient {
24672
24783
  async listIssueArtifacts(issue) {
24673
24784
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"]);
24674
24785
  }
24675
- async markdownRoundTrip(markdown) {
24676
- const answer = await this.#writingNothing(["api", "v1", "markdown", "round-trip"], { markdown }, { writes: false });
24786
+ async markdownRoundTrip(markdown, newDocument) {
24787
+ return this.#roundTrip(["api", "v1", "markdown", "round-trip"], { markdown }, newDocument);
24788
+ }
24789
+ async fileRoundTrip(bytes, newDocument) {
24790
+ const file = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
24791
+ return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], { file }, newDocument);
24792
+ }
24793
+ async#roundTrip(path, body, newDocument) {
24794
+ const answer = await this.#writingNothing(path, newDocument ? { ...body, new_document: true } : body, { writes: false });
24677
24795
  return answer.markdown;
24678
24796
  }
24679
24797
  async listProjectArtifacts(project, unlinked = false) {
@@ -25527,7 +25645,10 @@ class DispatchClient {
25527
25645
  if (response.status === 409 && refusal.code === IDEMPOTENCY_KEY_COMMITTED) {
25528
25646
  throw new DispatchWriteLandedError(IDEMPOTENCY_KEY_COMMITTED, response.status, method, requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING));
25529
25647
  }
25530
- throw new DispatchServiceError(refusal.code ?? `HTTP_${response.status}`, response.status, refusal.error, refusal);
25648
+ throw new DispatchServiceError(refusal.code ?? `HTTP_${response.status}`, response.status, refusal.error, {
25649
+ ...refusal,
25650
+ textRefusal: response.headers.has(TEXT_REFUSAL_HEADER)
25651
+ });
25531
25652
  }
25532
25653
  throw this.#gatewayError(method, url, response, text, "Dispatch's error JSON");
25533
25654
  }
@@ -25652,6 +25773,10 @@ function linkFor(href, linkBase) {
25652
25773
  }
25653
25774
 
25654
25775
  // ../envoy-client/src/dispatch-commands/context.ts
25776
+ var DRY_RUN_DEADLINE_MS = 5000;
25777
+ function askOnceWithinDryRun(deadlineMs = DRY_RUN_DEADLINE_MS) {
25778
+ return { deadlineMs, retryNoRoute: false, writeRetry: { ...DISPATCH_WRITE_RETRY, pausesMs: [] } };
25779
+ }
25655
25780
  function stringArg(args, name) {
25656
25781
  const value = args[name];
25657
25782
  if (typeof value !== "string")
@@ -25729,10 +25854,11 @@ function sessionContext(input, checked) {
25729
25854
  configUrl,
25730
25855
  linkBase: linkBaseOf(input.config.publicUrl ?? url),
25731
25856
  hostSession: input.sessionId?.trim(),
25732
- newClient: () => new DispatchClient(url, credential, fetchImpl, {
25857
+ newClient: (options = {}) => new DispatchClient(url, credential, fetchImpl, {
25733
25858
  signal: input.signal,
25734
25859
  writeRetry: input.writeRetry,
25735
- sleep: input.sleep
25860
+ sleep: input.sleep,
25861
+ ...options
25736
25862
  })
25737
25863
  };
25738
25864
  }
@@ -25786,6 +25912,7 @@ var WRITE_ROUTES = [
25786
25912
  { method: "POST", pattern: "/api/v1/issues/{key}/artifacts", commands: ["artifact"] },
25787
25913
  { method: "POST", pattern: "/api/v1/projects/{key}/artifacts", commands: ["artifact"] },
25788
25914
  { method: "POST", pattern: "/api/v1/markdown/round-trip", commands: ["artifact"] },
25915
+ { method: "POST", pattern: "/api/v1/markdown/file-round-trip", commands: ["artifact"] },
25789
25916
  { method: "POST", pattern: "/api/v1/projects", commands: ["project"] },
25790
25917
  {
25791
25918
  method: "PUT",
@@ -28625,14 +28752,14 @@ function brokerCredential(env, session, read) {
28625
28752
  }
28626
28753
 
28627
28754
  // ../envoy-client/src/file-token-credential.ts
28628
- import { readFileSync as readFileSync2 } from "fs";
28755
+ import { readFileSync as readFileSync3 } from "fs";
28629
28756
  var TOKEN_FILE_VAR = "DISPATCH_BROKER_TOKEN_FILE";
28630
28757
  var DPOP_KEY_FILE_VAR = "DISPATCH_BROKER_DPOP_KEY_FILE";
28631
28758
  var PKCS8_LABEL = "PRIVATE KEY";
28632
28759
  var PKCS8_PEM = new RegExp(`^-----BEGIN ${PKCS8_LABEL}-----\\r?\\n(?:[A-Za-z0-9+/=]+\\r?\\n)+-----END ${PKCS8_LABEL}-----$`);
28633
28760
  function readNamed(variable, filePath) {
28634
28761
  try {
28635
- return readFileSync2(filePath, "utf8");
28762
+ return readFileSync3(filePath, "utf8");
28636
28763
  } catch (error) {
28637
28764
  throw new Error(`${variable} names ${filePath}, which could not be read (${readErrorCode(error)})`);
28638
28765
  }
@@ -35549,62 +35676,343 @@ async function loginCommand(argv, env, io) {
35549
35676
  }
35550
35677
  }
35551
35678
 
35552
- // ../envoy-client/src/dispatch-commands/command-context.ts
35553
- function toolActor(origin, input) {
35554
- return {
35555
- kind: "session",
35556
- id: input.sessionId ?? "unknown",
35557
- origin: {
35558
- ...origin,
35559
- host: input.host,
35560
- ...input.sessionTitle === undefined ? {} : { session_title: input.sessionTitle }
35679
+ // ../envoy-client/src/dispatch-commands/stored-text.ts
35680
+ import { resolve as resolvePath2 } from "path";
35681
+
35682
+ // ../envoy-client/src/dispatch-commands/stored-spelling.ts
35683
+ function headedOpener(line) {
35684
+ for (let at = 0;at < line.length; at += Math.max(1, runOf(line, at, ":"))) {
35685
+ const brace = typedFenceBrace(line, at);
35686
+ if (brace === -1)
35687
+ continue;
35688
+ const opener = typedOpenerAt(line, at);
35689
+ return opener === undefined ? undefined : { ...opener, head: line.slice(0, brace + 1) };
35690
+ }
35691
+ return;
35692
+ }
35693
+ function attributesByName(attributes) {
35694
+ const byName = new Map(attributes.map((attribute) => [attribute.name, attribute.text]));
35695
+ return byName.size === attributes.length ? byName : undefined;
35696
+ }
35697
+ function inStoredOrder(given, stored) {
35698
+ const written = attributesByName(given.attributes);
35699
+ if (written === undefined || attributesByName(stored.attributes) === undefined || stored.attributes.length !== given.attributes.length) {
35700
+ return;
35701
+ }
35702
+ let line = `${given.head}${given.gaps[0] ?? ""}`;
35703
+ for (const [index, attribute] of stored.attributes.entries()) {
35704
+ const text = written.get(attribute.name);
35705
+ if (text === undefined)
35706
+ return;
35707
+ line += `${text}${given.gaps[index + 1] ?? ""}`;
35708
+ }
35709
+ return `${line}}`;
35710
+ }
35711
+ function onlyReordered(given, held, stored) {
35712
+ return given !== undefined && stored !== undefined && inStoredOrder(given, stored) === held;
35713
+ }
35714
+ function reorderedBlockLine(line, opener) {
35715
+ const named = `${opener.name} block${opener.id === undefined ? "" : ` ${opener.id}`}`;
35716
+ const order = opener.attributes.map((attribute) => attribute.name).join(", ");
35717
+ return `This upload put the attributes of ${named} (line ${line}) in the order Dispatch stores: ${order}.`;
35718
+ }
35719
+ function attributesReordered(given, stored) {
35720
+ const written = withoutFinalLineFeed(given).split(`
35721
+ `);
35722
+ const holds = withoutFinalLineFeed(stored).split(`
35723
+ `);
35724
+ if (written.length !== holds.length)
35725
+ return;
35726
+ const lines = [];
35727
+ for (const [index, held] of holds.entries()) {
35728
+ const wrote = written[index];
35729
+ if (wrote === held)
35730
+ continue;
35731
+ const opener = headedOpener(held);
35732
+ if (wrote === undefined || opener === undefined || !onlyReordered(headedOpener(wrote), held, opener)) {
35733
+ return;
35561
35734
  }
35562
- };
35735
+ lines.push(reorderedBlockLine(index + 1, opener));
35736
+ }
35737
+ return lines;
35563
35738
  }
35564
- async function commandContext(session) {
35565
- const { input, ownerArguments, pictures } = session;
35566
- const actor = toolActor(await resolveOrigin(input.env ?? process.env, input.exec ?? defaultExec, input.cwd), input);
35567
- const client = session.newClient();
35568
- const { owner, documentOwner, resolveDocument } = await documentTargets(client, ownerArguments);
35569
- const issueArgument = optionalString(input.args, "issue");
35570
- const refText = optionalString(ownerArguments.args, "ref");
35571
- if (input.tool !== "dispatch_ask" && owner?.kind === "issue" && issueArgument !== undefined && refText !== undefined && ownerArguments.ref?.owner.kind === "issue" && owner.issue !== ownerArguments.ref.owner.issue) {
35572
- throw new ToolInputError(input.tool, [
35573
- `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}`
35574
- ]);
35739
+ var STORED_LINE_QUOTED = 200;
35740
+ function quotedStoredLine(characters, from) {
35741
+ const shown = characters.slice(from, from + STORED_LINE_QUOTED);
35742
+ const quote = JSON.stringify(shown.join(""));
35743
+ const cutAfter = from + shown.length < characters.length;
35744
+ if (from === 0 && !cutAfter)
35745
+ return quote;
35746
+ const cut = from === 0 ? "after" : cutAfter ? "before and after" : "before the last";
35747
+ return `${quote} (cut ${cut} ${shown.length} of its ${characters.length} characters)`;
35748
+ }
35749
+ function lineWords(line, opener) {
35750
+ const plain = (text) => (text.match(/\s+|\S+/g) ?? []).map((word) => ({ text: word, attribute: false }));
35751
+ if (opener === undefined)
35752
+ return plain(line);
35753
+ const words = plain(opener.head);
35754
+ for (const [index, gap] of opener.gaps.entries()) {
35755
+ if (gap !== "")
35756
+ words.push({ text: gap, attribute: false });
35757
+ const attribute = opener.attributes[index];
35758
+ if (attribute !== undefined)
35759
+ words.push({ text: attribute.text, attribute: true });
35575
35760
  }
35576
- const issue = () => {
35577
- if (owner?.kind !== "issue")
35578
- throw new Error("issue is required");
35579
- return owner.issue;
35580
- };
35581
- const postWithPictures = (text, owner, upload) => textWithPictures(text, pictures, owner, (picture) => upload(picture).catch((error) => {
35582
- if (!(error instanceof DispatchWriteLandedError))
35583
- throw error;
35584
- 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 });
35585
- }), actor);
35586
- const writePictures = (resolved, text) => {
35587
- if (resolved?.owner.kind === "project") {
35588
- const { project } = resolved.owner;
35589
- return postWithPictures(text, project, (upload) => client.projectArtifact(project, upload));
35761
+ words.push({ text: "}", attribute: false });
35762
+ return words;
35763
+ }
35764
+ function wordText(word, from = 0, characters = Array.from(word.text)) {
35765
+ if (word.attribute)
35766
+ return `the attribute ${word.text}`;
35767
+ return `${/\S/.test(word.text) ? "the word" : "the space"} ${quotedStoredLine(characters, from)}`;
35768
+ }
35769
+ function wordDifference(written, holds) {
35770
+ let before = 0;
35771
+ for (let index = 0;index < Math.max(written.length, holds.length); index += 1) {
35772
+ const given = written[index];
35773
+ const stored = holds[index];
35774
+ if (given !== undefined && stored !== undefined && given.text === stored.text) {
35775
+ before += Array.from(given.text).length;
35776
+ continue;
35590
35777
  }
35591
- const issueKey = issue();
35592
- return postWithPictures(text, issueKey, (upload) => client.artifact(issueKey, upload));
35593
- };
35594
- const { hostSession } = session;
35778
+ if (given === undefined && stored !== undefined) {
35779
+ return `ends after character ${before}, where Dispatch goes on with ${wordText(stored)}`;
35780
+ }
35781
+ if (given !== undefined && stored === undefined) {
35782
+ return `reads ${wordText(given)} at character ${before + 1}, where Dispatch ends the line`;
35783
+ }
35784
+ if (given !== undefined && stored !== undefined) {
35785
+ const wrote = Array.from(given.text);
35786
+ const held = Array.from(stored.text);
35787
+ let from = 0;
35788
+ if (!given.attribute && !stored.attribute && Math.max(wrote.length, held.length) > STORED_LINE_QUOTED) {
35789
+ while (from < wrote.length && wrote[from] === held[from])
35790
+ from += 1;
35791
+ const tail = Math.max(0, from - STORED_LINE_QUOTED);
35792
+ if (from === wrote.length) {
35793
+ return `ends ${wordText(given, tail, wrote)} after character ${before + from}, where Dispatch goes on with ${wordText(stored, from, held)}`;
35794
+ }
35795
+ if (from === held.length) {
35796
+ return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch ends ${wordText(stored, tail, held)}`;
35797
+ }
35798
+ }
35799
+ return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch stores ${wordText(stored, from, held)}`;
35800
+ }
35801
+ }
35802
+ return "differs from the line Dispatch stores";
35803
+ }
35804
+ function attributeDifference(line, given, stored) {
35805
+ const written = attributesByName(given.attributes);
35806
+ if (written === undefined)
35807
+ return;
35808
+ for (const attribute of stored.attributes) {
35809
+ const text = written.get(attribute.name);
35810
+ if (text === undefined)
35811
+ return `Dispatch adds the attribute ${attribute.text} to line ${line}`;
35812
+ if (text !== attribute.text) {
35813
+ return `line ${line} holds the attribute ${text}, which Dispatch stores as ${attribute.text}`;
35814
+ }
35815
+ }
35816
+ const held = new Set(stored.attributes.map((attribute) => attribute.name));
35817
+ const dropped = given.attributes.find((attribute) => !held.has(attribute.name));
35818
+ return dropped === undefined ? undefined : `line ${line} holds the attribute ${dropped.text}, which Dispatch drops`;
35819
+ }
35820
+ function lineDifference(line, wrote, given, held, stored) {
35821
+ if (given === undefined || stored === undefined) {
35822
+ return `line ${line} ${wordDifference(lineWords(wrote, undefined), lineWords(held, undefined))}`;
35823
+ }
35824
+ const attribute = attributeDifference(line, given, stored);
35825
+ if (attribute !== undefined)
35826
+ return attribute;
35827
+ const reordered = inStoredOrder(given, stored);
35828
+ if (reordered !== undefined && reordered !== wrote) {
35829
+ const words = lineWords(reordered, headedOpener(reordered));
35830
+ return `line ${line}, with its attributes put in the order Dispatch stores, ${wordDifference(words, lineWords(held, stored))}`;
35831
+ }
35832
+ return `line ${line} ${wordDifference(lineWords(wrote, given), lineWords(held, stored))}`;
35833
+ }
35834
+ function firstStoredDifference(given, stored) {
35835
+ const written = given.split(`
35836
+ `);
35837
+ const holds = stored.split(`
35838
+ `);
35839
+ for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
35840
+ const wrote = written[line];
35841
+ const held = holds[line];
35842
+ if (wrote === held)
35843
+ continue;
35844
+ if (wrote === undefined && held !== undefined) {
35845
+ return `the store writes a line ${line + 1}, ${quotedStoredLine(Array.from(held), 0)}`;
35846
+ }
35847
+ if (held === undefined && wrote !== undefined) {
35848
+ return `the store drops line ${line + 1}, ${quotedStoredLine(Array.from(wrote), 0)}`;
35849
+ }
35850
+ if (wrote !== undefined && held !== undefined) {
35851
+ const givenOpener = headedOpener(wrote);
35852
+ const storedOpener = headedOpener(held);
35853
+ if (onlyReordered(givenOpener, held, storedOpener))
35854
+ continue;
35855
+ return lineDifference(line + 1, wrote, givenOpener, held, storedOpener);
35856
+ }
35857
+ }
35858
+ return "the stored text differs from the text given";
35859
+ }
35860
+ var STORED_TEXT_PRINTED = 2000;
35861
+ function storedTextPrinted(stored) {
35862
+ if (stored.length <= STORED_TEXT_PRINTED)
35863
+ return { text: stored, cut: "" };
35864
+ const head = stored.slice(0, STORED_TEXT_PRINTED);
35865
+ const lastLineFeed = head.lastIndexOf(`
35866
+ `);
35867
+ const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
35595
35868
  return {
35596
- ...session,
35597
- client,
35598
- actor,
35599
- owner,
35600
- documentOwner,
35601
- resolveDocument,
35602
- issue,
35603
- postWithPictures,
35604
- writePictures,
35605
- shown: hostSession ? shownPictures(hostSession) : undefined
35869
+ text,
35870
+ cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
35606
35871
  };
35607
35872
  }
35873
+ function storedTextProblem(given, stored, name) {
35874
+ const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
35875
+ const printed = storedTextPrinted(stored);
35876
+ return [
35877
+ `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
35878
+ ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
35879
+ `${printed.cut}
35880
+ --- the text Dispatch stores ---
35881
+ ${printed.text}`,
35882
+ "--- end of the text Dispatch stores ---"
35883
+ ].join("");
35884
+ }
35885
+ function withoutFinalLineFeed(text) {
35886
+ return text.endsWith(`
35887
+ `) ? text.slice(0, -1) : text;
35888
+ }
35889
+ function storedUpload(given, stored, name) {
35890
+ if (withoutFinalLineFeed(stored) === withoutFinalLineFeed(given)) {
35891
+ return { sent: given, reordered: [] };
35892
+ }
35893
+ const reordered = attributesReordered(given, stored);
35894
+ return reordered === undefined ? { refusal: storedTextProblem(given, stored, name) } : { sent: stored, reordered };
35895
+ }
35896
+
35897
+ // ../envoy-client/src/dispatch-commands/stored-text.ts
35898
+ var MARKDOWN_ROUND_TRIP = "POST /api/v1/markdown/round-trip";
35899
+ var FILE_ROUND_TRIP = "POST /api/v1/markdown/file-round-trip";
35900
+ function storedTextCheckFailed(failed) {
35901
+ 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.";
35902
+ return new Error(`Dispatch could not say how it would store this text, so nothing was uploaded: ${failed.failure}. ${again}`, { cause: failed.error });
35903
+ }
35904
+ function roundTripRouteAbsent(error) {
35905
+ return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
35906
+ }
35907
+ function documentTooLarge(measured) {
35908
+ const bytes = typeof measured === "number" ? measured : typeof measured === "string" ? utf8Bytes(measured) : measured.byteLength;
35909
+ return bytes > MARKDOWN_DOCUMENT_MAX_BYTES ? new Error(`CAP_EXCEEDED: ${MARKDOWN_DOCUMENT_TOO_LARGE}`) : undefined;
35910
+ }
35911
+ function documentBytesRefusal(field, bytes) {
35912
+ return documentTooLarge(bytes) ?? unstorableBytes(field, bytes);
35913
+ }
35914
+ function documentFieldRefusal(field, text) {
35915
+ return Buffer.byteLength(text, "utf8") > MARKDOWN_DOCUMENT_MAX_BYTES || text.includes("\x00") ? documentBytesRefusal(field, fileTextBytes(text)) : undefined;
35916
+ }
35917
+ function uploadedFile(cwd, path) {
35918
+ return Bun.file(resolvePath2(cwd, path));
35919
+ }
35920
+ async function documentFileRead(file, held) {
35921
+ if (file.type.split(";", 1)[0]?.trim().toLowerCase() !== "text/markdown") {
35922
+ return { kind: "passed", bytes: undefined };
35923
+ }
35924
+ let bytes = held;
35925
+ if (bytes === undefined) {
35926
+ const stats = await file.stat().catch(() => {
35927
+ return;
35928
+ });
35929
+ if (stats !== undefined && !stats.isFile() && !stats.isDirectory()) {
35930
+ return { kind: "passed", bytes: undefined };
35931
+ }
35932
+ const tooLarge = stats === undefined ? undefined : documentTooLarge(stats.size);
35933
+ if (tooLarge !== undefined)
35934
+ return { kind: "refused", refusal: tooLarge };
35935
+ try {
35936
+ bytes = await file.bytes();
35937
+ } catch (error) {
35938
+ return { kind: "unread", error };
35939
+ }
35940
+ }
35941
+ const refusal = documentBytesRefusal("file", bytes);
35942
+ return refusal === undefined ? { kind: "passed", bytes } : { kind: "refused", refusal };
35943
+ }
35944
+ async function documentFileBytes(file, held) {
35945
+ const read = await documentFileRead(file, held);
35946
+ if (read.kind === "refused")
35947
+ throw read.refusal;
35948
+ if (read.kind === "unread")
35949
+ throw read.error;
35950
+ return read.bytes;
35951
+ }
35952
+ function unchecked(answer) {
35953
+ return { kind: "unchecked", failure: answer.failure, routeAbsent: answer.routeAbsent };
35954
+ }
35955
+ async function askRoundTrip(client, route, ask) {
35956
+ const dispatch = client();
35957
+ try {
35958
+ return { kind: "stored", stored: await ask(dispatch) };
35959
+ } catch (error) {
35960
+ const routeAbsent = roundTripRouteAbsent(error);
35961
+ if (!routeAbsent && error instanceof DispatchServiceError && error.textRefusal) {
35962
+ return { kind: "refused", refusal: error };
35963
+ }
35964
+ return {
35965
+ kind: "unanswered",
35966
+ failure: error instanceof DispatchAnswerNotKeptError ? `${route} wrote nothing, and Dispatch kept no copy of its answer (${error.code})` : `${route} failed with ${messageFor(error)}`,
35967
+ error,
35968
+ routeAbsent
35969
+ };
35970
+ }
35971
+ }
35972
+ async function storedTextCheck(client, tool, name, content, force) {
35973
+ const tooLarge = documentTooLarge(content);
35974
+ if (tooLarge !== undefined)
35975
+ return { kind: "refused", refusal: tooLarge };
35976
+ if (content === "")
35977
+ return { kind: "kept" };
35978
+ const answer = await askRoundTrip(client, MARKDOWN_ROUND_TRIP, (dispatch) => dispatch.markdownRoundTrip(content, !force));
35979
+ const blank = goBlankPattern.test(content);
35980
+ switch (answer.kind) {
35981
+ case "refused":
35982
+ return answer;
35983
+ case "unanswered":
35984
+ return blank || answer.routeAbsent ? unchecked(answer) : { kind: "failed", failure: answer.failure, error: answer.error };
35985
+ case "stored": {
35986
+ if (blank)
35987
+ return { kind: "kept" };
35988
+ const upload = storedUpload(content, answer.stored, name);
35989
+ if ("refusal" in upload) {
35990
+ return { kind: "refused", refusal: new ToolInputError(tool, [upload.refusal]) };
35991
+ }
35992
+ return upload.reordered.length === 0 ? { kind: "kept" } : { kind: "reordered", sent: upload.sent, lines: upload.reordered };
35993
+ }
35994
+ }
35995
+ }
35996
+ async function storedFileCheck(client, bytes, force) {
35997
+ const answer = await askRoundTrip(client, FILE_ROUND_TRIP, (dispatch) => dispatch.fileRoundTrip(bytes, !force));
35998
+ switch (answer.kind) {
35999
+ case "stored":
36000
+ return { kind: "kept" };
36001
+ case "refused":
36002
+ return answer;
36003
+ case "unanswered":
36004
+ return unchecked(answer);
36005
+ }
36006
+ }
36007
+ function artifactTextCheck(upload) {
36008
+ const { tool, name, content, bytes, force } = upload;
36009
+ if (content !== undefined) {
36010
+ return () => storedTextCheck(upload.textClient, tool, name, content, force);
36011
+ }
36012
+ if (bytes !== undefined)
36013
+ return () => storedFileCheck(upload.fileClient, bytes, force);
36014
+ return;
36015
+ }
35608
36016
 
35609
36017
  // ../envoy-client/src/dispatch-commands/render-item.ts
35610
36018
  function askSummary({ ask, replies, answers }, askRef, pictures, incoming, outgoing) {
@@ -36451,222 +36859,7 @@ async function sendToAgentCommand(context) {
36451
36859
  }
36452
36860
 
36453
36861
  // ../envoy-client/src/dispatch-commands/documents.ts
36454
- import { resolve as resolvePath2 } from "path";
36455
-
36456
- // ../envoy-client/src/dispatch-commands/stored-spelling.ts
36457
- function headedOpener(line) {
36458
- for (let at = 0;at < line.length; at += Math.max(1, runOf(line, at, ":"))) {
36459
- const brace = typedFenceBrace(line, at);
36460
- if (brace === -1)
36461
- continue;
36462
- const opener = typedOpenerAt(line, at);
36463
- return opener === undefined ? undefined : { ...opener, head: line.slice(0, brace + 1) };
36464
- }
36465
- return;
36466
- }
36467
- function attributesByName(attributes) {
36468
- const byName = new Map(attributes.map((attribute) => [attribute.name, attribute.text]));
36469
- return byName.size === attributes.length ? byName : undefined;
36470
- }
36471
- function inStoredOrder(given, stored) {
36472
- const written = attributesByName(given.attributes);
36473
- if (written === undefined || attributesByName(stored.attributes) === undefined || stored.attributes.length !== given.attributes.length) {
36474
- return;
36475
- }
36476
- let line = `${given.head}${given.gaps[0] ?? ""}`;
36477
- for (const [index, attribute] of stored.attributes.entries()) {
36478
- const text = written.get(attribute.name);
36479
- if (text === undefined)
36480
- return;
36481
- line += `${text}${given.gaps[index + 1] ?? ""}`;
36482
- }
36483
- return `${line}}`;
36484
- }
36485
- function onlyReordered(given, held, stored) {
36486
- return given !== undefined && stored !== undefined && inStoredOrder(given, stored) === held;
36487
- }
36488
- function reorderedBlockLine(line, opener) {
36489
- const named = `${opener.name} block${opener.id === undefined ? "" : ` ${opener.id}`}`;
36490
- const order = opener.attributes.map((attribute) => attribute.name).join(", ");
36491
- return `This upload put the attributes of ${named} (line ${line}) in the order Dispatch stores: ${order}.`;
36492
- }
36493
- function attributesReordered(given, stored) {
36494
- const written = withoutFinalLineFeed(given).split(`
36495
- `);
36496
- const holds = withoutFinalLineFeed(stored).split(`
36497
- `);
36498
- if (written.length !== holds.length)
36499
- return;
36500
- const lines = [];
36501
- for (const [index, held] of holds.entries()) {
36502
- const wrote = written[index];
36503
- if (wrote === held)
36504
- continue;
36505
- const opener = headedOpener(held);
36506
- if (wrote === undefined || opener === undefined || !onlyReordered(headedOpener(wrote), held, opener)) {
36507
- return;
36508
- }
36509
- lines.push(reorderedBlockLine(index + 1, opener));
36510
- }
36511
- return lines;
36512
- }
36513
- var STORED_LINE_QUOTED = 200;
36514
- function quotedStoredLine(characters, from) {
36515
- const shown = characters.slice(from, from + STORED_LINE_QUOTED);
36516
- const quote = JSON.stringify(shown.join(""));
36517
- const cutAfter = from + shown.length < characters.length;
36518
- if (from === 0 && !cutAfter)
36519
- return quote;
36520
- const cut = from === 0 ? "after" : cutAfter ? "before and after" : "before the last";
36521
- return `${quote} (cut ${cut} ${shown.length} of its ${characters.length} characters)`;
36522
- }
36523
- function lineWords(line, opener) {
36524
- const plain = (text) => (text.match(/\s+|\S+/g) ?? []).map((word) => ({ text: word, attribute: false }));
36525
- if (opener === undefined)
36526
- return plain(line);
36527
- const words = plain(opener.head);
36528
- for (const [index, gap] of opener.gaps.entries()) {
36529
- if (gap !== "")
36530
- words.push({ text: gap, attribute: false });
36531
- const attribute = opener.attributes[index];
36532
- if (attribute !== undefined)
36533
- words.push({ text: attribute.text, attribute: true });
36534
- }
36535
- words.push({ text: "}", attribute: false });
36536
- return words;
36537
- }
36538
- function wordText(word, from = 0, characters = Array.from(word.text)) {
36539
- if (word.attribute)
36540
- return `the attribute ${word.text}`;
36541
- return `${/\S/.test(word.text) ? "the word" : "the space"} ${quotedStoredLine(characters, from)}`;
36542
- }
36543
- function wordDifference(written, holds) {
36544
- let before = 0;
36545
- for (let index = 0;index < Math.max(written.length, holds.length); index += 1) {
36546
- const given = written[index];
36547
- const stored = holds[index];
36548
- if (given !== undefined && stored !== undefined && given.text === stored.text) {
36549
- before += Array.from(given.text).length;
36550
- continue;
36551
- }
36552
- if (given === undefined && stored !== undefined) {
36553
- return `ends after character ${before}, where Dispatch goes on with ${wordText(stored)}`;
36554
- }
36555
- if (given !== undefined && stored === undefined) {
36556
- return `reads ${wordText(given)} at character ${before + 1}, where Dispatch ends the line`;
36557
- }
36558
- if (given !== undefined && stored !== undefined) {
36559
- const wrote = Array.from(given.text);
36560
- const held = Array.from(stored.text);
36561
- let from = 0;
36562
- if (!given.attribute && !stored.attribute && Math.max(wrote.length, held.length) > STORED_LINE_QUOTED) {
36563
- while (from < wrote.length && wrote[from] === held[from])
36564
- from += 1;
36565
- const tail = Math.max(0, from - STORED_LINE_QUOTED);
36566
- if (from === wrote.length) {
36567
- return `ends ${wordText(given, tail, wrote)} after character ${before + from}, where Dispatch goes on with ${wordText(stored, from, held)}`;
36568
- }
36569
- if (from === held.length) {
36570
- return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch ends ${wordText(stored, tail, held)}`;
36571
- }
36572
- }
36573
- return `reads ${wordText(given, from, wrote)} at character ${before + from + 1}, where Dispatch stores ${wordText(stored, from, held)}`;
36574
- }
36575
- }
36576
- return "differs from the line Dispatch stores";
36577
- }
36578
- function attributeDifference(line, given, stored) {
36579
- const written = attributesByName(given.attributes);
36580
- if (written === undefined)
36581
- return;
36582
- for (const attribute of stored.attributes) {
36583
- const text = written.get(attribute.name);
36584
- if (text === undefined)
36585
- return `Dispatch adds the attribute ${attribute.text} to line ${line}`;
36586
- if (text !== attribute.text) {
36587
- return `line ${line} holds the attribute ${text}, which Dispatch stores as ${attribute.text}`;
36588
- }
36589
- }
36590
- const held = new Set(stored.attributes.map((attribute) => attribute.name));
36591
- const dropped = given.attributes.find((attribute) => !held.has(attribute.name));
36592
- return dropped === undefined ? undefined : `line ${line} holds the attribute ${dropped.text}, which Dispatch drops`;
36593
- }
36594
- function lineDifference(line, wrote, given, held, stored) {
36595
- if (given === undefined || stored === undefined) {
36596
- return `line ${line} ${wordDifference(lineWords(wrote, undefined), lineWords(held, undefined))}`;
36597
- }
36598
- const attribute = attributeDifference(line, given, stored);
36599
- if (attribute !== undefined)
36600
- return attribute;
36601
- const reordered = inStoredOrder(given, stored);
36602
- if (reordered !== undefined && reordered !== wrote) {
36603
- const words = lineWords(reordered, headedOpener(reordered));
36604
- return `line ${line}, with its attributes put in the order Dispatch stores, ${wordDifference(words, lineWords(held, stored))}`;
36605
- }
36606
- return `line ${line} ${wordDifference(lineWords(wrote, given), lineWords(held, stored))}`;
36607
- }
36608
- function firstStoredDifference(given, stored) {
36609
- const written = given.split(`
36610
- `);
36611
- const holds = stored.split(`
36612
- `);
36613
- for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
36614
- const wrote = written[line];
36615
- const held = holds[line];
36616
- if (wrote === held)
36617
- continue;
36618
- if (wrote === undefined && held !== undefined) {
36619
- return `the store writes a line ${line + 1}, ${quotedStoredLine(Array.from(held), 0)}`;
36620
- }
36621
- if (held === undefined && wrote !== undefined) {
36622
- return `the store drops line ${line + 1}, ${quotedStoredLine(Array.from(wrote), 0)}`;
36623
- }
36624
- if (wrote !== undefined && held !== undefined) {
36625
- const givenOpener = headedOpener(wrote);
36626
- const storedOpener = headedOpener(held);
36627
- if (onlyReordered(givenOpener, held, storedOpener))
36628
- continue;
36629
- return lineDifference(line + 1, wrote, givenOpener, held, storedOpener);
36630
- }
36631
- }
36632
- return "the stored text differs from the text given";
36633
- }
36634
- var STORED_TEXT_PRINTED = 2000;
36635
- function storedTextPrinted(stored) {
36636
- if (stored.length <= STORED_TEXT_PRINTED)
36637
- return { text: stored, cut: "" };
36638
- const head = stored.slice(0, STORED_TEXT_PRINTED);
36639
- const lastLineFeed = head.lastIndexOf(`
36640
- `);
36641
- const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
36642
- return {
36643
- text,
36644
- cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
36645
- };
36646
- }
36647
- function storedTextProblem(given, stored, name) {
36648
- const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
36649
- const printed = storedTextPrinted(stored);
36650
- return [
36651
- `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
36652
- ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
36653
- `${printed.cut}
36654
- --- the text Dispatch stores ---
36655
- ${printed.text}`,
36656
- "--- end of the text Dispatch stores ---"
36657
- ].join("");
36658
- }
36659
- function withoutFinalLineFeed(text) {
36660
- return text.endsWith(`
36661
- `) ? text.slice(0, -1) : text;
36662
- }
36663
- function storedUpload(given, stored, name) {
36664
- if (withoutFinalLineFeed(stored) === withoutFinalLineFeed(given)) {
36665
- return { sent: given, reordered: [] };
36666
- }
36667
- const reordered = attributesReordered(given, stored);
36668
- return reordered === undefined ? { refusal: storedTextProblem(given, stored, name) } : { sent: stored, reordered };
36669
- }
36862
+ import { resolve as resolvePath3 } from "path";
36670
36863
 
36671
36864
  // ../envoy-client/src/dispatch-commands/upload-checks.ts
36672
36865
  function artifactUnderName(artifacts, name) {
@@ -36689,20 +36882,6 @@ function artifactNameExistsProblem(held, owner, upload) {
36689
36882
  const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
36690
36883
  return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${rule}`;
36691
36884
  }
36692
- function storedTextCheckFailed(error, name) {
36693
- if (error instanceof DispatchAnswerNotKeptError) {
36694
- return `Dispatch could not say how it would store this text, so nothing was uploaded: POST /api/v1/markdown/round-trip wrote nothing, and Dispatch kept no copy of its answer (${error.code}). Send the upload again, which asks it under a new key.`;
36695
- }
36696
- const failure = `Dispatch could not say how it would store this text, so nothing was uploaded: POST /api/v1/markdown/round-trip failed with ${messageFor(error)}.`;
36697
- if (!dispatchAnswered(error, 413)) {
36698
- return `${failure} Send the upload again once that call is answered.`;
36699
- }
36700
- const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
36701
- return `${failure} This text is longer than the check reads, and sending the upload again does not change that: a markdown document is at most 1 MiB, so shorten it or split it across documents of at most that.${asBytes}`;
36702
- }
36703
- function roundTripRouteAbsent(error) {
36704
- return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
36705
- }
36706
36885
 
36707
36886
  // ../envoy-client/src/dispatch-commands/documents.ts
36708
36887
  async function blockAsks(client, resolved, state) {
@@ -37067,7 +37246,7 @@ async function planApproveCommand(context) {
37067
37246
  };
37068
37247
  }
37069
37248
  async function artifactCommand(context) {
37070
- const { args, client, actor, input, documentOwner, issue } = context;
37249
+ const { args, client, actor, input, documentOwner, issue, newClient } = context;
37071
37250
  const summary = optionalString(args, "summary");
37072
37251
  const name = stringArg(args, "name");
37073
37252
  const content = optionalString(args, "content");
@@ -37080,40 +37259,40 @@ async function artifactCommand(context) {
37080
37259
  actor
37081
37260
  };
37082
37261
  const artifactOwner = documentOwner();
37262
+ const force = optionalBoolean(args, "force") === true;
37083
37263
  const blank = content === undefined || goBlankPattern.test(content);
37084
- if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
37264
+ const file = path === undefined ? undefined : uploadedFile(input.cwd, path);
37265
+ const heldBytes = input.uploadBytes === undefined ? undefined : new Uint8Array(input.uploadBytes);
37266
+ const documentBytes = file === undefined ? undefined : await documentFileBytes(file, heldBytes);
37267
+ const check = artifactTextCheck({
37268
+ tool: input.tool,
37269
+ name,
37270
+ content,
37271
+ bytes: documentBytes,
37272
+ force,
37273
+ textClient: () => client,
37274
+ fileClient: () => newClient(askOnceWithinDryRun())
37275
+ });
37276
+ const stored = await check?.();
37277
+ if (stored?.kind === "refused")
37278
+ throw stored.refusal;
37279
+ if (stored?.kind === "failed")
37280
+ throw storedTextCheckFailed(stored);
37281
+ if ((path !== undefined || !blank) && !force) {
37085
37282
  const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
37086
37283
  if (held !== undefined) {
37087
- const kind = await uploadKindOf(path, (named) => input.uploadBytes === undefined ? readPictureHead(resolvePath2(input.cwd, named)) : Promise.resolve(input.uploadBytes.subarray(0, PICTURE_SNIFF_BYTES)));
37284
+ const kind = await uploadKindOf(path, (named) => input.uploadBytes === undefined ? readPictureHead(resolvePath3(input.cwd, named)) : Promise.resolve(input.uploadBytes.subarray(0, PICTURE_SNIFF_BYTES)));
37088
37285
  throw new ToolInputError(input.tool, [
37089
37286
  artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`, kind)
37090
37287
  ]);
37091
37288
  }
37092
37289
  }
37093
- let sent = content;
37094
- let reordered = [];
37095
- if (!blank) {
37096
- let stored;
37097
- try {
37098
- stored = await client.markdownRoundTrip(content);
37099
- } catch (error) {
37100
- if (!roundTripRouteAbsent(error)) {
37101
- throw new Error(storedTextCheckFailed(error, name), { cause: error });
37102
- }
37103
- }
37104
- if (stored !== undefined) {
37105
- const upload = storedUpload(content, stored, name);
37106
- if ("refusal" in upload)
37107
- throw new ToolInputError(input.tool, [upload.refusal]);
37108
- sent = upload.sent;
37109
- reordered = upload.reordered;
37110
- }
37111
- }
37112
- const artifactInput = path !== undefined ? {
37290
+ const fileBytes = documentBytes ?? heldBytes;
37291
+ const sent = stored?.kind === "reordered" ? stored.sent : content;
37292
+ const reordered = stored?.kind === "reordered" ? stored.lines : [];
37293
+ const artifactInput = file !== undefined ? {
37113
37294
  ...options,
37114
- file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
37115
- type: Bun.file(resolvePath2(input.cwd, path)).type
37116
- })
37295
+ file: fileBytes === undefined ? file : new Blob([fileBytes], { type: file.type })
37117
37296
  } : sent !== undefined ? { ...options, content: sent } : options;
37118
37297
  const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
37119
37298
  const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
@@ -37141,6 +37320,59 @@ async function artifactCommand(context) {
37141
37320
  }
37142
37321
  };
37143
37322
  }
37323
+ function endedSentence(text) {
37324
+ return /[.!?]$/.test(text) ? text : `${text}.`;
37325
+ }
37326
+ async function artifactDryRun(context) {
37327
+ const { tool, args, cwd, uploadBytes, client, deadline, deadlineMs } = context;
37328
+ const content = optionalString(args, "content");
37329
+ const path = optionalString(args, "path");
37330
+ let bytes;
37331
+ if (content === undefined && path !== undefined) {
37332
+ try {
37333
+ bytes = await documentFileBytes(uploadedFile(cwd, path), uploadBytes);
37334
+ } catch (error) {
37335
+ return {
37336
+ kind: "refused",
37337
+ refusal: error instanceof Error ? error : new Error(messageFor(error))
37338
+ };
37339
+ }
37340
+ }
37341
+ const check = artifactTextCheck({
37342
+ tool,
37343
+ name: stringArg(args, "name"),
37344
+ content,
37345
+ bytes,
37346
+ force: optionalBoolean(args, "force") === true,
37347
+ textClient: client,
37348
+ fileClient: client
37349
+ });
37350
+ if (check === undefined)
37351
+ return { kind: "passed" };
37352
+ const subject = content === undefined ? "the file" : "the text";
37353
+ const uploadsUnchecked = content === undefined ? "The call asks once more, and uploads the file unchecked if it gets no answer either." : "The call uploads the text unchecked.";
37354
+ const unasked = (why, then) => ({
37355
+ kind: "passed",
37356
+ warning: `dispatch: warning: the dry run could not ask Dispatch about ${subject}: ${endedSentence(why)} ${then}`
37357
+ });
37358
+ let stored;
37359
+ try {
37360
+ stored = await check();
37361
+ } catch (error) {
37362
+ return unasked(messageFor(error), "The call is refused for the same reason.");
37363
+ }
37364
+ if (stored.kind === "kept" || stored.kind === "reordered")
37365
+ return { kind: "passed" };
37366
+ if (stored.kind === "refused")
37367
+ return { kind: "refused", refusal: stored.refusal };
37368
+ if (stored.kind === "unchecked" && stored.routeAbsent) {
37369
+ return {
37370
+ kind: "passed",
37371
+ warning: `dispatch: warning: this Dispatch cannot check ${subject}: ${endedSentence(stored.failure)} ${uploadsUnchecked}`
37372
+ };
37373
+ }
37374
+ return unasked(deadline.aborted ? `Dispatch gave no answer within ${deadlineMs / 1000} s` : stored.failure, stored.kind === "unchecked" ? uploadsUnchecked : "The call refuses the upload until Dispatch answers.");
37375
+ }
37144
37376
 
37145
37377
  // ../envoy-client/src/dispatch-commands/handoffs.ts
37146
37378
  async function handoffWriteCommand(context) {
@@ -37699,7 +37931,7 @@ async function reviewCommand(context) {
37699
37931
  }
37700
37932
 
37701
37933
  // ../envoy-client/src/session-answers.ts
37702
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3 } from "fs";
37934
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "fs";
37703
37935
  import { join as join8 } from "path";
37704
37936
 
37705
37937
  // ../envoy-client/src/json-line-record.ts
@@ -37840,7 +38072,7 @@ processGlobal2[STATE_KEY] = state;
37840
38072
  var CACHE_FILE = "answers.json";
37841
38073
  function readCacheFile(directory, url) {
37842
38074
  try {
37843
- const value = JSON.parse(readFileSync3(join8(directory, CACHE_FILE), "utf-8"));
38075
+ const value = JSON.parse(readFileSync4(join8(directory, CACHE_FILE), "utf-8"));
37844
38076
  if (typeof value === "object" && value !== null && "dispatch_url" in value && typeof value.dispatch_url === "string" && value.dispatch_url === url && "read_at" in value && typeof value.read_at === "string" && "total" in value && typeof value.total === "number" && "items" in value && Array.isArray(value.items)) {
37845
38077
  return {
37846
38078
  dispatch_url: value.dispatch_url,
@@ -38315,7 +38547,12 @@ var dispatchCommands = {
38315
38547
  dispatch_review: acting(reviewCommand),
38316
38548
  dispatch_result: acting(resultCommand),
38317
38549
  dispatch_results: acting(resultsCommand),
38318
- dispatch_artifact: acting(artifactCommand),
38550
+ dispatch_artifact: {
38551
+ ...acting(artifactCommand),
38552
+ dryRun: artifactDryRun,
38553
+ documentFields: ["content"],
38554
+ documentPathField: "path"
38555
+ },
38319
38556
  dispatch_handoff_write: acting(handoffWriteCommand),
38320
38557
  dispatch_handoff_read: acting(handoffReadCommand),
38321
38558
  dispatch_steps: acting(stepsCommand),
@@ -38327,6 +38564,63 @@ var dispatchCommands = {
38327
38564
  dispatch_api: onSession(apiCommand),
38328
38565
  dispatch_inbox: onSession(inboxCommand)
38329
38566
  };
38567
+
38568
+ // ../envoy-client/src/dispatch-commands/command-context.ts
38569
+ function toolActor(origin, input) {
38570
+ return {
38571
+ kind: "session",
38572
+ id: input.sessionId ?? "unknown",
38573
+ origin: {
38574
+ ...origin,
38575
+ host: input.host,
38576
+ ...input.sessionTitle === undefined ? {} : { session_title: input.sessionTitle }
38577
+ }
38578
+ };
38579
+ }
38580
+ async function commandContext(session) {
38581
+ const { input, ownerArguments, pictures } = session;
38582
+ const actor = toolActor(await resolveOrigin(input.env ?? process.env, input.exec ?? defaultExec, input.cwd), input);
38583
+ const client = session.newClient();
38584
+ const { owner, documentOwner, resolveDocument } = await documentTargets(client, ownerArguments);
38585
+ const issueArgument = optionalString(input.args, "issue");
38586
+ const refText = optionalString(ownerArguments.args, "ref");
38587
+ if (input.tool !== "dispatch_ask" && owner?.kind === "issue" && issueArgument !== undefined && refText !== undefined && ownerArguments.ref?.owner.kind === "issue" && owner.issue !== ownerArguments.ref.owner.issue) {
38588
+ throw new ToolInputError(input.tool, [
38589
+ `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}`
38590
+ ]);
38591
+ }
38592
+ const issue = () => {
38593
+ if (owner?.kind !== "issue")
38594
+ throw new Error("issue is required");
38595
+ return owner.issue;
38596
+ };
38597
+ const postWithPictures = (text, owner, upload) => textWithPictures(text, pictures, owner, (picture) => upload(picture).catch((error) => {
38598
+ if (!(error instanceof DispatchWriteLandedError))
38599
+ throw error;
38600
+ 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 });
38601
+ }), actor);
38602
+ const writePictures = (resolved, text) => {
38603
+ if (resolved?.owner.kind === "project") {
38604
+ const { project } = resolved.owner;
38605
+ return postWithPictures(text, project, (upload) => client.projectArtifact(project, upload));
38606
+ }
38607
+ const issueKey = issue();
38608
+ return postWithPictures(text, issueKey, (upload) => client.artifact(issueKey, upload));
38609
+ };
38610
+ const { hostSession } = session;
38611
+ return {
38612
+ ...session,
38613
+ client,
38614
+ actor,
38615
+ owner,
38616
+ documentOwner,
38617
+ resolveDocument,
38618
+ issue,
38619
+ postWithPictures,
38620
+ writePictures,
38621
+ shown: hostSession ? shownPictures(hostSession) : undefined
38622
+ };
38623
+ }
38330
38624
  // ../envoy-client/src/dispatch-execute.ts
38331
38625
  async function executeDispatchTool(input) {
38332
38626
  const checked = await checkDispatchCall({
@@ -38336,7 +38630,7 @@ async function executeDispatchTool(input) {
38336
38630
  if (checked.problems.length > 0)
38337
38631
  throw new ToolInputError(input.tool, checked.problems);
38338
38632
  if (input.dryRun === true && !dryRunAsksDispatch(input.tool, checked.args)) {
38339
- throw new Error(`dispatch ${input.tool}'s dry run asks Dispatch nothing`);
38633
+ throw new Error(`dispatch ${input.tool}'s dry run runs no command`);
38340
38634
  }
38341
38635
  const command = dispatchCommands[input.tool];
38342
38636
  if (command === undefined)
@@ -38354,7 +38648,7 @@ import {
38354
38648
  mkdirSync as mkdirSync3,
38355
38649
  openSync as openSync3,
38356
38650
  readdirSync as readdirSync2,
38357
- readFileSync as readFileSync4,
38651
+ readFileSync as readFileSync5,
38358
38652
  readSync as readSync2,
38359
38653
  rmSync as rmSync3,
38360
38654
  statSync as statSync2,
@@ -38377,7 +38671,7 @@ function ensureDirectory(dir) {
38377
38671
  }
38378
38672
  function readIfPresent(path) {
38379
38673
  try {
38380
- return readFileSync4(path, "utf-8");
38674
+ return readFileSync5(path, "utf-8");
38381
38675
  } catch (error) {
38382
38676
  if (hasErrnoCode(error, "ENOENT"))
38383
38677
  return;
@@ -38495,12 +38789,12 @@ function pruneSessions(root, now) {
38495
38789
 
38496
38790
  // ../envoy-client/src/process-ancestry.ts
38497
38791
  import { execFileSync } from "child_process";
38498
- import { readFileSync as readFileSync5 } from "fs";
38792
+ import { readFileSync as readFileSync6 } from "fs";
38499
38793
  var MAX_ANCESTORS = 64;
38500
38794
  var PARENT_LOOKUP_MS = 1000;
38501
38795
  function procParentPid(pid) {
38502
38796
  try {
38503
- const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
38797
+ const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
38504
38798
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
38505
38799
  return Number.isInteger(parent) ? parent : undefined;
38506
38800
  } catch {
@@ -38542,7 +38836,7 @@ function isAncestor(candidate, pid = process.pid) {
38542
38836
  }
38543
38837
  function procCommand(pid) {
38544
38838
  try {
38545
- return readFileSync5(`/proc/${pid}/comm`, "utf8").trim();
38839
+ return readFileSync6(`/proc/${pid}/comm`, "utf8").trim();
38546
38840
  } catch {
38547
38841
  return;
38548
38842
  }
@@ -39199,6 +39493,9 @@ function stateWriteFailed(problem) {
39199
39493
  }
39200
39494
  var LITERAL_FORM = "AskGate reviews a Dispatch write, and lets it post, only when it is sent as one bash call of literal words: `dispatch <command> <words\u2026>`. Each word is plain text, text in single quotes (also over more than one line), or text in double quotes with no `$`, backtick or `\\`. A `\\` at the end of a line continues the command. Before it, one `cd <path> &&` is permitted; after it, one `2>&1`, one here-document opened with a quoted delimiter (`<<'EOF'`) and one `| head -n N` or `| tail -n N`. For text with `$` or a backtick in it, use `--<field>-file - <<'EOF'`. A variable, `~`, a glob, an assignment, another redirect (`2>/dev/null`, `> file`), another pipe, another command (`;`, `&&`, `||`), a loop, xargs, `bash -c`, a script, an alias, or a process that a program or an eval cell starts carries no marker.";
39201
39495
  var SUBSCRIPTIONS_TIMEOUT_MS = 1500;
39496
+ function dispatchOffText(off) {
39497
+ return off.error === null ? off.notice : `dispatch config: ${off.error}`;
39498
+ }
39202
39499
  function fitOutput(text, pictures, kept, limit, writeFull) {
39203
39500
  const whole = [text, ...pictures, ...kept].join(`
39204
39501
  `);
@@ -39313,6 +39610,30 @@ async function runDispatchCli(argv, rawEnv, io) {
39313
39610
  `)}`, "Run dispatch --help."].join(`
39314
39611
  `), USAGE) : refuse(new ToolInputError(parsed.tool, parsed.problems, defined("aboutAFlag", parsed.aboutAFlag)).message, USAGE, parsed.tool);
39315
39612
  }
39613
+ const command = dispatchCommands[parsed.tool];
39614
+ const documentFields = command?.documentFields ?? [];
39615
+ if (parsed.kind === "unstorable") {
39616
+ const { tool, field, bytes } = parsed;
39617
+ const refusal = (documentFields.includes(field) ? documentBytesRefusal : unstorableBytes)(field, bytes);
39618
+ return refuse(messageFor(refusal), REFUSED, tool);
39619
+ }
39620
+ for (const field of documentFields) {
39621
+ const text = parsed.args[field];
39622
+ if (typeof text !== "string")
39623
+ continue;
39624
+ const refusal = documentFieldRefusal(field, text);
39625
+ if (refusal !== undefined)
39626
+ return refuse(messageFor(refusal), REFUSED, parsed.tool);
39627
+ }
39628
+ const uploadPath = command?.documentPathField === undefined ? undefined : parsed.args[command.documentPathField];
39629
+ let pathBytes;
39630
+ if (typeof uploadPath === "string") {
39631
+ const read = await documentFileRead(uploadedFile(io.cwd, uploadPath));
39632
+ if (read.kind === "refused")
39633
+ return refuse(messageFor(read.refusal), REFUSED, parsed.tool);
39634
+ if (read.kind === "passed")
39635
+ pathBytes = read.bytes;
39636
+ }
39316
39637
  if (parsed.tool === "dispatch_api" && ledgerHost() === undefined) {
39317
39638
  const { problems, args } = await checkDispatchCall({
39318
39639
  tool: parsed.tool,
@@ -39361,20 +39682,52 @@ async function runDispatchCli(argv, rawEnv, io) {
39361
39682
  return refuse(messageFor(error), USAGE, parsed.tool);
39362
39683
  }
39363
39684
  if (parsed.dryRun && !dryRunAsksDispatch(parsed.tool, parsed.args)) {
39364
- const settings = file.path === null ? null : (await sessionDispatchSettings(file, env, {
39685
+ const resolved = await sessionDispatchSettings(file, env, {
39365
39686
  cwd: io.cwd,
39366
39687
  session: sessionId,
39367
39688
  tokenFiles: true
39368
- })).dispatch;
39369
- const { problems } = await checkDispatchCall({
39689
+ });
39690
+ const settings = resolved.dispatch;
39691
+ const checked = await checkDispatchCall({
39370
39692
  tool: parsed.tool,
39371
39693
  args: parsed.args,
39372
39694
  cwd: io.cwd,
39373
39695
  env,
39374
- serverUrls: settings?.enabled === true ? dispatchServerUrls(settings) : []
39696
+ serverUrls: settings.enabled ? dispatchServerUrls(settings) : []
39375
39697
  });
39376
- if (problems.length > 0) {
39377
- return refuse(new ToolInputError(parsed.tool, problems).message, USAGE, parsed.tool);
39698
+ if (checked.problems.length > 0) {
39699
+ return refuse(new ToolInputError(parsed.tool, checked.problems).message, USAGE, parsed.tool);
39700
+ }
39701
+ const step = command?.dryRun;
39702
+ if (step !== undefined && env.DISPATCH_DRY_RUN_LOCAL !== "1") {
39703
+ const deadlineMs = io.dryRunDeadlineMs ?? DRY_RUN_DEADLINE_MS;
39704
+ const deadline = AbortSignal.timeout(deadlineMs);
39705
+ const verdict = await step({
39706
+ tool: parsed.tool,
39707
+ args: checked.args,
39708
+ cwd: io.cwd,
39709
+ ...defined("uploadBytes", pathBytes),
39710
+ deadline,
39711
+ deadlineMs,
39712
+ client: () => {
39713
+ for (const warning of resolved.warnings)
39714
+ io.stderr(`dispatch: ${warning}
39715
+ `);
39716
+ if (!settings.enabled) {
39717
+ throw new Error(file.path === null ? file.error : dispatchOffText(settings));
39718
+ }
39719
+ return new DispatchClient(settings.url, settings.credential, io.fetchImpl ?? fetch, {
39720
+ signal: deadline,
39721
+ ...askOnceWithinDryRun(deadlineMs)
39722
+ });
39723
+ }
39724
+ });
39725
+ if (verdict.kind === "refused") {
39726
+ return refuse(messageFor(verdict.refusal), verdict.refusal instanceof ToolInputError ? USAGE : REFUSED, parsed.tool);
39727
+ }
39728
+ if (verdict.warning !== undefined)
39729
+ io.stderr(`${verdict.warning}
39730
+ `);
39378
39731
  }
39379
39732
  print(JSON.stringify(parsed.args, null, 2));
39380
39733
  return OK;
@@ -39433,7 +39786,7 @@ ${result.text}`);
39433
39786
  const fd = openSync4(operandPath(io.cwd, file), constants4.O_RDONLY | constants4.O_NONBLOCK);
39434
39787
  try {
39435
39788
  if (fstatSync3(fd).isFile())
39436
- bytes = readFileSync6(fd);
39789
+ bytes = readFileSync7(fd);
39437
39790
  } finally {
39438
39791
  closeSync4(fd);
39439
39792
  }
@@ -39509,7 +39862,7 @@ ${result.text}`);
39509
39862
  tool,
39510
39863
  args,
39511
39864
  cwd: io.cwd,
39512
- ...uploadBytes === undefined ? {} : { uploadBytes },
39865
+ ...defined("uploadBytes", uploadBytes ?? pathBytes),
39513
39866
  host,
39514
39867
  sessionId,
39515
39868
  sessionTitle: env.DISPATCH_SESSION_TITLE ?? readSessionTitle(dir),
@@ -39579,7 +39932,6 @@ ${result.text}`);
39579
39932
  }
39580
39933
 
39581
39934
  // ../envoy-client/bin/dispatch.ts
39582
- var readText = (path) => readFileSync7(path === "-" ? 0 : path, "utf-8");
39583
39935
  var pending = [];
39584
39936
  var writeTo = (stream) => (chunk) => {
39585
39937
  const { promise, resolve } = Promise.withResolvers();
@@ -39590,7 +39942,7 @@ var code = await runDispatchCli(Bun.argv.slice(2), process.env, {
39590
39942
  stdout: writeTo(process.stdout),
39591
39943
  stdoutBytes: writeTo(process.stdout),
39592
39944
  stderr: writeTo(process.stderr),
39593
- readText,
39945
+ readText: readFileText,
39594
39946
  cwd: process.cwd()
39595
39947
  });
39596
39948
  await Promise.all(pending);