@sjawhar/claude-envoy 6.2.0 → 6.2.2

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.
@@ -36399,6 +36399,14 @@ var wholeIdPattern = /^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a
36399
36399
  function isIdPrefix(value) {
36400
36400
  return idPrefixPattern.test(value) && !wholeIdPattern.test(value);
36401
36401
  }
36402
+ function utf8Bytes(value) {
36403
+ let bytes = 0;
36404
+ for (const character of value) {
36405
+ const code = character.codePointAt(0) ?? 0;
36406
+ bytes += code < 128 ? 1 : code < 2048 ? 2 : code < 65536 ? 3 : 4;
36407
+ }
36408
+ return bytes;
36409
+ }
36402
36410
  var PLAIN_ISSUE_TABS = [
36403
36411
  "verification",
36404
36412
  "plan",
@@ -36661,6 +36669,9 @@ var ISSUE_LABEL_MAX = 40;
36661
36669
  var MAX_ISSUE_COMPONENTS = 50;
36662
36670
  var ISSUE_TITLE_MAX = 1000;
36663
36671
  var PROJECT_NAME_MAX = 80;
36672
+ var MARKDOWN_DOCUMENT_MAX_BYTES = 1 << 20;
36673
+ 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`;
36674
+ var TEXT_REFUSAL_HEADER = "Dispatch-Text-Refusal";
36664
36675
  var MAX_ISSUE_PAGE_LIMIT = 250;
36665
36676
  var DEFAULT_ISSUE_PAGE_LIMIT = 50;
36666
36677
  var DEFAULT_ISSUE_READ_EVENTS = 10;
@@ -36957,6 +36968,7 @@ function artifactKindConflictRule(held, upload) {
36957
36968
  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.`;
36958
36969
  }
36959
36970
  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}.`;
36971
+ 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.`;
36960
36972
  var NAME_EXTENSION = /\.([^\s.]+)$/u;
36961
36973
  var MARKDOWN_EXTENSION = /^(md|markdown)$/i;
36962
36974
  function preconditionArgument(z) {
@@ -37744,6 +37756,7 @@ var dispatchToolSpecs = [
37744
37756
  },
37745
37757
  {
37746
37758
  name: "dispatch_result",
37759
+ 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.",
37747
37760
  example: {
37748
37761
  issue: "DSP-1",
37749
37762
  check: "k1",
@@ -37789,14 +37802,15 @@ var dispatchToolSpecs = [
37789
37802
  name: "dispatch_artifact",
37790
37803
  example: { issue: "DSP-1", name: "design.md", content: `# Design
37791
37804
  ` },
37792
- 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}`,
37805
+ 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.`,
37806
+ 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}`,
37793
37807
  arguments: (z) => ({
37794
37808
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
37795
37809
  project: z.string().describe("Project key for an unlinked document.").optional(),
37796
37810
  name: z.string().describe("Artifact filename shown in Dispatch."),
37797
37811
  path: z.string().describe("Local path to the file to upload.").optional(),
37798
37812
  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(),
37799
- 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(),
37813
+ 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(),
37800
37814
  precondition: uploadPreconditionArgument(z),
37801
37815
  summary: z.string().describe("Optional version summary.").optional()
37802
37816
  }),
@@ -47980,6 +47994,7 @@ class DispatchServiceError extends Error {
47980
47994
  mismatches;
47981
47995
  issues;
47982
47996
  changed;
47997
+ textRefusal;
47983
47998
  hint;
47984
47999
  constructor(code, status, message, details = {}) {
47985
48000
  super(message);
@@ -47990,6 +48005,7 @@ class DispatchServiceError extends Error {
47990
48005
  this.mismatches = details.mismatches;
47991
48006
  this.issues = details.issues;
47992
48007
  this.changed = details.changed;
48008
+ this.textRefusal = details.textRefusal ?? false;
47993
48009
  this.hint = details.hint;
47994
48010
  }
47995
48011
  }
@@ -48270,7 +48286,8 @@ function answerEvent(answer, requestKey, keyEchoed, canTellDeadToken) {
48270
48286
  if (status === 404 && answer.code === "NOT_FOUND" && answer.error?.startsWith(NO_ROUTE_MESSAGE_PREFIX) === true) {
48271
48287
  return "no-route";
48272
48288
  }
48273
- if (retriesUnderKey(status, answer.code)) {
48289
+ const textRefusal = answer.error !== undefined && answer.response.headers.has(TEXT_REFUSAL_HEADER);
48290
+ if (!textRefusal && retriesUnderKey(status, answer.code)) {
48274
48291
  if (status === 409)
48275
48292
  return "in-flight";
48276
48293
  return status >= 500 ? "server-error" : "try-later";
@@ -48419,8 +48436,15 @@ class DispatchClient {
48419
48436
  async listIssueArtifacts(issue) {
48420
48437
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"]);
48421
48438
  }
48422
- async markdownRoundTrip(markdown) {
48423
- const answer = await this.#writingNothing(["api", "v1", "markdown", "round-trip"], { markdown }, { writes: false });
48439
+ async markdownRoundTrip(markdown, newDocument) {
48440
+ return this.#roundTrip(["api", "v1", "markdown", "round-trip"], { markdown }, newDocument);
48441
+ }
48442
+ async fileRoundTrip(bytes, newDocument) {
48443
+ const file = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
48444
+ return this.#roundTrip(["api", "v1", "markdown", "file-round-trip"], { file }, newDocument);
48445
+ }
48446
+ async#roundTrip(path, body, newDocument) {
48447
+ const answer = await this.#writingNothing(path, newDocument ? { ...body, new_document: true } : body, { writes: false });
48424
48448
  return answer.markdown;
48425
48449
  }
48426
48450
  async listProjectArtifacts(project, unlinked = false) {
@@ -49274,7 +49298,10 @@ class DispatchClient {
49274
49298
  if (response.status === 409 && refusal.code === IDEMPOTENCY_KEY_COMMITTED) {
49275
49299
  throw new DispatchWriteLandedError(IDEMPOTENCY_KEY_COMMITTED, response.status, method, requestForText(this.#baseUrl, url, DISPATCH_URL_SETTING));
49276
49300
  }
49277
- throw new DispatchServiceError(refusal.code ?? `HTTP_${response.status}`, response.status, refusal.error, refusal);
49301
+ throw new DispatchServiceError(refusal.code ?? `HTTP_${response.status}`, response.status, refusal.error, {
49302
+ ...refusal,
49303
+ textRefusal: response.headers.has(TEXT_REFUSAL_HEADER)
49304
+ });
49278
49305
  }
49279
49306
  throw this.#gatewayError(method, url, response, text, "Dispatch's error JSON");
49280
49307
  }
@@ -49351,7 +49378,7 @@ import {
49351
49378
  mkdirSync as mkdirSync3,
49352
49379
  openSync as openSync3,
49353
49380
  readdirSync as readdirSync2,
49354
- readFileSync as readFileSync4,
49381
+ readFileSync as readFileSync5,
49355
49382
  readSync as readSync2,
49356
49383
  rmSync as rmSync3,
49357
49384
  statSync as statSync2,
@@ -49694,6 +49721,94 @@ function consumeMarker(stores, argv, args, files, now) {
49694
49721
  };
49695
49722
  }
49696
49723
 
49724
+ // ../envoy-client/src/dispatch-file-text.ts
49725
+ import { isUtf8 } from "buffer";
49726
+ import { readFileSync as readFileSync3 } from "fs";
49727
+ var decoder4 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
49728
+ var encoder4 = new TextEncoder;
49729
+ function byteText(byte) {
49730
+ return `0x${byte.toString(16).toUpperCase().padStart(2, "0")}`;
49731
+ }
49732
+
49733
+ class NotUtf8Error extends Error {
49734
+ bytes;
49735
+ name = "NotUtf8Error";
49736
+ constructor(bytes) {
49737
+ super("the bytes are not UTF-8");
49738
+ this.bytes = bytes;
49739
+ }
49740
+ }
49741
+ function firstNotUtf8(bytes) {
49742
+ for (let at = 0;at < bytes.length; ) {
49743
+ const lead = bytes[at];
49744
+ if (lead < 128) {
49745
+ at += 1;
49746
+ continue;
49747
+ }
49748
+ let width;
49749
+ let low = 128;
49750
+ let high = 191;
49751
+ if (lead >= 194 && lead <= 223) {
49752
+ width = 2;
49753
+ } else if (lead >= 224 && lead <= 239) {
49754
+ width = 3;
49755
+ if (lead === 224)
49756
+ low = 160;
49757
+ if (lead === 237)
49758
+ high = 159;
49759
+ } else if (lead >= 240 && lead <= 244) {
49760
+ width = 4;
49761
+ if (lead === 240)
49762
+ low = 144;
49763
+ if (lead === 244)
49764
+ high = 143;
49765
+ } else {
49766
+ return at;
49767
+ }
49768
+ if (at + width > bytes.length)
49769
+ return at;
49770
+ const second = bytes[at + 1];
49771
+ if (second < low || second > high)
49772
+ return at;
49773
+ for (let next = at + 2;next < at + width; next += 1) {
49774
+ if ((bytes[next] & 192) !== 128)
49775
+ return at;
49776
+ }
49777
+ at += width;
49778
+ }
49779
+ return -1;
49780
+ }
49781
+ function firstUnstorable(bytes) {
49782
+ const notUtf8 = isUtf8(bytes) ? -1 : firstNotUtf8(bytes);
49783
+ const nul = bytes.indexOf(0);
49784
+ const at = nul !== -1 && (notUtf8 === -1 || nul < notUtf8) ? nul : notUtf8;
49785
+ if (at === -1)
49786
+ return;
49787
+ return { byte: bytes[at], character: decoder4.decode(bytes.subarray(0, at)).length + 1 };
49788
+ }
49789
+ function unstorableBytes(field, bytes) {
49790
+ const first = firstUnstorable(bytes);
49791
+ if (first === undefined)
49792
+ return;
49793
+ const { byte, character } = first;
49794
+ 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`);
49795
+ }
49796
+ function utf8Text(bytes) {
49797
+ try {
49798
+ return decoder4.decode(bytes);
49799
+ } catch (error) {
49800
+ if (isUtf8(bytes))
49801
+ throw error;
49802
+ throw new NotUtf8Error(bytes);
49803
+ }
49804
+ }
49805
+ function readFileText(path, readStdin = () => readFileSync3(0)) {
49806
+ return utf8Text(path === "-" ? readStdin() : readFileSync3(path));
49807
+ }
49808
+ function fileTextBytes(text) {
49809
+ return encoder4.encode(text);
49810
+ }
49811
+
49697
49812
  // ../envoy-client/src/dispatch-command.ts
49698
49813
  var PREFIXED_FLAGS = [
49699
49814
  {
@@ -49706,6 +49821,7 @@ var PREFIXED_FLAGS = [
49706
49821
  }
49707
49822
  ];
49708
49823
  var STDIN = "-";
49824
+ var FILE_BYTES_RULE = "Bytes that are not UTF-8 are refused in Dispatch's own words, and nothing is sent.";
49709
49825
  var BARE_WORD = /^[A-Za-z0-9_./:@%+=,-]+$/;
49710
49826
  var OPTION_SEPARATOR = ": ";
49711
49827
  var LOCAL_FILE_FIELD = { tool: "dispatch_artifact", field: "path" };
@@ -49748,7 +49864,7 @@ function surfaceFor(tool) {
49748
49864
  spec,
49749
49865
  command: commandName(spec.name),
49750
49866
  fields,
49751
- flags: flagTable(spec.name, fields)
49867
+ flags: flagTable(spec, fields)
49752
49868
  };
49753
49869
  surfaces.set(tool, surface);
49754
49870
  return surface;
@@ -49869,11 +49985,11 @@ function placeholder(info) {
49869
49985
  return info.kind.array === "string" ? "<text>" : "<n>";
49870
49986
  return "<text>";
49871
49987
  }
49872
- function flagTable(tool, fields) {
49988
+ function flagTable(spec, fields) {
49873
49989
  const flags = new Map;
49874
49990
  const add = (flag, entry) => {
49875
49991
  if (flags.has(flag))
49876
- throw new Error(`${tool}: two fields claim the flag ${flag}`);
49992
+ throw new Error(`${spec.name}: two fields claim the flag ${flag}`);
49877
49993
  flags.set(flag, entry);
49878
49994
  };
49879
49995
  for (const [field, info] of fields) {
@@ -49886,7 +50002,7 @@ function flagTable(tool, fields) {
49886
50002
  field,
49887
50003
  action: "file",
49888
50004
  value: "<path>",
49889
- text: `--${name} read from a file; - reads stdin.`
50005
+ text: `--${name} read from a file; - reads stdin. ${FILE_BYTES_RULE}`
49890
50006
  });
49891
50007
  } else if (kind === "number") {
49892
50008
  add(`--${name}`, { field, action: "set", value: "<n>", text: about });
@@ -49919,7 +50035,7 @@ function flagTable(tool, fields) {
49919
50035
  field,
49920
50036
  action: "json-file",
49921
50037
  value: "<path>",
49922
- text: `--${name}-json read from a file; - reads stdin.`
50038
+ text: `--${name}-json read from a file; - reads stdin. ${FILE_BYTES_RULE}`
49923
50039
  });
49924
50040
  } else {
49925
50041
  const none = kind.array === "number-or-null" ? " none is null." : "";
@@ -49930,10 +50046,10 @@ function flagTable(tool, fields) {
49930
50046
  text: `${about} One item per flag, repeated.${none}`.trim()
49931
50047
  });
49932
50048
  for (const prefixed of PREFIXED_FLAGS) {
49933
- if (prefixed.tool !== tool || prefixed.field !== field)
50049
+ if (prefixed.tool !== spec.name || prefixed.field !== field)
49934
50050
  continue;
49935
50051
  if (kind.array !== "string") {
49936
- throw new Error(`${tool}: ${prefixed.flag} needs ${field} to be a list of text`);
50052
+ throw new Error(`${spec.name}: ${prefixed.flag} needs ${field} to be a list of text`);
49937
50053
  }
49938
50054
  add(prefixed.flag, {
49939
50055
  field,
@@ -49955,7 +50071,7 @@ function flagTable(tool, fields) {
49955
50071
  add("--help", { action: "help", text: "Prints this help." });
49956
50072
  add("--dry-run", {
49957
50073
  action: "dry-run",
49958
- 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."
50074
+ text: spec.dryRunHelp ?? "Checks the arguments as the call would, then prints them as JSON and sends nothing."
49959
50075
  });
49960
50076
  return flags;
49961
50077
  }
@@ -49979,7 +50095,8 @@ function parseCommand(argv, io) {
49979
50095
  let help = false;
49980
50096
  let dryRun = false;
49981
50097
  let stdinFlag;
49982
- const read = (flag, path) => {
50098
+ let unstorable;
50099
+ const read = (flag, field, path) => {
49983
50100
  if (path === STDIN) {
49984
50101
  if (stdinFlag !== undefined) {
49985
50102
  problems.push(`${stdinFlag} and ${flag} both read stdin (-); only one flag can`);
@@ -49990,6 +50107,11 @@ function parseCommand(argv, io) {
49990
50107
  try {
49991
50108
  return io.readText(path);
49992
50109
  } catch (error) {
50110
+ if (error instanceof NotUtf8Error) {
50111
+ claim(field, flag, false);
50112
+ unstorable ??= { field, bytes: error.bytes };
50113
+ return;
50114
+ }
49993
50115
  problems.push(`${flag} could not read ${path === STDIN ? "stdin" : path}: ${messageFor(error)}`);
49994
50116
  return;
49995
50117
  }
@@ -50100,14 +50222,14 @@ function parseCommand(argv, io) {
50100
50222
  break;
50101
50223
  }
50102
50224
  case "file": {
50103
- const text = read(flag, value);
50225
+ const text = read(flag, field, value);
50104
50226
  if (text !== undefined && claim(field, flag, false))
50105
50227
  args[field] = text;
50106
50228
  break;
50107
50229
  }
50108
50230
  case "json":
50109
50231
  case "json-file": {
50110
- const text = action === "json" ? value : read(flag, value);
50232
+ const text = action === "json" ? value : read(flag, field, value);
50111
50233
  const parsed = text === undefined ? undefined : json(flag, text);
50112
50234
  if (parsed !== undefined && claim(field, flag, false))
50113
50235
  args[field] = parsed.value;
@@ -50143,6 +50265,8 @@ function parseCommand(argv, io) {
50143
50265
  if (problems.length > 0) {
50144
50266
  return problems.length === bareDashes.size ? { kind: "refused", tool, problems, aboutAFlag: false } : { kind: "refused", tool, problems };
50145
50267
  }
50268
+ if (unstorable !== undefined)
50269
+ return { kind: "unstorable", tool, ...unstorable };
50146
50270
  return { kind: "call", tool, args, dryRun };
50147
50271
  }
50148
50272
  function appendedItem(kind, flag, value, number) {
@@ -50242,7 +50366,7 @@ function commandsHelp() {
50242
50366
  return ` ${commandName(spec.name).padEnd(width)} ${sentence}`;
50243
50367
  }),
50244
50368
  "",
50245
- "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.",
50369
+ "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.",
50246
50370
  "",
50247
50371
  "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).",
50248
50372
  ""
@@ -52878,7 +53002,7 @@ var DISPATCH_BOOKKEEPING = new Set([
52878
53002
  "references_changed_truncated_kinds",
52879
53003
  "rank"
52880
53004
  ]);
52881
- function dispatchPayloadForReader(event, sessionID, issuedAt) {
53005
+ function dispatchPayloadForReader(event, sessionID, issuedAt, toReader) {
52882
53006
  const whole = dispatchPayload(event);
52883
53007
  const changed = event.type !== "issue.created" && isObject3(whole) && Array.isArray(whole["changed"]) ? whole["changed"] : [];
52884
53008
  const payload = withoutEmptyFields(whole, (key, item) => changed.includes(key) || (key === "suggestion" || key === "forced") && item !== null && item !== undefined);
@@ -52891,6 +53015,7 @@ function dispatchPayloadForReader(event, sessionID, issuedAt) {
52891
53015
  case "issue_key":
52892
53016
  return value === event.issue_key;
52893
53017
  case "author":
53018
+ case "actor":
52894
53019
  return isObject3(value) && Object.entries(value).every(([field, held]) => isDeepStrictEqual(held, actor[field]));
52895
53020
  case "created_at": {
52896
53021
  if (typeof value !== "string")
@@ -52901,6 +53026,8 @@ function dispatchPayloadForReader(event, sessionID, issuedAt) {
52901
53026
  case "thread_root_id":
52902
53027
  case "answers":
52903
53028
  return typeof replyTo === "string" && value === replyTo;
53029
+ case "target":
53030
+ return toReader && value === `session:${sessionID}`;
52904
53031
  default:
52905
53032
  return DISPATCH_BOOKKEEPING.has(key);
52906
53033
  }
@@ -53100,6 +53227,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
53100
53227
  let payloadSessions = [];
53101
53228
  let trailer = "";
53102
53229
  const at = inboundTimestamp(envelope.issued_at);
53230
+ const toReader = envelope.topic !== undefined && topicForms(envelope.topic).includes(legacyAgentSubject(sessionID));
53103
53231
  const dispatchRendered = envelope.source === "dispatch" && envelope.payload !== undefined;
53104
53232
  if (envelope.source === "dispatch") {
53105
53233
  const topic = subject ?? envelope.topic;
@@ -53205,15 +53333,16 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
53205
53333
  ask: dispatchReplyRef(frame.event, topic, compact.askId, commentPayload),
53206
53334
  ...compact.record
53207
53335
  };
53208
- const payload = compactRecord === undefined ? dispatchPayloadForReader(frame.event, sessionID, envelope.issued_at) : undefined;
53336
+ const payload = compactRecord === undefined ? dispatchPayloadForReader(frame.event, sessionID, envelope.issued_at, toReader) : undefined;
53209
53337
  let actor = frame.event.actor;
53210
53338
  if ("origin" in frame.event.actor) {
53211
53339
  const { origin, ...rest } = frame.event.actor;
53212
53340
  const title = isObject3(origin) ? origin["session_title"] : undefined;
53213
53341
  actor = typeof title === "string" && title !== "" ? { ...rest, origin: { session_title: title } } : rest;
53214
53342
  }
53343
+ const owner = dispatchOwner(frame.event, topic);
53215
53344
  dispatchEvent = {
53216
- owner: dispatchOwner(frame.event, topic),
53345
+ ...owner === "unknown" ? {} : { owner },
53217
53346
  type: frame.event.type,
53218
53347
  actor,
53219
53348
  ...relation === undefined ? {} : { relation },
@@ -53268,7 +53397,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
53268
53397
  ...dispatchIssue === undefined ? [] : [dispatchIssue]
53269
53398
  ].join(", ") || undefined;
53270
53399
  const rendered = {
53271
- ...envelope.topic !== undefined && topicForms(envelope.topic).includes(legacyAgentSubject(sessionID)) ? { to: `you (${sessionID})` } : {},
53400
+ ...toReader ? { to: `you (${sessionID})` } : {},
53272
53401
  from: senderLabel(envelope),
53273
53402
  at,
53274
53403
  id: envelope.event_id ?? "unknown",
@@ -53813,6 +53942,10 @@ function linkFor(href, linkBase) {
53813
53942
  }
53814
53943
 
53815
53944
  // ../envoy-client/src/dispatch-commands/context.ts
53945
+ var DRY_RUN_DEADLINE_MS = 5000;
53946
+ function askOnceWithinDryRun(deadlineMs = DRY_RUN_DEADLINE_MS) {
53947
+ return { deadlineMs, retryNoRoute: false, writeRetry: { ...DISPATCH_WRITE_RETRY, pausesMs: [] } };
53948
+ }
53816
53949
  function stringArg(args, name) {
53817
53950
  const value = args[name];
53818
53951
  if (typeof value !== "string")
@@ -53890,10 +54023,11 @@ function sessionContext(input, checked) {
53890
54023
  configUrl,
53891
54024
  linkBase: linkBaseOf(input.config.publicUrl ?? url),
53892
54025
  hostSession: input.sessionId?.trim(),
53893
- newClient: () => new DispatchClient(url, credential, fetchImpl, {
54026
+ newClient: (options = {}) => new DispatchClient(url, credential, fetchImpl, {
53894
54027
  signal: input.signal,
53895
54028
  writeRetry: input.writeRetry,
53896
- sleep: input.sleep
54029
+ sleep: input.sleep,
54030
+ ...options
53897
54031
  })
53898
54032
  };
53899
54033
  }
@@ -56562,6 +56696,7 @@ var WRITE_ROUTES = [
56562
56696
  { method: "POST", pattern: "/api/v1/issues/{key}/artifacts", commands: ["artifact"] },
56563
56697
  { method: "POST", pattern: "/api/v1/projects/{key}/artifacts", commands: ["artifact"] },
56564
56698
  { method: "POST", pattern: "/api/v1/markdown/round-trip", commands: ["artifact"] },
56699
+ { method: "POST", pattern: "/api/v1/markdown/file-round-trip", commands: ["artifact"] },
56565
56700
  { method: "POST", pattern: "/api/v1/projects", commands: ["project"] },
56566
56701
  {
56567
56702
  method: "PUT",
@@ -57499,6 +57634,9 @@ async function sendToAgentCommand(context) {
57499
57634
  }
57500
57635
 
57501
57636
  // ../envoy-client/src/dispatch-commands/documents.ts
57637
+ import { resolve as resolvePath3 } from "path";
57638
+
57639
+ // ../envoy-client/src/dispatch-commands/stored-text.ts
57502
57640
  import { resolve as resolvePath2 } from "path";
57503
57641
 
57504
57642
  // ../envoy-client/src/typed-block-opener.ts
@@ -57886,6 +58024,126 @@ function storedUpload(given, stored, name) {
57886
58024
  return reordered === undefined ? { refusal: storedTextProblem(given, stored, name) } : { sent: stored, reordered };
57887
58025
  }
57888
58026
 
58027
+ // ../envoy-client/src/dispatch-commands/stored-text.ts
58028
+ var MARKDOWN_ROUND_TRIP = "POST /api/v1/markdown/round-trip";
58029
+ var FILE_ROUND_TRIP = "POST /api/v1/markdown/file-round-trip";
58030
+ function storedTextCheckFailed(failed) {
58031
+ 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.";
58032
+ return new Error(`Dispatch could not say how it would store this text, so nothing was uploaded: ${failed.failure}. ${again}`, { cause: failed.error });
58033
+ }
58034
+ function roundTripRouteAbsent(error) {
58035
+ return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
58036
+ }
58037
+ function documentTooLarge(measured) {
58038
+ const bytes = typeof measured === "number" ? measured : typeof measured === "string" ? utf8Bytes(measured) : measured.byteLength;
58039
+ return bytes > MARKDOWN_DOCUMENT_MAX_BYTES ? new Error(`CAP_EXCEEDED: ${MARKDOWN_DOCUMENT_TOO_LARGE}`) : undefined;
58040
+ }
58041
+ function documentBytesRefusal(field, bytes) {
58042
+ return documentTooLarge(bytes) ?? unstorableBytes(field, bytes);
58043
+ }
58044
+ function documentFieldRefusal(field, text) {
58045
+ return Buffer.byteLength(text, "utf8") > MARKDOWN_DOCUMENT_MAX_BYTES || text.includes("\x00") ? documentBytesRefusal(field, fileTextBytes(text)) : undefined;
58046
+ }
58047
+ function uploadedFile(cwd, path) {
58048
+ return Bun.file(resolvePath2(cwd, path));
58049
+ }
58050
+ async function documentFileRead(file, held) {
58051
+ if (file.type.split(";", 1)[0]?.trim().toLowerCase() !== "text/markdown") {
58052
+ return { kind: "passed", bytes: undefined };
58053
+ }
58054
+ let bytes = held;
58055
+ if (bytes === undefined) {
58056
+ const stats = await file.stat().catch(() => {
58057
+ return;
58058
+ });
58059
+ if (stats !== undefined && !stats.isFile() && !stats.isDirectory()) {
58060
+ return { kind: "passed", bytes: undefined };
58061
+ }
58062
+ const tooLarge = stats === undefined ? undefined : documentTooLarge(stats.size);
58063
+ if (tooLarge !== undefined)
58064
+ return { kind: "refused", refusal: tooLarge };
58065
+ try {
58066
+ bytes = await file.bytes();
58067
+ } catch (error) {
58068
+ return { kind: "unread", error };
58069
+ }
58070
+ }
58071
+ const refusal = documentBytesRefusal("file", bytes);
58072
+ return refusal === undefined ? { kind: "passed", bytes } : { kind: "refused", refusal };
58073
+ }
58074
+ async function documentFileBytes(file, held) {
58075
+ const read = await documentFileRead(file, held);
58076
+ if (read.kind === "refused")
58077
+ throw read.refusal;
58078
+ if (read.kind === "unread")
58079
+ throw read.error;
58080
+ return read.bytes;
58081
+ }
58082
+ function unchecked(answer) {
58083
+ return { kind: "unchecked", failure: answer.failure, routeAbsent: answer.routeAbsent };
58084
+ }
58085
+ async function askRoundTrip(client, route, ask) {
58086
+ const dispatch = client();
58087
+ try {
58088
+ return { kind: "stored", stored: await ask(dispatch) };
58089
+ } catch (error) {
58090
+ const routeAbsent = roundTripRouteAbsent(error);
58091
+ if (!routeAbsent && error instanceof DispatchServiceError && error.textRefusal) {
58092
+ return { kind: "refused", refusal: error };
58093
+ }
58094
+ return {
58095
+ kind: "unanswered",
58096
+ failure: error instanceof DispatchAnswerNotKeptError ? `${route} wrote nothing, and Dispatch kept no copy of its answer (${error.code})` : `${route} failed with ${messageFor(error)}`,
58097
+ error,
58098
+ routeAbsent
58099
+ };
58100
+ }
58101
+ }
58102
+ async function storedTextCheck(client, tool, name, content, force) {
58103
+ const tooLarge = documentTooLarge(content);
58104
+ if (tooLarge !== undefined)
58105
+ return { kind: "refused", refusal: tooLarge };
58106
+ if (content === "")
58107
+ return { kind: "kept" };
58108
+ const answer = await askRoundTrip(client, MARKDOWN_ROUND_TRIP, (dispatch) => dispatch.markdownRoundTrip(content, !force));
58109
+ const blank = goBlankPattern.test(content);
58110
+ switch (answer.kind) {
58111
+ case "refused":
58112
+ return answer;
58113
+ case "unanswered":
58114
+ return blank || answer.routeAbsent ? unchecked(answer) : { kind: "failed", failure: answer.failure, error: answer.error };
58115
+ case "stored": {
58116
+ if (blank)
58117
+ return { kind: "kept" };
58118
+ const upload = storedUpload(content, answer.stored, name);
58119
+ if ("refusal" in upload) {
58120
+ return { kind: "refused", refusal: new ToolInputError(tool, [upload.refusal]) };
58121
+ }
58122
+ return upload.reordered.length === 0 ? { kind: "kept" } : { kind: "reordered", sent: upload.sent, lines: upload.reordered };
58123
+ }
58124
+ }
58125
+ }
58126
+ async function storedFileCheck(client, bytes, force) {
58127
+ const answer = await askRoundTrip(client, FILE_ROUND_TRIP, (dispatch) => dispatch.fileRoundTrip(bytes, !force));
58128
+ switch (answer.kind) {
58129
+ case "stored":
58130
+ return { kind: "kept" };
58131
+ case "refused":
58132
+ return answer;
58133
+ case "unanswered":
58134
+ return unchecked(answer);
58135
+ }
58136
+ }
58137
+ function artifactTextCheck(upload) {
58138
+ const { tool, name, content, bytes, force } = upload;
58139
+ if (content !== undefined) {
58140
+ return () => storedTextCheck(upload.textClient, tool, name, content, force);
58141
+ }
58142
+ if (bytes !== undefined)
58143
+ return () => storedFileCheck(upload.fileClient, bytes, force);
58144
+ return;
58145
+ }
58146
+
57889
58147
  // ../envoy-client/src/dispatch-commands/upload-checks.ts
57890
58148
  function artifactUnderName(artifacts, name) {
57891
58149
  const written = name.trim();
@@ -57907,20 +58165,6 @@ function artifactNameExistsProblem(held, owner, upload) {
57907
58165
  const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
57908
58166
  return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${rule}`;
57909
58167
  }
57910
- function storedTextCheckFailed(error, name) {
57911
- if (error instanceof DispatchAnswerNotKeptError) {
57912
- 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.`;
57913
- }
57914
- 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)}.`;
57915
- if (!dispatchAnswered(error, 413)) {
57916
- return `${failure} Send the upload again once that call is answered.`;
57917
- }
57918
- const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
57919
- 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}`;
57920
- }
57921
- function roundTripRouteAbsent(error) {
57922
- return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
57923
- }
57924
58168
 
57925
58169
  // ../envoy-client/src/dispatch-commands/documents.ts
57926
58170
  async function blockAsks(client, resolved, state) {
@@ -58285,7 +58529,7 @@ async function planApproveCommand(context) {
58285
58529
  };
58286
58530
  }
58287
58531
  async function artifactCommand(context) {
58288
- const { args, client, actor, input, documentOwner, issue } = context;
58532
+ const { args, client, actor, input, documentOwner, issue, newClient } = context;
58289
58533
  const summary = optionalString(args, "summary");
58290
58534
  const name = stringArg(args, "name");
58291
58535
  const content = optionalString(args, "content");
@@ -58298,40 +58542,40 @@ async function artifactCommand(context) {
58298
58542
  actor
58299
58543
  };
58300
58544
  const artifactOwner = documentOwner();
58545
+ const force = optionalBoolean(args, "force") === true;
58301
58546
  const blank = content === undefined || goBlankPattern.test(content);
58302
- if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
58547
+ const file = path === undefined ? undefined : uploadedFile(input.cwd, path);
58548
+ const heldBytes = input.uploadBytes === undefined ? undefined : new Uint8Array(input.uploadBytes);
58549
+ const documentBytes = file === undefined ? undefined : await documentFileBytes(file, heldBytes);
58550
+ const check = artifactTextCheck({
58551
+ tool: input.tool,
58552
+ name,
58553
+ content,
58554
+ bytes: documentBytes,
58555
+ force,
58556
+ textClient: () => client,
58557
+ fileClient: () => newClient(askOnceWithinDryRun())
58558
+ });
58559
+ const stored = await check?.();
58560
+ if (stored?.kind === "refused")
58561
+ throw stored.refusal;
58562
+ if (stored?.kind === "failed")
58563
+ throw storedTextCheckFailed(stored);
58564
+ if ((path !== undefined || !blank) && !force) {
58303
58565
  const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
58304
58566
  if (held !== undefined) {
58305
- const kind = await uploadKindOf(path, (named) => input.uploadBytes === undefined ? readPictureHead(resolvePath2(input.cwd, named)) : Promise.resolve(input.uploadBytes.subarray(0, PICTURE_SNIFF_BYTES)));
58567
+ const kind = await uploadKindOf(path, (named) => input.uploadBytes === undefined ? readPictureHead(resolvePath3(input.cwd, named)) : Promise.resolve(input.uploadBytes.subarray(0, PICTURE_SNIFF_BYTES)));
58306
58568
  throw new ToolInputError(input.tool, [
58307
58569
  artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`, kind)
58308
58570
  ]);
58309
58571
  }
58310
58572
  }
58311
- let sent = content;
58312
- let reordered = [];
58313
- if (!blank) {
58314
- let stored;
58315
- try {
58316
- stored = await client.markdownRoundTrip(content);
58317
- } catch (error) {
58318
- if (!roundTripRouteAbsent(error)) {
58319
- throw new Error(storedTextCheckFailed(error, name), { cause: error });
58320
- }
58321
- }
58322
- if (stored !== undefined) {
58323
- const upload = storedUpload(content, stored, name);
58324
- if ("refusal" in upload)
58325
- throw new ToolInputError(input.tool, [upload.refusal]);
58326
- sent = upload.sent;
58327
- reordered = upload.reordered;
58328
- }
58329
- }
58330
- const artifactInput = path !== undefined ? {
58573
+ const fileBytes = documentBytes ?? heldBytes;
58574
+ const sent = stored?.kind === "reordered" ? stored.sent : content;
58575
+ const reordered = stored?.kind === "reordered" ? stored.lines : [];
58576
+ const artifactInput = file !== undefined ? {
58331
58577
  ...options,
58332
- file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
58333
- type: Bun.file(resolvePath2(input.cwd, path)).type
58334
- })
58578
+ file: fileBytes === undefined ? file : new Blob([fileBytes], { type: file.type })
58335
58579
  } : sent !== undefined ? { ...options, content: sent } : options;
58336
58580
  const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
58337
58581
  const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
@@ -58359,6 +58603,59 @@ async function artifactCommand(context) {
58359
58603
  }
58360
58604
  };
58361
58605
  }
58606
+ function endedSentence(text) {
58607
+ return /[.!?]$/.test(text) ? text : `${text}.`;
58608
+ }
58609
+ async function artifactDryRun(context) {
58610
+ const { tool, args, cwd, uploadBytes, client, deadline, deadlineMs } = context;
58611
+ const content = optionalString(args, "content");
58612
+ const path = optionalString(args, "path");
58613
+ let bytes;
58614
+ if (content === undefined && path !== undefined) {
58615
+ try {
58616
+ bytes = await documentFileBytes(uploadedFile(cwd, path), uploadBytes);
58617
+ } catch (error) {
58618
+ return {
58619
+ kind: "refused",
58620
+ refusal: error instanceof Error ? error : new Error(messageFor(error))
58621
+ };
58622
+ }
58623
+ }
58624
+ const check = artifactTextCheck({
58625
+ tool,
58626
+ name: stringArg(args, "name"),
58627
+ content,
58628
+ bytes,
58629
+ force: optionalBoolean(args, "force") === true,
58630
+ textClient: client,
58631
+ fileClient: client
58632
+ });
58633
+ if (check === undefined)
58634
+ return { kind: "passed" };
58635
+ const subject = content === undefined ? "the file" : "the text";
58636
+ 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.";
58637
+ const unasked = (why, then) => ({
58638
+ kind: "passed",
58639
+ warning: `dispatch: warning: the dry run could not ask Dispatch about ${subject}: ${endedSentence(why)} ${then}`
58640
+ });
58641
+ let stored;
58642
+ try {
58643
+ stored = await check();
58644
+ } catch (error) {
58645
+ return unasked(messageFor(error), "The call is refused for the same reason.");
58646
+ }
58647
+ if (stored.kind === "kept" || stored.kind === "reordered")
58648
+ return { kind: "passed" };
58649
+ if (stored.kind === "refused")
58650
+ return { kind: "refused", refusal: stored.refusal };
58651
+ if (stored.kind === "unchecked" && stored.routeAbsent) {
58652
+ return {
58653
+ kind: "passed",
58654
+ warning: `dispatch: warning: this Dispatch cannot check ${subject}: ${endedSentence(stored.failure)} ${uploadsUnchecked}`
58655
+ };
58656
+ }
58657
+ 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.");
58658
+ }
58362
58659
 
58363
58660
  // ../envoy-client/src/dispatch-commands/handoffs.ts
58364
58661
  async function handoffWriteCommand(context) {
@@ -58917,7 +59214,7 @@ async function reviewCommand(context) {
58917
59214
  }
58918
59215
 
58919
59216
  // ../envoy-client/src/session-answers.ts
58920
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3 } from "fs";
59217
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "fs";
58921
59218
  import { join as join8 } from "path";
58922
59219
 
58923
59220
  // ../envoy-client/src/json-line-record.ts
@@ -59058,7 +59355,7 @@ processGlobal2[STATE_KEY] = state;
59058
59355
  var CACHE_FILE = "answers.json";
59059
59356
  function readCacheFile(directory, url) {
59060
59357
  try {
59061
- const value = JSON.parse(readFileSync3(join8(directory, CACHE_FILE), "utf-8"));
59358
+ const value = JSON.parse(readFileSync4(join8(directory, CACHE_FILE), "utf-8"));
59062
59359
  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)) {
59063
59360
  return {
59064
59361
  dispatch_url: value.dispatch_url,
@@ -59533,7 +59830,12 @@ var dispatchCommands = {
59533
59830
  dispatch_review: acting(reviewCommand),
59534
59831
  dispatch_result: acting(resultCommand),
59535
59832
  dispatch_results: acting(resultsCommand),
59536
- dispatch_artifact: acting(artifactCommand),
59833
+ dispatch_artifact: {
59834
+ ...acting(artifactCommand),
59835
+ dryRun: artifactDryRun,
59836
+ documentFields: ["content"],
59837
+ documentPathField: "path"
59838
+ },
59537
59839
  dispatch_handoff_write: acting(handoffWriteCommand),
59538
59840
  dispatch_handoff_read: acting(handoffReadCommand),
59539
59841
  dispatch_steps: acting(stepsCommand),
@@ -59554,7 +59856,7 @@ async function executeDispatchTool(input) {
59554
59856
  if (checked.problems.length > 0)
59555
59857
  throw new ToolInputError(input.tool, checked.problems);
59556
59858
  if (input.dryRun === true && !dryRunAsksDispatch(input.tool, checked.args)) {
59557
- throw new Error(`dispatch ${input.tool}'s dry run asks Dispatch nothing`);
59859
+ throw new Error(`dispatch ${input.tool}'s dry run runs no command`);
59558
59860
  }
59559
59861
  const command = dispatchCommands[input.tool];
59560
59862
  if (command === undefined)
@@ -59580,7 +59882,7 @@ function ensureDirectory(dir) {
59580
59882
  }
59581
59883
  function readIfPresent(path) {
59582
59884
  try {
59583
- return readFileSync4(path, "utf-8");
59885
+ return readFileSync5(path, "utf-8");
59584
59886
  } catch (error) {
59585
59887
  if (hasErrnoCode(error, "ENOENT"))
59586
59888
  return;
@@ -63637,7 +63939,7 @@ var RelayHeader = {
63637
63939
  var RELAY_PROGRESS_INTERVAL_MS = 20000;
63638
63940
  var FOLLOW_CLOCK_ALLOWANCE_MS = 2000;
63639
63941
  var RELAY_ATTEMPTS_BEFORE_FAILED = 3;
63640
- var decoder4 = new TextDecoder;
63942
+ var decoder5 = new TextDecoder;
63641
63943
  var DECIMAL = /^[0-9]+$/;
63642
63944
  var RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
63643
63945
  function positiveInteger(text) {
@@ -63686,7 +63988,7 @@ function decodeRelayFrame(message) {
63686
63988
  storedAt,
63687
63989
  storedAtMs,
63688
63990
  gap: headers.get(RelayHeader.gap) === "true",
63689
- data: typeof message.data === "string" ? message.data : decoder4.decode(message.data),
63991
+ data: typeof message.data === "string" ? message.data : decoder5.decode(message.data),
63690
63992
  reply
63691
63993
  }
63692
63994
  };
@@ -64112,7 +64414,7 @@ function inboundUnavailable(tell, restored) {
64112
64414
  var import_nats2 = __toESM(require_mod4(), 1);
64113
64415
  var import_nats3 = __toESM(require_nats(), 1);
64114
64416
  var import_servers = __toESM(require_servers(), 1);
64115
- import { readFileSync as readFileSync5 } from "fs";
64417
+ import { readFileSync as readFileSync6 } from "fs";
64116
64418
  import { setTimeout as delay } from "timers/promises";
64117
64419
 
64118
64420
  // ../envoy-client/src/nats-auth.ts
@@ -64150,7 +64452,7 @@ var RELEASE_VERSION = /^\d+\.\d+\.\d+$/;
64150
64452
  function clientBuild(stampFile, release) {
64151
64453
  let stamp = "";
64152
64454
  try {
64153
- stamp = readFileSync5(stampFile, "utf8").trim();
64455
+ stamp = readFileSync6(stampFile, "utf8").trim();
64154
64456
  } catch {}
64155
64457
  if (FULL_COMMIT.test(stamp))
64156
64458
  return `legion@${stamp}`;
@@ -65936,7 +66238,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
65936
66238
 
65937
66239
  // package.json
65938
66240
  var name2 = "@sjawhar/claude-envoy";
65939
- var version2 = "6.2.0";
66241
+ var version2 = "6.2.2";
65940
66242
  var package_default = {
65941
66243
  name: name2,
65942
66244
  version: version2,
@@ -65947,7 +66249,7 @@ var package_default = {
65947
66249
  repository: { type: "git", url: "https://github.com/cybermonklabs/legion" },
65948
66250
  scripts: { channel: "bun bin/envoy-channel.ts", "verify-build": "bash scripts/verify-build.sh", prepack: "bash scripts/pack-skills.sh", postpack: "bash scripts/pack-skills.sh --restore", typecheck: "bun ../contracts/scripts/gen-api.ts && bunx tsc --noEmit", test: "bun test --timeout=60000", lint: "bunx biome check src/ hooks/ scripts/" },
65949
66251
  devDependencies: { "@biomejs/biome": "^2.3.14", "@legion/cipher-client": "workspace:*", "@legion/contracts": "workspace:*", "@legion/envoy-client": "workspace:*", "@legion/pi-shared": "workspace:*", "@legion/test-fixtures": "workspace:*", "@modelcontextprotocol/sdk": "^1.30.0", "bun-types": "latest", nats: "^2.29.2", typescript: "^5.3.0", zod: "4.3.6" },
65950
- legion: { daemonApiVersion: 278 }
66252
+ legion: { daemonApiVersion: 279 }
65951
66253
  };
65952
66254
 
65953
66255
  // ../envoy-client/src/inbound-card.ts
@@ -66004,10 +66306,10 @@ function readInboundCard(text) {
66004
66306
 
66005
66307
  // ../pi-shared/src/agent-stream.ts
66006
66308
  var ENVOY_CARD = "envoy-message";
66007
- var encoder4 = new TextEncoder;
66309
+ var encoder5 = new TextEncoder;
66008
66310
  var REPLAY_ARRAY_BYTES = 2;
66009
66311
  function jsonBytes(value) {
66010
- return encoder4.encode(JSON.stringify(value)).length;
66312
+ return encoder5.encode(JSON.stringify(value)).length;
66011
66313
  }
66012
66314
  var SEQ_PER_MS = 1000;
66013
66315
  function modelReference(provider, id) {
@@ -66778,8 +67080,8 @@ function rememberBoundedEntry(remembered, key, value, max) {
66778
67080
  }
66779
67081
 
66780
67082
  // src/control-subscription.ts
66781
- var encoder5 = new TextEncoder;
66782
- var decoder5 = new TextDecoder;
67083
+ var encoder6 = new TextEncoder;
67084
+ var decoder6 = new TextDecoder;
66783
67085
  var RESUBSCRIBE_MS = 1000;
66784
67086
  function controlSubscription(options) {
66785
67087
  let connection = options.connection;
@@ -66789,7 +67091,7 @@ function controlSubscription(options) {
66789
67091
  try {
66790
67092
  for await (const message of taken) {
66791
67093
  try {
66792
- const parsed = JSON.parse(decoder5.decode(message.data));
67094
+ const parsed = JSON.parse(decoder6.decode(message.data));
66793
67095
  if (typeof parsed !== "object" || parsed === null)
66794
67096
  continue;
66795
67097
  const request = parsed;
@@ -66799,7 +67101,7 @@ function controlSubscription(options) {
66799
67101
  const answer = options.answer(request, reply !== undefined, forSession);
66800
67102
  if (answer === undefined || reply === undefined)
66801
67103
  continue;
66802
- connection.publish(reply, encoder5.encode(answer));
67104
+ connection.publish(reply, encoder6.encode(answer));
66803
67105
  } catch (error) {
66804
67106
  options.warn(`a live view control message failed \u2014 ${messageFor(error)}`);
66805
67107
  }
@@ -66842,7 +67144,7 @@ function controlSubscription(options) {
66842
67144
  },
66843
67145
  publish(subject, payload) {
66844
67146
  if (!stopped && !connection.isClosed())
66845
- connection.publish(subject, encoder5.encode(payload));
67147
+ connection.publish(subject, encoder6.encode(payload));
66846
67148
  },
66847
67149
  start() {
66848
67150
  subscribeWhenAdmitted(options.session());
@@ -67101,7 +67403,7 @@ import { readFile as readFile7 } from "fs/promises";
67101
67403
  import { basename as basename3, join as join11 } from "path";
67102
67404
 
67103
67405
  // src/session-state.ts
67104
- import { readFileSync as readFileSync6 } from "fs";
67406
+ import { readFileSync as readFileSync7 } from "fs";
67105
67407
  import { mkdir as mkdir2, readdir as readdir3, rename as rename3, rm as rm4, stat as stat4, utimes as utimes2, writeFile } from "fs/promises";
67106
67408
  import { dirname as dirname4, join as join10 } from "path";
67107
67409
  async function writeAtomicStateFile(file, contents) {
@@ -67147,7 +67449,7 @@ async function removeChosenTitle(file) {
67147
67449
  }
67148
67450
  function readChosenTitleSync(file) {
67149
67451
  try {
67150
- return readFileSync6(file, "utf8");
67452
+ return readFileSync7(file, "utf8");
67151
67453
  } catch {
67152
67454
  return;
67153
67455
  }
@@ -67335,7 +67637,7 @@ import { join as join15 } from "path";
67335
67637
  import { setTimeout as delay2 } from "timers/promises";
67336
67638
 
67337
67639
  // ../contracts/src/daemon-contract.ts
67338
- import { existsSync, readdirSync as readdirSync3, readFileSync as readFileSync7 } from "fs";
67640
+ import { existsSync, readdirSync as readdirSync3, readFileSync as readFileSync8 } from "fs";
67339
67641
  import { dirname as dirname6, join as join13, resolve as resolve3 } from "path";
67340
67642
  var ENTRY_FIXTURE_NAME = /^[0-9]{14}_.+\.json$/;
67341
67643
  var DAEMON_API_FIXTURES = join13("packages", "contracts", "fixtures", "daemon-api");
@@ -67355,7 +67657,7 @@ function daemonContract(manifest, from) {
67355
67657
  throw new Error(`the plugin's package.json holds no legion.daemonApiVersion, which every pack writes, and ${from} is in no checkout: no directory from it up holds ${join13(DAEMON_API_FIXTURES, "released-contracts.json")}`);
67356
67658
  }
67357
67659
  function lastReleased(file) {
67358
- const released = JSON.parse(readFileSync7(file, "utf8"));
67660
+ const released = JSON.parse(readFileSync8(file, "utf8"));
67359
67661
  if (!Array.isArray(released) || released.length === 0 || !released.every((contract, at) => Number.isInteger(contract) && (at === 0 || contract > released[at - 1]))) {
67360
67662
  throw new Error(`${file} is not a list of contract numbers in strictly ascending order`);
67361
67663
  }
@@ -67525,6 +67827,7 @@ var LEGION_FAILURE_CAUSES = [
67525
67827
  "stale_plugin",
67526
67828
  "prompt_retires_exhausted",
67527
67829
  "provider_error",
67830
+ "cyber_policy",
67528
67831
  "unrecorded"
67529
67832
  ];
67530
67833
  var legionFailureCause = _enum2(LEGION_FAILURE_CAUSES);
@@ -68002,7 +68305,8 @@ var turnOutcomeFields = {
68002
68305
  outcome: _enum2(["clean", "refused"]),
68003
68306
  message: string2().optional(),
68004
68307
  httpStatus: number2().int().min(100).max(599).optional(),
68005
- unprompted: boolean2().optional()
68308
+ unprompted: boolean2().optional(),
68309
+ code: literal("cyber_policy").optional()
68006
68310
  };
68007
68311
  var LegionTurnOutcomeAgentRequest = strictObject({
68008
68312
  claimToken: nonEmptyString2,
@@ -68856,7 +69160,7 @@ function listenerAskedToClaimAgain(error) {
68856
69160
 
68857
69161
  // src/legion-phase-hook.ts
68858
69162
  import { randomUUID as randomUUID7 } from "crypto";
68859
- import { readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
69163
+ import { readFileSync as readFileSync9, renameSync as renameSync3, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
68860
69164
  import { dirname as dirname7, join as join14 } from "path";
68861
69165
 
68862
69166
  // ../pi-shared/src/phase-reminder.ts
@@ -69337,7 +69641,7 @@ var NO_RECORD = { entry: undefined, recreatedNoticeSent: false };
69337
69641
  function readPhaseStallRecord(file, log) {
69338
69642
  let raw;
69339
69643
  try {
69340
- raw = readFileSync8(file, "utf8");
69644
+ raw = readFileSync9(file, "utf8");
69341
69645
  } catch (error) {
69342
69646
  const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
69343
69647
  if (!missing) {
@@ -70863,12 +71167,12 @@ import { basename as basename4 } from "path";
70863
71167
 
70864
71168
  // ../envoy-client/src/process-ancestry.ts
70865
71169
  import { execFileSync } from "child_process";
70866
- import { readFileSync as readFileSync9 } from "fs";
71170
+ import { readFileSync as readFileSync10 } from "fs";
70867
71171
  var MAX_ANCESTORS = 64;
70868
71172
  var PARENT_LOOKUP_MS = 1000;
70869
71173
  function procParentPid(pid) {
70870
71174
  try {
70871
- const stat = readFileSync9(`/proc/${pid}/stat`, "utf8");
71175
+ const stat = readFileSync10(`/proc/${pid}/stat`, "utf8");
70872
71176
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
70873
71177
  return Number.isInteger(parent) ? parent : undefined;
70874
71178
  } catch {
@@ -70910,7 +71214,7 @@ function isAncestor(candidate, pid = process.pid) {
70910
71214
  }
70911
71215
  function procCommand(pid) {
70912
71216
  try {
70913
- return readFileSync9(`/proc/${pid}/comm`, "utf8").trim();
71217
+ return readFileSync10(`/proc/${pid}/comm`, "utf8").trim();
70914
71218
  } catch {
70915
71219
  return;
70916
71220
  }
@@ -71433,7 +71737,7 @@ async function pruneStaleSessionTurns(stateDirectory) {
71433
71737
  // src/envoy-channel-server.ts
71434
71738
  var CHANNEL_INSTRUCTIONS = "Envoy delivers trusted, internal session and Dispatch events into this conversation. Use the Envoy tools for Envoy actions, and reach Dispatch through the `dispatch` command in Bash (`dispatch --help` lists its commands; the `dispatch` skill teaches them). Dispatch asks stay on Dispatch.";
71435
71739
  var CHANNEL_INBOX_LIMIT = 50;
71436
- var encoder6 = new TextEncoder;
71740
+ var encoder7 = new TextEncoder;
71437
71741
  var HANDOFF_POLL_MS = 250;
71438
71742
  var HANDOFF_FLUSH_TIMEOUT_MS = 1e4;
71439
71743
  async function withTimeout(promise, ms, what) {
@@ -71828,7 +72132,7 @@ async function startChannelSession(options) {
71828
72132
  `);
71829
72133
  }
71830
72134
  },
71831
- publish: (reply, body) => connection.publish(reply, encoder6.encode(body)),
72135
+ publish: (reply, body) => connection.publish(reply, encoder7.encode(body)),
71832
72136
  persist: (snapshot) => {
71833
72137
  if (relay !== owner)
71834
72138
  return false;
@@ -73159,10 +73463,10 @@ function startCodexAgentStream(options) {
73159
73463
  // src/codex/codex-cli.ts
73160
73464
  import { spawn } from "child_process";
73161
73465
  import { randomBytes as randomBytes2 } from "crypto";
73162
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
73466
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "fs";
73163
73467
  import { join as join18 } from "path";
73164
73468
  var QUEUE_TIMEOUT_MS = 30000;
73165
- function codexProcessEnv(pid, fallback, read = (path) => readFileSync10(path, "utf8")) {
73469
+ function codexProcessEnv(pid, fallback, read = (path) => readFileSync11(path, "utf8")) {
73166
73470
  let raw;
73167
73471
  try {
73168
73472
  raw = read(`/proc/${pid}/environ`);
@@ -73606,7 +73910,7 @@ import { join as join21 } from "path";
73606
73910
 
73607
73911
  // src/codex/codex-session-record.ts
73608
73912
  import { spawnSync } from "child_process";
73609
- import { readFileSync as readFileSync11, readlinkSync as readlinkSync2, unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
73913
+ import { readFileSync as readFileSync12, readlinkSync as readlinkSync2, unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
73610
73914
  import { mkdir as mkdir5, readFile as readFile10, rename as rename5, utimes as utimes3, writeFile as writeFile3 } from "fs/promises";
73611
73915
  import { homedir as homedir3 } from "os";
73612
73916
  import { basename as basename5, dirname as dirname9, join as join20 } from "path";
@@ -73692,14 +73996,14 @@ function codexProcessId(readComm = procComm, readParent = procParent) {
73692
73996
  }
73693
73997
  function procComm(pid) {
73694
73998
  try {
73695
- return readFileSync11(`/proc/${pid}/comm`, "utf8").trim();
73999
+ return readFileSync12(`/proc/${pid}/comm`, "utf8").trim();
73696
74000
  } catch {
73697
74001
  return;
73698
74002
  }
73699
74003
  }
73700
74004
  function procParent(pid) {
73701
74005
  try {
73702
- const stat = readFileSync11(`/proc/${pid}/stat`, "utf8");
74006
+ const stat = readFileSync12(`/proc/${pid}/stat`, "utf8");
73703
74007
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
73704
74008
  return Number.isInteger(parent) ? parent : undefined;
73705
74009
  } catch {
@@ -73713,7 +74017,7 @@ var PS_OPTIONS = {
73713
74017
  };
73714
74018
  function procStarted(pid) {
73715
74019
  try {
73716
- const stat = readFileSync11(`/proc/${pid}/stat`, "utf8");
74020
+ const stat = readFileSync12(`/proc/${pid}/stat`, "utf8");
73717
74021
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
73718
74022
  } catch {
73719
74023
  return;
@@ -73734,7 +74038,7 @@ function recordOfProcess(record, pid) {
73734
74038
  function sharedAppServer(pid) {
73735
74039
  let argv;
73736
74040
  try {
73737
- argv = readFileSync11(`/proc/${pid}/cmdline`, "utf8").split("\x00");
74041
+ argv = readFileSync12(`/proc/${pid}/cmdline`, "utf8").split("\x00");
73738
74042
  } catch {
73739
74043
  const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS);
73740
74044
  if (ps.status !== 0)