@sjawhar/claude-envoy 4.11.1 → 4.11.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.
@@ -37414,7 +37414,7 @@ var dispatchToolSpecs = [
37414
37414
  verdict: "pass",
37415
37415
  commit: "1111111111111111111111111111111111111111"
37416
37416
  },
37417
- description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. A " + "commit that repository does not hold is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and that owner/repo. Record the result after the commit is pushed. A repository " + "Dispatch cannot read records the result as before. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED, as it refuses every other write. " + "A check a document version rewords while the result is being written is 409 " + "CHECK_CONTENDED, with nothing recorded: run the same command again. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + ISSUE_REFERENCE,
37417
+ description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch, no private host and no issue key: Dispatch keeps only words " + "of letters, digits and plain punctuation, and of those leaves out every word that holds " + "`://`, a private or Dispatch host, or an issue key of one of its projects; the record keeps " + "the whole reading. --dry-run prints the line the record would print, and records nothing. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. A " + "commit that repository does not hold is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and that owner/repo. Record the result after the commit is pushed. A repository " + "Dispatch cannot read records the result as before. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED, as it refuses every other write. " + "A check a document version rewords while the result is being written is 409 " + "CHECK_CONTENDED, with nothing recorded: run the same command again. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + ISSUE_REFERENCE,
37418
37418
  arguments: (z) => ({
37419
37419
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
37420
37420
  check: z.string().describe("The check block's id, or its canonical reference dispatch://KEY/artifact/verification-md#b-<id> when the id is not unique among the issue's Verification document and those of the issues above it.").optional(),
@@ -43484,6 +43484,9 @@ function reviewNoRouteRefusal(baseUrl, route, version) {
43484
43484
  const health = isCleanUrl(baseUrl) ? `${baseUrl}/healthz` : "/healthz on that server";
43485
43485
  return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${shown} answered no route for ${route} each time the review was sent, and an ` + "answer of no route records no review. This build is older than that route. No other review " + "route was asked: the review route an older build serves takes no version, and it " + `would record the review at a version that build chooses, which may not be version ${version}. ` + `The no-route answer does not name the build; GET ${health} names the commit of the ` + "build that answers it, when that build was stamped with one.");
43486
43486
  }
43487
+ function resultDryRunNoRouteRefusal(baseUrl, route) {
43488
+ return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${urlForText(baseUrl, DISPATCH_URL_SETTING)} answered no route for ${route} each ` + "time the dry run was sent: this build is older than a result's dry run, so it cannot show " + "the pull-request body line before the record. Nothing was recorded.");
43489
+ }
43487
43490
  var ISSUE_EVENTS_PAGE_MAX = 200;
43488
43491
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
43489
43492
  function requestSignal(signal, deadlineMs) {
@@ -43991,6 +43994,20 @@ class DispatchClient {
43991
43994
  async recordResult(issue, input) {
43992
43995
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
43993
43996
  }
43997
+ async dryRunResult(issue, input) {
43998
+ const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "results", "dry-run"];
43999
+ try {
44000
+ const { payload } = await this.#jsonAnswer("POST", path, input, {
44001
+ writes: false
44002
+ });
44003
+ return payload;
44004
+ } catch (error) {
44005
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
44006
+ throw error;
44007
+ const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
44008
+ throw resultDryRunNoRouteRefusal(this.#baseUrl, route);
44009
+ }
44010
+ }
43994
44011
  async issueResults(issue, at) {
43995
44012
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], undefined, at === undefined ? undefined : { at });
43996
44013
  }
@@ -45223,7 +45240,7 @@ function flagTable(tool, fields) {
45223
45240
  add("--help", { action: "help", text: "Prints this help." });
45224
45241
  add("--dry-run", {
45225
45242
  action: "dry-run",
45226
- text: "Checks the arguments as the call would, then prints them as JSON and sends nothing."
45243
+ 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."
45227
45244
  });
45228
45245
  return flags;
45229
45246
  }
@@ -45497,7 +45514,7 @@ function commandsHelp() {
45497
45514
  return ` ${commandName(spec.name).padEnd(width)} ${sentence}`;
45498
45515
  }),
45499
45516
  "",
45500
- "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.",
45517
+ "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.",
45501
45518
  ""
45502
45519
  ].join(`
45503
45520
  `);
@@ -48873,372 +48890,265 @@ async function otherAdviceLines(render) {
48873
48890
  }
48874
48891
  }
48875
48892
 
48876
- // ../envoy-client/src/dispatch-commands/render-graph.ts
48877
- function referenceLines(read) {
48878
- if (typeof read === "string")
48879
- return [`- ${read}`];
48880
- const edges = read.edges ?? [];
48881
- if (edges.length === 0)
48882
- return ["- none"];
48883
- return edges.map(edgeLine);
48884
- }
48885
- function isItemKind(kind) {
48886
- return ITEM_KINDS.some((item) => item === kind);
48887
- }
48888
- function edgeLine(edge) {
48889
- const { node } = edge;
48890
- const excerpt = edge.excerpt === undefined ? "" : `${textHead(edge.excerpt.text)} \xB7 `;
48891
- const block = edge.block === undefined ? "" : ` (block ${edge.block.ref ?? edge.block.id})`;
48892
- const parent = node.parent ?? undefined;
48893
- const item = node.kind === "block" && node.document === undefined && isItemKind(parent?.kind) ? parent : undefined;
48894
- const source = item === undefined ? `${node.kind} ${node.ref ?? node.id}` : `${item.kind} ${item.ref ?? item.id} block ${node.block_id ?? node.id}`;
48895
- return `- ${edge.kind} ${source} (${excerpt}${edge.created_at})${block}`;
48896
- }
48897
- function unavailableReason(error) {
48898
- return dispatchAnswered(error, 404) ? "unavailable" : `unavailable: ${messageFor(error)}`;
48899
- }
48900
- async function graphReferences(client, query) {
48901
- try {
48902
- return await client.getReferences(query);
48903
- } catch (error) {
48904
- return unavailableReason(error);
48893
+ // ../envoy-client/src/dispatch-commands/render-issue.ts
48894
+ function componentsLine(components) {
48895
+ const ids = components.ids ?? [];
48896
+ const unknown = components.unknown ?? [];
48897
+ const inherited = components.inherited_from === null ? "" : ` (inherited from ${components.inherited_from})`;
48898
+ const retired = unknown.length === 0 ? "" : ` (retired: ${unknown.join(", ")})`;
48899
+ switch (components.mode) {
48900
+ case "explicit":
48901
+ return `Components: ${ids.length === 0 ? "none live" : ids.join(", ")}${inherited}${retired}`;
48902
+ case "none":
48903
+ return `Components: none \u2014 ${components.reason ?? ""}${inherited}`;
48904
+ case "inherit":
48905
+ return "Components: unassigned";
48906
+ default:
48907
+ return `Components: ${components.mode}${inherited}${retired}`;
48905
48908
  }
48906
48909
  }
48907
- async function issueReferencesOrUnavailable(client, key) {
48908
- try {
48909
- return await client.getIssueReferences(key);
48910
- } catch (error) {
48911
- return unavailableReason(error);
48912
- }
48910
+ function advanceText(advance) {
48911
+ return `${advance.id} (${advance.inherited ? "inherited" : "own"})`;
48913
48912
  }
48914
- async function issueCoverageOrReason(client, key) {
48915
- try {
48916
- return await client.issueCoverage(key);
48917
- } catch (error) {
48918
- return unavailableReason(error);
48913
+ function advancesLine(issue) {
48914
+ if (issue.advances === undefined) {
48915
+ return "Advances: unknown (this Dispatch server predates priorities; upgrade it)";
48919
48916
  }
48917
+ const advances = issue.advances ?? [];
48918
+ if (advances.length === 0)
48919
+ return "Advances: no priority";
48920
+ return `Advances: ${advances.map(advanceText).join(", ")}`;
48920
48921
  }
48921
- async function graphSections(client, ref) {
48922
- const [incoming, outgoing] = await Promise.all([
48923
- graphReferences(client, { to: ref }),
48924
- graphReferences(client, { from: ref })
48925
- ]);
48926
- return graphSectionLines(incoming, outgoing);
48927
- }
48928
- function graphSectionLines(incoming, outgoing) {
48929
- return [
48930
- ...typeof incoming === "string" ? [] : nodeLine(incoming.node),
48931
- "Referenced by:",
48932
- ...referenceLines(incoming),
48933
- "Links:",
48934
- ...referenceLines(outgoing)
48935
- ];
48936
- }
48937
- function nodeLine(node) {
48938
- if (node.made_by === undefined)
48939
- return [];
48940
- const fact = (by, time) => `${by == null || by.length === 0 ? "nobody recorded" : by.map(actorText).join(", ")}${time == null ? "" : ` at ${time}`}`;
48941
- const made = fact(node.made_by, node.made_at);
48942
- const changed = fact(node.changed_by, node.changed_at);
48943
- const { parent } = node;
48944
- const partOf = parent == null ? "" : ` \xB7 part of ${parent.ref ?? `${parent.kind} ${parent.id}`}${node.parent_version == null ? "" : ` (${isItemKind(parent.kind) ? "revision" : "version"} ${node.parent_version})`}`;
48945
- return [
48946
- `Node: ${node.kind} ${node.ref ?? node.id} \xB7 made by ${made} \xB7 changed by ${changed}${partOf}`
48947
- ];
48922
+ function claimText(claim, agents, read = {}) {
48923
+ const titles = agents?.titles;
48924
+ const liveness = holderLiveness(claim, agents, read);
48925
+ const holding = claimHolds(claim, titles, liveness);
48926
+ const takeableAt = claimTakeableAt(liveness);
48927
+ const unresponsive = liveness.holder_state === "unresponsive" && liveness.last_seen != null ? ` \xB7 unresponsive since ${liveness.last_seen}${takeableAt === null ? "" : `, takeable at ${takeableAt}`}` : " \xB7 unresponsive";
48928
+ const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : holding === "unresponsive" ? unresponsive : "";
48929
+ return `${actorLabel(claim.actor, titles)} since ${claim.at}${marker}`;
48948
48930
  }
48949
- function blockLines(node, ref, typed, noun = "Block") {
48950
- const unit = ref.item === undefined ? "version" : "revision";
48951
- const blockID = node.block_id ?? ref.block;
48952
- const head = ref.item === undefined ? [
48953
- `Block: ${blockID}`,
48954
- ...typed === undefined ? [] : [`Type: ${typed.type}`],
48955
- `Document: ${node.document ?? ref.document}`,
48956
- ...(typed?.attributes ?? []).map((attribute) => `${attribute.name}: ${attribute.value === "" ? "(empty)" : attribute.value}`),
48957
- ...node.changed_version === undefined ? [] : [`Changed in version: ${node.changed_version}`],
48958
- ...node.text === undefined ? [] : ["Text:", node.text]
48959
- ] : [
48960
- `${noun} ${blockID} of ${ref.item.kind} ${ref.item.id}${node.changed_version === undefined ? "" : ` (changed in revision ${node.changed_version})`}:`,
48961
- ...node.text === undefined ? [] : [node.text]
48962
- ];
48963
- const { pin } = node;
48964
- if (pin === undefined)
48965
- return head;
48966
- const state = pin.state === "unchanged" ? `Unchanged since ${unit} ${pin.version}.` : pin.state === "changed" ? `Changed since ${unit} ${pin.version}; last changed in ${unit} ${node.changed_version}.` : `Removed in ${unit} ${pin.removed_version}.`;
48967
- return [
48968
- ...head,
48969
- `Pinned to ${unit}: ${pin.version}`,
48970
- state,
48971
- `Text at ${unit} ${pin.version}:`,
48972
- pin.text
48973
- ];
48931
+ function holderLiveness(claim, agents, read) {
48932
+ if (claim.actor.kind !== "session")
48933
+ return read;
48934
+ const row = agents?.liveness.get(claim.actor.id);
48935
+ if (row === undefined)
48936
+ return read;
48937
+ const holderState = read.holder_state ?? row.holder_state;
48938
+ const lastSeen = read.last_seen ?? row.last_seen;
48939
+ const takeableAt = read.takeable_at ?? row.takeable_at;
48940
+ return {
48941
+ ...holderState === undefined ? {} : { holder_state: holderState },
48942
+ ...lastSeen === undefined ? {} : { last_seen: lastSeen },
48943
+ ...takeableAt === undefined ? {} : { takeable_at: takeableAt }
48944
+ };
48974
48945
  }
48975
- async function typedBlockOf(client, ref) {
48976
- if (ref.item !== undefined || ref.block === undefined)
48946
+ async function liveAgents(client, needed) {
48947
+ if (!needed) {
48977
48948
  return;
48949
+ }
48978
48950
  try {
48979
- const blocks = ref.owner.kind === "project" ? await client.projectArtifactBlocks(ref.owner.project, ref.id) : await client.issueArtifactBlocks(ref.owner.issue, ref.id);
48980
- return blocks.find((block) => block.id === ref.block);
48951
+ const agents = await client.listAgents();
48952
+ return {
48953
+ titles: new Map(agents.map((agent) => [agent.session_id, agent.title])),
48954
+ liveness: new Map(agents.map((agent) => [agent.session_id, agentLiveness(agent)]))
48955
+ };
48981
48956
  } catch {
48982
48957
  return;
48983
48958
  }
48984
48959
  }
48985
- function askPartNoun(ask, node, blockID) {
48986
- if (ask.answer?.id === blockID)
48987
- return "Answer";
48988
- if ((ask.options ?? []).some((option) => option.id === blockID))
48989
- return "Option";
48990
- const placed = (ask.revision ?? 0) > 0 && (ask.options ?? []).every((option) => option.id !== undefined) && (ask.answer === null || ask.answer.id !== undefined);
48991
- return placed && node.pin?.state !== "removed" ? "Question" : "Part";
48960
+ function agentLiveness(agent) {
48961
+ return {
48962
+ ...agent.state === undefined ? {} : { holder_state: agent.state },
48963
+ ...agent.last_seen > 0 ? { last_seen: new Date(agent.last_seen).toISOString() } : {}
48964
+ };
48992
48965
  }
48993
-
48994
- // ../envoy-client/src/dispatch-commands/render-item.ts
48995
- function askSummary({ ask, replies, answers }, askRef, pictures, incoming, outgoing) {
48996
- const answer = ask.answer;
48997
- const earlierAnswers = (answers ?? []).slice(0, -1);
48998
- const parts = askPartEdges(ask, incoming);
48999
- const partRef = (id) => `${askRef}#b-${encodeBlockId(id)}`;
49000
- const chain = (replies ?? []).flatMap((reply) => [
49001
- `${reply.id} \xB7 ${actorText(reply.author)}`,
49002
- `Body: ${reply.body}`
49003
- ]);
49004
- const resolutionWords = dispatchWordsText(ask.resolution?.dispatch_words);
49005
- return [
49006
- `Question: ${ask.question}`,
49007
- ...anchorLines(ask),
49008
- "Options:",
49009
- ...(ask.options ?? []).length === 0 ? ["- none"] : (ask.options ?? []).flatMap((option) => [
49010
- `- ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}${option.id === undefined ? "" : ` (${partRef(option.id)})`}`,
49011
- ...partReferenceLines(parts.at, option.id)
49012
- ]),
49013
- `State: ${ask.state}`,
49014
- `Ask id: ${ask.id}`,
49015
- "Answer:",
49016
- ...answer === null ? ["- none"] : [
49017
- `- By: ${actorActText(answer.user, answer.act)}`,
49018
- `- Selected: ${(answer.selected ?? []).length === 0 ? "none" : (answer.selected ?? []).join(", ")}`,
49019
- ...answer.text === null ? [] : [`- Text: ${answer.text}`],
49020
- ...answer.id === undefined ? [] : [`- Reference: ${partRef(answer.id)}`],
49021
- ...partReferenceLines(parts.at, answer.id)
49022
- ],
49023
- ...earlierAnswers.length === 0 ? [] : [
49024
- "Earlier answers:",
49025
- ...earlierAnswers.map((earlier) => `- ${earlier.at} \xB7 ${actorActText(earlier.user, earlier.act)} \xB7 ${askAnswerText(earlier)}`)
49026
- ],
49027
- ...ask.resolution === undefined ? [] : [
49028
- "Resolution:",
49029
- `- By: ${ask.resolution.actor.id}`,
49030
- `- Kind: ${ask.resolution.kind}`,
49031
- ...ask.resolution.reason === "" ? [] : [`- Reason: ${ask.resolution.reason}`],
49032
- ...resolutionWords === undefined ? [] : [`- ${resolutionWords}`]
49033
- ],
49034
- "Replies:",
49035
- ...chain.length === 0 ? ["- none"] : chain,
49036
- ...pictures,
49037
- ...graphSectionLines(parts.rest, outgoing)
49038
- ].join(`
49039
- `);
48966
+ function holdsSession(claim) {
48967
+ return claim?.actor.kind === "session";
49040
48968
  }
49041
- function askPartEdges(ask, incoming) {
49042
- const ids = new Set([...(ask.options ?? []).map((option) => option.id), ask.answer?.id].filter((id) => id !== undefined));
49043
- const at = new Map;
49044
- if (typeof incoming === "string" || ids.size === 0)
49045
- return { at, rest: incoming };
49046
- const rest = [];
49047
- for (const edge of incoming.edges ?? []) {
49048
- const part = edge.block?.block_id;
49049
- if (part === undefined || !ids.has(part)) {
49050
- rest.push(edge);
49051
- continue;
49052
- }
49053
- const { block: _block, ...atPart } = edge;
49054
- const held = at.get(part);
49055
- if (held === undefined)
49056
- at.set(part, [atPart]);
49057
- else
49058
- held.push(atPart);
49059
- }
49060
- return { at, rest: { node: incoming.node, edges: rest } };
48969
+ function isRouteStatus(value) {
48970
+ return ISSUE_ROUTE_STATUSES.some((status) => status === value);
49061
48971
  }
49062
- function partReferenceLines(at, id) {
49063
- const edges = id === undefined ? undefined : at.get(id);
49064
- if (edges === undefined || edges.length === 0)
49065
- return [];
49066
- return [" Referenced by:", ...edges.map((edge) => ` ${edgeLine(edge)}`)];
48972
+ function routeHeldBySession(issue) {
48973
+ return issue.route_status === "live" && issue.route?.startsWith("role:") === true;
49067
48974
  }
49068
- function openAskAge(ageSeconds) {
49069
- const seconds = Math.max(0, Math.floor(ageSeconds));
49070
- if (seconds < 60)
49071
- return `${seconds}s`;
49072
- const minutes = Math.floor(seconds / 60);
49073
- if (minutes < 60)
49074
- return `${minutes}m${seconds % 60 === 0 ? "" : ` ${seconds % 60}s`}`;
49075
- const hours = Math.floor(minutes / 60);
49076
- if (hours < 24)
49077
- return `${hours}h${minutes % 60 === 0 ? "" : ` ${minutes % 60}m`}`;
49078
- const days = Math.floor(hours / 24);
49079
- return `${days}d${hours % 24 === 0 ? "" : ` ${hours % 24}h`}`;
48975
+ function routeText(issue, titles) {
48976
+ if (issue.route === null)
48977
+ return "none";
48978
+ const holder = issue.route_holder ?? null;
48979
+ const reach = {
48980
+ live: routeHeldBySession(issue) && holder !== null ? ` (held by ${titles?.get(holder) ?? holder})` : "",
48981
+ holder_unresponsive: issue.route.startsWith("role:") ? ` (its holder${holder === null ? "" : ` ${titles?.get(holder) ?? holder}`} is unresponsive: messages wait for it)` : " (that session is unresponsive: messages wait for it)",
48982
+ no_holder: issue.route.startsWith("role:") ? " (nobody holds it right now)" : " (that session is not running right now)",
48983
+ unknown: issue.route_status_reason === "refilling" ? " (the Envoy listener's agent list is refilling, so whether it reaches anyone is unknown; try again in a moment)" : " (the Envoy listener did not answer, so whether it reaches anyone is unknown)"
48984
+ };
48985
+ const status = issue.route_status;
48986
+ return issue.route + (status != null && isRouteStatus(status) ? reach[status] : "");
49080
48987
  }
49081
- function namedPerson(person) {
49082
- return person === undefined || person === "" ? undefined : person;
48988
+ function progressText(progress, sep) {
48989
+ if (progress === undefined)
48990
+ return "";
48991
+ const parts = [];
48992
+ if (progress.tasks !== null)
48993
+ parts.push(`tasks ${progress.tasks.done}/${progress.tasks.total}`);
48994
+ if (progress.children !== null) {
48995
+ parts.push(`children ${progress.children.done}/${progress.children.total}`);
48996
+ }
48997
+ return parts.join(sep);
49083
48998
  }
49084
- function waitsOnPerson(ask) {
49085
- return namedPerson(ask.waiting_on_person);
48999
+ function repositoryLine(issue) {
49000
+ if (issue.resolved_repo === undefined) {
49001
+ return "Repository: unknown (this Dispatch server predates repository fields; upgrade it)";
49002
+ }
49003
+ if (issue.resolved_repo === null)
49004
+ return "Repository: none";
49005
+ if (issue.repo !== null && issue.repo !== undefined)
49006
+ return `Repository: ${issue.repo} (own)`;
49007
+ return `Repository: ${issue.resolved_repo} (inherited or project default)`;
49086
49008
  }
49087
- function openAskLine(ask, linkBase) {
49088
- const priority = ask.priority === null ? "" : `P${ask.priority} \xB7 `;
49089
- return `- ${openAskAge(ask.age_seconds)} \xB7 ${priority}${ownerTitle(ask.owner)} \xB7 asked of ${waitsOnPerson(ask) ?? "nobody"} \xB7 ${ask.question} \xB7 ${linkFor(ask.ref, linkBase)}`;
49009
+ function olderServerWarnings(issue) {
49010
+ const warnings = [
49011
+ ...issue.resolved_repo !== undefined ? [] : [
49012
+ `dispatch: warning: Dispatch issue is missing resolved_repo: this Dispatch server predates repository fields, so ${issue.key}'s repository is unknown; upgrade the server`
49013
+ ],
49014
+ ...issue.advances !== undefined ? [] : [
49015
+ `dispatch: warning: Dispatch issue is missing advances: this Dispatch server predates priorities, so the priorities ${issue.key} advances are unknown; upgrade the server`
49016
+ ]
49017
+ ];
49018
+ return warnings.length === 0 ? {} : { warnings };
49090
49019
  }
49091
- function formatOpenAsksSummary(response, linkBase) {
49092
- const scope = "active open asks you authored on open issues and project documents";
49093
- if (response.count === 0) {
49094
- return ["There are no unanswered asks for this session.", `Scope: ${scope}.`].join(`
49095
- `);
49020
+ function issueSummary(issue, events, references, graph, linkBase, coverage, agents) {
49021
+ const asks = issue.open_asks ?? [];
49022
+ const labels = issue.labels ?? [];
49023
+ const links = issue.external_links ?? [];
49024
+ const members = typeof references === "string" ? [] : references.members ?? [];
49025
+ const spec = issue.artifacts?.find((artifact) => artifact.primary);
49026
+ const specApproval = spec === undefined ? undefined : approvalLine(spec, typeof issue.closed_at === "string");
49027
+ if (issue.priority === undefined)
49028
+ throw new Error("Dispatch issue is missing priority");
49029
+ if (issue.assignee === undefined)
49030
+ throw new Error("Dispatch issue is missing assignee");
49031
+ if (issue.components === undefined)
49032
+ throw new Error("Dispatch issue is missing components");
49033
+ if (issue.claim === undefined)
49034
+ throw new Error("Dispatch issue is missing claim");
49035
+ if (issue.external_links === undefined) {
49036
+ throw new Error("Dispatch issue is missing external_links");
49096
49037
  }
49097
- const waitingOnHuman = (response.asks ?? []).filter((ask) => ask.waiting_on === "human");
49098
- const waitingOnAgent = (response.asks ?? []).filter((ask) => ask.waiting_on === "agent");
49099
49038
  return [
49100
- `${response.count} unanswered ${response.count === 1 ? "ask" : "asks"} you authored on active issues and project documents.`,
49101
- "",
49102
- `Waiting on human (${waitingOnHuman.length}):`,
49103
- ...waitingOnHuman.map((ask) => openAskLine(ask, linkBase)),
49104
- "",
49105
- `Waiting on agent (${waitingOnAgent.length}):`,
49106
- ...waitingOnAgent.map((ask) => openAskLine(ask, linkBase))
49039
+ `Title: ${issue.title}`,
49040
+ `Key: ${issue.key}`,
49041
+ `Link: ${linkFor(`/issues/${encodeURIComponent(issue.key)}`, linkBase)}`,
49042
+ `Status: ${issue.status}`,
49043
+ `Assignee: ${issue.assignee ?? "unassigned"}`,
49044
+ `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, agents, issue)}`,
49045
+ ...issue.priority === null ? [] : [`Priority: P${issue.priority}`],
49046
+ `Labels: ${labels.length === 0 ? "none" : labels.join(", ")}`,
49047
+ componentsLine(issue.components),
49048
+ advancesLine(issue),
49049
+ `Route: ${routeText(issue, agents?.titles)}`,
49050
+ repositoryLine(issue),
49051
+ `Progress: ${progressText(issue.progress, ", ") || "none"}`,
49052
+ ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
49053
+ ...typeof coverage === "string" ? [`Coverage: ${coverage}`] : (coverage.gaps ?? []).map((gap) => `Coverage: ${gap}`),
49054
+ "External links:",
49055
+ ...links.length === 0 ? ["- none"] : links.map((link) => `- ${link.url}${link.kind === undefined ? "" : ` (${link.kind})`}`),
49056
+ "Documents:",
49057
+ ...documentListLines(issue.artifacts ?? []),
49058
+ "Open asks:",
49059
+ ...asks.length === 0 ? ["- none"] : asks.map((ask) => `- ${ask.id}: ${ask.question}`),
49060
+ "References:",
49061
+ ...typeof references === "string" ? [`- ${references}`] : members.length === 0 ? ["- none"] : members.map(({ artifact, depth, via }) => `- ${artifact.project}/${artifact.slug} \xB7 depth ${depth} via ${via.kind} ${via.id}`),
49062
+ ...typeof references === "string" || !references.truncated ? [] : ["- more references beyond 8 hops"],
49063
+ "Events:",
49064
+ ...events.length === 0 ? ["- none"] : events.map(eventLine),
49065
+ ...graph
49107
49066
  ].join(`
49108
49067
  `);
49109
49068
  }
49110
- function commentSummary({ comment, replies }, graph) {
49111
- const root = [
49112
- `${comment.id} \xB7 ${actorText(comment.author)}`,
49113
- ...anchorLines(comment),
49114
- ...replyBlockLines(comment),
49115
- `Body: ${comment.body}`
49116
- ];
49117
- const chain = (replies ?? []).flatMap((reply) => [
49118
- `${reply.id} \xB7 ${actorText(reply.author)}`,
49119
- ...anchorLines(reply),
49120
- ...replyBlockLines(reply),
49121
- ...reply.answers != null && reply.answers !== comment.id ? [`Answers: ${reply.answers}`] : [],
49122
- `Body: ${reply.body}`
49123
- ]);
49069
+ function logSummary(issue, events) {
49124
49070
  return [
49125
- "Comment:",
49126
- ...root,
49127
- "Reply chain:",
49128
- ...chain.length === 0 ? ["- none"] : chain,
49129
- ...graph
49071
+ `Key: ${issue.key}`,
49072
+ "Events:",
49073
+ ...events.length === 0 ? ["- none"] : events.map(eventLine)
49130
49074
  ].join(`
49131
49075
  `);
49132
49076
  }
49133
- function replyBlockLines(record) {
49134
- const block = record.reply_block;
49135
- if (block === undefined || block === null)
49136
- return [];
49137
- return [
49138
- block.removed ? `Re: block ${block.block_id} (removed)` : `Re: block ${block.block_id}: ${textHead(block.text)}`
49139
- ];
49077
+ function eventHead(event) {
49078
+ switch (event.type) {
49079
+ case "ask.opened":
49080
+ case "ask.anchor_refreshed":
49081
+ case "ask.edited":
49082
+ case "ask.handed_back":
49083
+ case "ask.resolved":
49084
+ return textHead(event.payload.question);
49085
+ case "ask.answered": {
49086
+ const previousAnswer = event.payload.previous_answer;
49087
+ return `${textHead(event.payload.question)} -> ${textHead(askAnswerText(event.payload.answer))}${previousAnswer === undefined ? "" : ` (was: ${textHead(askAnswerText(previousAnswer))})`}`;
49088
+ }
49089
+ case "ask.asked_of":
49090
+ return `${textHead(event.payload.question)} -> asked of ${event.payload.asked_of ?? "the assignee of its issue"}`;
49091
+ case "comment.created":
49092
+ case "comment.answered":
49093
+ case "comment.anchor_refreshed":
49094
+ case "comment.edited":
49095
+ case "comment.resolved":
49096
+ case "comment.reopened":
49097
+ case "suggestion.accepted":
49098
+ case "suggestion.rejected":
49099
+ case "message.created":
49100
+ case "message.answered":
49101
+ return textHead(event.payload.body);
49102
+ case "artifact.version":
49103
+ return textHead(`${event.payload.name} v${event.payload.version.number}${event.payload.version.summary ? `: ${event.payload.version.summary}` : ""}`);
49104
+ case "artifact.approved":
49105
+ case "artifact.changes_requested": {
49106
+ const { name, version, kind, reason } = event.payload;
49107
+ const verb = event.type === "artifact.approved" ? "approved" : "changes requested";
49108
+ const reviewer = kind === "plan_review" ? " by plan review" : kind === "person" ? " by a person" : "";
49109
+ return textHead(`${name} v${version} ${verb}${reviewer}${reason ? `: ${reason}` : ""}`);
49110
+ }
49111
+ case "artifact.human_edited":
49112
+ return textHead(humanEditHead(event.payload));
49113
+ case "issue.created": {
49114
+ const forced = event.payload.forced;
49115
+ const head = `status ${event.payload.status}`;
49116
+ if (forced === undefined)
49117
+ return head;
49118
+ return forced.past.length === 0 ? `${head} \xB7 forced, the near-copy check did not answer` : `${head} \xB7 forced past ${forced.past.join(", ")}`;
49119
+ }
49120
+ case "issue.updated":
49121
+ case "issue.closed":
49122
+ return `status ${event.payload.status}`;
49123
+ default:
49124
+ return;
49125
+ }
49140
49126
  }
49141
- function anchorLines(record) {
49142
- return [
49143
- ...record.anchor?.quote === undefined ? [] : [`> ${record.anchor.quote}`],
49144
- ...record.anchor_block === undefined ? [] : [`Position: ${positionText(record.anchor_block)}`],
49145
- ...record.anchor_block_error === undefined ? [] : [`Position: unavailable (${record.anchor_block_error})`]
49146
- ];
49127
+ function eventRef(event) {
49128
+ const payload = event.payload;
49129
+ const id = typeof payload === "object" && payload !== null && "id" in payload ? payload.id : undefined;
49130
+ if (typeof id !== "string" || id === "" || event.issue_key === null)
49131
+ return;
49132
+ const kind = event.type.startsWith("message.") ? "message" : event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("ask.") ? "ask" : undefined;
49133
+ return kind === undefined ? undefined : `dispatch://${event.issue_key}/${kind}/${id}`;
49147
49134
  }
49148
- function positionText(block) {
49149
- const { table, path } = block;
49150
- const segments = (path ?? []).map((entry) => `${entry.type}[${entry.index}]`);
49151
- if (table === undefined || table.row === null)
49152
- return segments.join(" \u203A ");
49153
- const tableAt = (path ?? []).findIndex((entry) => entry.type === "table");
49154
- const cells = table.cells ?? [];
49155
- const label = (table.column === null ? cells : cells.slice(0, table.column)).map((cell) => cell.trim()).filter((cell) => cell !== "" && !/^\d+$/.test(cell)).join(" \xB7 ");
49156
- const row = label === "" ? `row ${table.row}` : `row ${table.row} (${label})`;
49157
- const header = table.header === null || table.header === "" ? String(table.column) : table.header;
49158
- return [
49159
- ...segments.slice(0, tableAt + 1),
49160
- table.column === null ? row : `${row}, column ${header}`
49161
- ].join(" \u203A ");
49135
+ function eventActorText(actor) {
49136
+ const title = actor.kind === "session" ? actor.origin?.session_title : undefined;
49137
+ return title === undefined || title === "" ? actorText(actor) : `${actorText(actor)} (${title})`;
49162
49138
  }
49163
- function messageSummary({ message, replies }, graph) {
49164
- const root = [
49165
- `${message.id} \xB7 ${actorText(message.author)}`,
49166
- ...replyBlockLines(message),
49167
- `Body: ${message.body}`
49168
- ];
49169
- const chain = (replies ?? []).flatMap((reply) => [
49170
- `${reply.id} \xB7 ${actorText(reply.author)}`,
49171
- ...replyBlockLines(reply),
49172
- `Body: ${reply.body}`
49173
- ]);
49139
+ function eventLine(event) {
49140
+ const head = eventHead(event);
49141
+ const ref = eventRef(event);
49142
+ return `- #${event.seq} ${event.type}${ref === undefined ? "" : ` ${ref}`} \xB7 ${eventActorText(event.actor)} \xB7 ${event.created_at}${head === undefined || head === "" ? "" : ` \xB7 ${head}`}`;
49143
+ }
49144
+ function childrenSummary(issue) {
49174
49145
  return [
49175
- "Message:",
49176
- ...root,
49177
- "Reply chain:",
49178
- ...chain.length === 0 ? ["- none"] : chain,
49179
- ...graph
49146
+ `Key: ${issue.key}`,
49147
+ "Children:",
49148
+ ...(issue.children ?? []).length === 0 ? ["- none"] : (issue.children ?? []).map((child) => `- ${child.key}: ${child.title} (${child.status})`)
49180
49149
  ].join(`
49181
49150
  `);
49182
49151
  }
49183
- async function openAnchoredThreads(client, resolved) {
49184
- const asksPromise = resolved.owner.kind === "project" ? client.getArtifactAsks(resolved.artifact.id) : Promise.resolve(resolved.issue?.open_asks ?? []);
49185
- const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "");
49186
- const commentsResultPromise = commentsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
49187
- const asks = (await asksPromise).filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id);
49188
- const commentsResult = await commentsResultPromise;
49189
- if (commentsResult.status === "rejected" && !dispatchAnswered(commentsResult.reason, 404)) {
49190
- throw commentsResult.reason;
49191
- }
49192
- const comments = commentsResult.status === "fulfilled" ? commentsResult.value : [];
49193
- const askReplies = new Map(asks.map((ask) => [ask.id, []]));
49194
- for (const comment of comments) {
49195
- if (comment.ask_id)
49196
- askReplies.get(comment.ask_id)?.push(comment);
49197
- }
49198
- const askThreads = asks.map((ask) => [
49199
- `ask ${ask.id} \xB7 ${actorText(ask.author)} \xB7 ${ask.created_at}`,
49200
- ...anchorLines(ask),
49201
- `Question: ${ask.question}`,
49202
- ...threadReplyLines(askReplies.get(ask.id) ?? [])
49203
- ].join(`
49204
- `));
49205
- const byId = new Map(comments.map((comment) => [comment.id, comment]));
49206
- const roots = comments.filter((comment) => comment.reply_to === null && !comment.ask_id && !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id);
49207
- const replies = new Map(roots.map((root) => [root.id, []]));
49208
- for (const comment of comments) {
49209
- const root = comment.reply_to === null ? undefined : threadRootId(comment, byId);
49210
- if (root !== undefined)
49211
- replies.get(root)?.push(comment);
49212
- }
49213
- const commentThreads = roots.map((root) => [
49214
- `comment ${root.id} \xB7 ${actorText(root.author)} \xB7 ${root.created_at}`,
49215
- ...anchorLines(root),
49216
- `Body: ${root.body}`,
49217
- ...threadReplyLines(replies.get(root.id) ?? [])
49218
- ].join(`
49219
- `));
49220
- return [...askThreads, ...commentThreads];
49221
- }
49222
- function threadReplyLines(replies) {
49223
- return replies.flatMap((reply) => [
49224
- `reply ${reply.id} \xB7 ${actorText(reply.author)} \xB7 ${reply.created_at}`,
49225
- `Body: ${reply.body}`
49226
- ]);
49227
- }
49228
- function threadRootId(comment, byId) {
49229
- const seen = new Set;
49230
- let current = comment;
49231
- while (current.reply_to !== null) {
49232
- if (seen.has(current.id))
49233
- return;
49234
- seen.add(current.id);
49235
- const parent = byId.get(current.reply_to);
49236
- if (parent === undefined)
49237
- return;
49238
- current = parent;
49239
- }
49240
- return current.id;
49241
- }
49242
49152
 
49243
49153
  // ../envoy-client/src/dispatch-subscribe.ts
49244
49154
  function followedAsk(details) {
@@ -49367,1893 +49277,2014 @@ async function followedAskDetails(client, ask, artifact) {
49367
49277
  return { ...await askOwnerDetails(client, ask, artifact), follows: { ask: ask.id } };
49368
49278
  }
49369
49279
 
49370
- // ../envoy-client/src/dispatch-commands/asks.ts
49371
- function askUrgency(args) {
49372
- const value = args.urgency;
49373
- return ASK_URGENCIES.find((urgency) => urgency === value);
49374
- }
49375
- var askHintLimit = 8;
49376
- function openAskChoices(asks, owner) {
49377
- if (asks.length === 0)
49378
- return `${owner} holds no open ask.`;
49379
- const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)}\u2026 ${textHead(ask.question)}`);
49380
- return `The open asks of ${owner} are: ${hints.join(", ")}.`;
49381
- }
49382
- function askIDInputProblem(asks, owner) {
49383
- return `ask ids are uuids. Write the whole id, or at least its first 8 characters. ${openAskChoices(asks, owner)}`;
49384
- }
49385
- async function movedApprovalLine(client, askID) {
49386
- const ask = (await client.getAsk(askID).catch(() => {
49387
- return;
49388
- }))?.ask;
49389
- const approval = ask?.approval;
49390
- if (ask?.kind !== "approval" || approval === undefined)
49391
- return;
49392
- const listed = approval.documents ?? [];
49393
- const documents = listed.length > 0 ? listed : [
49394
- {
49395
- name: approval.name,
49396
- requested_version: approval.requested_version,
49397
- version: approval.version
49398
- }
49399
- ];
49400
- const moved = movedApprovalDocuments(documents);
49401
- if (moved.length === 0)
49402
- return;
49403
- const firstMoved = moved[0];
49404
- if (firstMoved === undefined)
49405
- return;
49406
- const command = handBackApprovalCommand({
49407
- owner: ask.issue_key === null ? { kind: "project", key: ask.approval_artifact?.project ?? "<project>" } : { kind: "issue", key: ask.issue_key },
49408
- artifactID: approval.artifact_id,
49409
- primary: ask.approval_artifact?.primary === true,
49410
- verification: documents.length > 1 && ask.approval_artifact?.primary === true,
49411
- summaryVersion: firstMoved.requested_version
49412
- });
49413
- return "The reply did not hand the ask to the human: it is an open approval request, and " + `${movedApprovalClauses(moved)}. No reply hands a moved approval request back. Once the ` + `human has agreed to every point in it, run: ${command}`;
49414
- }
49415
- async function replyToAskCandidates(client, owner, resolved) {
49416
- if (owner.kind === "issue") {
49417
- const issue = resolved?.issue ?? await client.getIssue(owner.issue);
49418
- return { asks: issue.open_asks ?? [], owner: "this issue" };
49419
- }
49420
- if (resolved === undefined)
49421
- throw new Error("project document is missing its resolved artifact");
49422
- return {
49423
- asks: await client.getArtifactAsks(resolved.artifact.id, "open"),
49424
- owner: "this document"
49425
- };
49426
- }
49427
- async function resolveReplyToAsk(tool, client, target, resolved, id) {
49428
- const whole = normalizeUUID(id);
49429
- if (whole !== undefined)
49430
- return whole;
49431
- const { asks, owner } = await replyToAskCandidates(client, target, resolved);
49432
- if (!isIdPrefix(id)) {
49433
- throw new ToolInputError(tool, [askIDInputProblem(asks, owner)], { aboutAFlag: false });
49280
+ // ../envoy-client/src/dispatch-commands/issues.ts
49281
+ function componentsChange(input, after) {
49282
+ switch (input.mode) {
49283
+ case "explicit":
49284
+ return `components -> explicit [${(after.ids ?? []).join(", ")}]`;
49285
+ case "none":
49286
+ return `components -> none (${after.reason ?? input.reason ?? ""})`;
49287
+ case "inherit":
49288
+ return "components -> inherit";
49289
+ default:
49290
+ return `components -> ${input.mode}`;
49434
49291
  }
49435
- return resolveIdPrefix(tool, "ask", id, owner, async () => asks, {
49436
- refusal: (found, all) => found.length === 0 ? `reply_to_ask ${id} names no open ask of ${owner}. ${openAskChoices(all, owner)}` : `reply_to_ask ${id} names ${found.length} open asks of ${owner}. Write more of the id. ${openAskChoices(all, owner)}`
49437
- });
49438
49292
  }
49439
- var askIdShapeProblem = "ask ids are uuids (a prefix of at least 8 hex characters works)";
49440
- async function readAskRef(tool, id, ownerName, client, list) {
49441
- const fullID = normalizeUUID(id);
49442
- if (fullID !== undefined) {
49443
- try {
49444
- return await client.getAsk(fullID);
49445
- } catch (error) {
49446
- if (!(error instanceof DispatchServiceError) || error.status !== 404)
49447
- throw error;
49448
- const blocks = (await list()).filter((ask) => ask.block_id?.toLowerCase() === fullID);
49449
- if (blocks.length !== 1 || blocks[0] === undefined)
49450
- throw error;
49451
- return client.getAsk(blocks[0].id);
49452
- }
49453
- }
49454
- const asks = await list();
49455
- let matches = asks.filter((ask) => ask.block_id === id);
49456
- if (matches.length === 0) {
49457
- if (!isIdPrefix(id)) {
49458
- throw new ToolInputError(tool, [
49459
- `ask id ${id} must be a full uuid, a prefix of at least 8 hex characters, or the id of an :::ask block on ${ownerName}`
49460
- ]);
49461
- }
49462
- const prefix = id.toLowerCase();
49463
- matches = asks.filter((ask) => ask.id.toLowerCase().startsWith(prefix) || (ask.block_id?.toLowerCase().startsWith(prefix) ?? false));
49293
+ var architectureComponentsAction = 'Review the `dispatch` skill, "Architecture components", to attach it to the parts it changes or mark it as non-architectural with a reason.';
49294
+ var LEGION_OWNS_STATUS = "Legion's daemon moves this issue's status on an issue it runs, so leave it alone \u2014 a status written here is undone.";
49295
+ async function architectureGuidance(client, project, components) {
49296
+ if (components.mode === "none" || (components.ids ?? []).length > 0)
49297
+ return;
49298
+ try {
49299
+ if ((await client.listArchitectureSources(project)).length === 0)
49300
+ return;
49301
+ return `Project ${project} has an architecture model, but this issue is not linked to any of its current components. ${architectureComponentsAction}`;
49302
+ } catch (error) {
49303
+ return `Could not check whether project ${project} has an architecture model: ${messageFor(error)}. ${architectureComponentsAction}`;
49464
49304
  }
49465
- if (matches.length === 1 && matches[0] !== undefined)
49466
- return client.getAsk(matches[0].id);
49467
- throw new ToolInputError(tool, [
49468
- matches.length === 0 ? `ask id ${id} matches none of the asks on ${ownerName}; use the full id` : `ask id ${id} matches ${matches.length} asks on ${ownerName}; use the full id`
49469
- ]);
49470
49305
  }
49471
- async function sessionOpenAsks(client, sessionId) {
49472
- const session = sessionId?.trim();
49473
- if (!session)
49474
- throw new Error("host session id is required to read this session's open asks");
49475
- return (await client.openAsks(session)).asks ?? [];
49306
+ function isDuplicateCandidate(value) {
49307
+ if (typeof value !== "object" || value === null)
49308
+ return false;
49309
+ const candidate = value;
49310
+ return typeof candidate.key === "string" && typeof candidate.title === "string" && typeof candidate.status === "string" && typeof candidate.snippet === "string" && typeof candidate.shared_terms === "number" && typeof candidate.href === "string";
49476
49311
  }
49477
- function openAskHints(asks) {
49478
- if (asks.length === 0)
49479
- return "you have no open asks";
49480
- const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)} \u2014 ${textHead(ask.question)}`);
49481
- return `your open asks: ${hints.join("; ")}`;
49312
+ function duplicateCandidates(error) {
49313
+ if (error.candidates === undefined || !error.candidates.every(isDuplicateCandidate))
49314
+ throw error;
49315
+ return error.candidates;
49482
49316
  }
49483
- async function resolveAskArgument(tool, args, client, sessionId) {
49484
- const id = askId(args);
49485
- if (normalizeUUID(id) === undefined && !isIdPrefix(id)) {
49486
- const asks = await sessionOpenAsks(client, sessionId).catch(() => {
49487
- return;
49488
- });
49489
- throw new ToolInputError(tool, [
49490
- asks === undefined ? askIdShapeProblem : `${askIdShapeProblem}; ${openAskHints(asks)}`
49491
- ]);
49492
- }
49493
- const resolved = await resolveIdPrefix(tool, "ask", id, "this session", () => sessionOpenAsks(client, sessionId));
49494
- const reference = stringArg(args, "ask");
49495
- const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
49496
- if (ref === null)
49497
- return { id: resolved };
49498
- const read = await client.getAsk(resolved);
49499
- await refuseItemOffRef(tool, "ask", ref, reference, read.ask, async () => {
49500
- const document = await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true });
49501
- return document.artifact.id;
49502
- });
49503
- return { id: resolved, read };
49317
+ function refuseUnsavedRepository(verb, issue, repo) {
49318
+ if (repo === undefined || issue.repo !== undefined)
49319
+ return;
49320
+ const lost = repo === "" ? "the repository was not cleared" : `${repo} was not saved`;
49321
+ throw new Error(`Dispatch ${verb} ${issue.key} without its repository: this Dispatch server predates repository fields, so ${lost}; upgrade the server`);
49504
49322
  }
49505
- async function openAsksCommand(context) {
49506
- const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
49507
- const client = dispatchClient();
49508
- const project = optionalString(ownerArguments.args, "project");
49509
- if (project !== undefined) {
49510
- const response = await client.openAsksForProject(project);
49511
- return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
49323
+ function advancesRevisionToSend(issue, named) {
49324
+ if (issue.advances_revision === undefined) {
49325
+ throw new Error(`Dispatch read ${issue.key} without its advances: this Dispatch server predates priorities, so nothing was sent; upgrade the server`);
49512
49326
  }
49513
- const sessionId = input.sessionId?.trim();
49514
- if (!sessionId)
49515
- throw new Error("host session id is required for dispatch open-asks");
49516
- const response = await client.openAsks(sessionId);
49517
- return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
49327
+ return named ?? issue.advances_revision;
49518
49328
  }
49519
- async function askCommand(context) {
49520
- const {
49521
- args,
49522
- client,
49523
- actor,
49524
- input,
49525
- linkBase,
49526
- documentOwner,
49527
- resolveDocument,
49528
- writePictures,
49529
- issue
49530
- } = context;
49531
- const anchorArgs = asObject(args.anchor);
49532
- const owner = documentOwner();
49533
- const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
49534
- const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
49535
- const options = args.options;
49536
- const multiple = optionalBoolean(args, "multiple");
49537
- const urgency = askUrgency(args);
49538
- const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
49539
- const question = await writePictures(resolved, askQuestionWithRef(args));
49540
- const askInput = {
49541
- question,
49542
- ...Array.isArray(options) ? { options } : {},
49543
- ...multiple === undefined ? {} : { multiple },
49544
- ...urgency === undefined ? {} : { urgency },
49545
- ...anchored === undefined ? {} : { anchor: anchored },
49546
- actor
49329
+ async function issueCommand(context) {
49330
+ const { args, client, actor, input, linkBase } = context;
49331
+ const project = stringArg(args, "project");
49332
+ const title = stringArg(args, "title");
49333
+ const parent = optionalString(args, "parent");
49334
+ const external = optionalString(args, "external");
49335
+ const force = optionalBoolean(args, "force");
49336
+ const spec = optionalString(args, "spec");
49337
+ const priority = optionalPriority(args, "priority");
49338
+ const assignee = optionalString(args, "assignee");
49339
+ const components = optionalComponents(args, "components");
49340
+ const repo = optionalString(args, "repo");
49341
+ const labels = args.labels;
49342
+ const blockedBy = args.blocked_by;
49343
+ const advances = optionalStringArray(args, "advances");
49344
+ try {
49345
+ const created = await client.issue({
49346
+ project,
49347
+ title,
49348
+ ...parent === undefined ? {} : { parent },
49349
+ ...Array.isArray(blockedBy) ? { blocked_by: blockedBy } : {},
49350
+ ...advances === undefined ? {} : { advances },
49351
+ ...external === undefined ? {} : { external },
49352
+ ...force === undefined ? {} : { force },
49353
+ ...spec === undefined ? {} : { spec },
49354
+ ...priority === undefined ? {} : { priority },
49355
+ ...assignee === undefined ? {} : { assignee },
49356
+ ...components === undefined ? {} : { components },
49357
+ ...repo === undefined ? {} : { repo },
49358
+ ...Array.isArray(labels) ? { labels } : {},
49359
+ actor
49360
+ });
49361
+ refuseUnsavedRepository(created.created ? "created" : "already holds", created, repo);
49362
+ const adviceLines = await otherAdviceLines(async () => {
49363
+ const componentGuidance = await architectureGuidance(client, created.project, created.components);
49364
+ return [
49365
+ ...renderAdvice(input.tool, created.key, created.advice, {
49366
+ isPrimarySpec: spec !== undefined
49367
+ }),
49368
+ ...componentGuidance === undefined ? [] : [componentGuidance]
49369
+ ];
49370
+ });
49371
+ const href = linkFor(`/issues/${encodeURIComponent(created.key)}`, linkBase);
49372
+ const assigned = created.assignee === undefined ? "" : created.assignee === null ? "; unassigned" : `; assigned to ${created.assignee}`;
49373
+ const suffixes = `${assigned}${await notSubscribed(issueTopic(created.key), input.subscriptions)}`;
49374
+ return {
49375
+ text: [
49376
+ created.created ? `Created ${created.key}: ${created.title} \u2192 ${href}${suffixes}` : `Dispatch already holds ${created.key}: ${created.title} \u2192 ${href}; nothing was created${suffixes}`,
49377
+ ...created.created ? relatedCheckLines(created.advice?.suggestions, {
49378
+ project: created.project,
49379
+ text: title,
49380
+ linkBase
49381
+ }) : [],
49382
+ ...adviceLines
49383
+ ].join(`
49384
+ `),
49385
+ details: {
49386
+ issue: created.key,
49387
+ ...created.advice === undefined ? {} : { advice: created.advice }
49388
+ }
49389
+ };
49390
+ } catch (error) {
49391
+ if (!(error instanceof DispatchServiceError) || error.code !== "POSSIBLE_DUPLICATE") {
49392
+ throw error;
49393
+ }
49394
+ const candidates = duplicateCandidates(error);
49395
+ return {
49396
+ text: [
49397
+ `Not created: "${title}" is a near copy of an open issue.`,
49398
+ ...candidates.map((candidate) => {
49399
+ const href = linkFor(candidate.href, linkBase);
49400
+ return `${candidate.key} [${candidate.status}] ${candidate.title} \u2192 ${href}`;
49401
+ }),
49402
+ "Read each issue above. If one is the same work, fold this into it by the duplicate rule of skill://dispatch-first.",
49403
+ "If none is, run dispatch issue again with --force, and write in the new issue's spec why it is not each issue named here."
49404
+ ].join(`
49405
+ `),
49406
+ details: { duplicates: candidates },
49407
+ refused: true
49408
+ };
49409
+ }
49410
+ }
49411
+ async function issueUpdateCommand(context) {
49412
+ const { args, client, actor, input, issue } = context;
49413
+ const issueKey = issue();
49414
+ const status = optionalString(args, "status");
49415
+ const reason = optionalString(args, "reason");
49416
+ const title = optionalString(args, "title");
49417
+ const route = optionalString(args, "route");
49418
+ const parent = optionalString(args, "parent");
49419
+ const components = optionalComponents(args, "components");
49420
+ const repo = optionalString(args, "repo");
49421
+ const rankBefore = optionalString(args, "before");
49422
+ const rankAfter = optionalString(args, "after");
49423
+ const priority = optionalPriority(args, "priority");
49424
+ const assignee = optionalNullableString(args, "assignee");
49425
+ const labels = Array.isArray(args.labels) ? args.labels : undefined;
49426
+ const blockedBy = Array.isArray(args.blocked_by) ? args.blocked_by : undefined;
49427
+ const advances = optionalStringArray(args, "advances");
49428
+ const advancesRevision = optionalNumber(args, "advances_revision");
49429
+ const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
49430
+ let before;
49431
+ try {
49432
+ before = await client.getIssue(issueKey);
49433
+ } catch (error) {
49434
+ throw refusalWithCode(error);
49435
+ }
49436
+ const advancesWrite = advances === undefined ? undefined : { advances, advances_revision: advancesRevisionToSend(before, advancesRevision) };
49437
+ if (status === "done" && typeof before.closed_at === "string") {
49438
+ throw refusalWithCode(new DispatchServiceError("ISSUE_CLOSED", 409, "issue is closed"), `${issueKey} closed at ${before.closed_at}, so the reason was not posted and the close was not sent`);
49439
+ }
49440
+ let closingNote;
49441
+ if (reason !== undefined) {
49442
+ try {
49443
+ const message = await client.message(issueKey, { body: reason, actor });
49444
+ closingNote = {
49445
+ id: message.id,
49446
+ ref: dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id)
49447
+ };
49448
+ } catch (error) {
49449
+ if (error instanceof DispatchWriteLandedError) {
49450
+ throw new Error(`${error.message} That was the closing reason, so the close was not sent: read the issue's messages for it, then close with a reason that points at it, since retrying this call posts its reason again.`, { cause: error });
49451
+ }
49452
+ const told = writeMayHaveLanded(error) ? "the reason may or may not have been posted, and the close was not sent: read the issue's messages before retrying, since retrying this call posts its reason again" : "the reason was not posted, so the close was not sent";
49453
+ if (error instanceof DispatchServiceError)
49454
+ throw refusalWithCode(error, told);
49455
+ throw withAccount(error, told);
49456
+ }
49457
+ }
49458
+ const existingLinks = before.external_links ?? [];
49459
+ const linked = existingLinks.map((link) => link.url);
49460
+ const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
49461
+ const sentLinks = requestedLinks === undefined ? undefined : requestedLinks.length === 0 ? [] : [...existingLinks, ...newLinks.map((url) => ({ url }))];
49462
+ const rank = rankBefore === undefined && rankAfter === undefined ? undefined : {
49463
+ ...rankBefore === undefined ? {} : { before: rankBefore },
49464
+ ...rankAfter === undefined ? {} : { after: rankAfter }
49547
49465
  };
49548
- const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
49549
- const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
49550
- const checkLines = relatedCheckLines(ask.advice?.suggestions, {
49551
- project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
49552
- text: stringArg(args, "question"),
49553
- linkBase
49466
+ let after;
49467
+ try {
49468
+ after = await client.updateIssue(issueKey, {
49469
+ ...status === undefined ? {} : { status },
49470
+ ...title === undefined ? {} : { title },
49471
+ ...labels === undefined ? {} : { labels },
49472
+ ...priority === undefined ? {} : { priority },
49473
+ ...assignee === undefined ? {} : { assignee },
49474
+ ...route === undefined ? {} : { route },
49475
+ ...parent === undefined ? {} : { parent: parent === "" ? null : parent },
49476
+ ...blockedBy === undefined ? {} : { blocked_by: blockedBy },
49477
+ ...advancesWrite,
49478
+ ...components === undefined ? {} : { components },
49479
+ ...repo === undefined ? {} : { repo: repo === "" ? null : repo },
49480
+ ...sentLinks === undefined ? {} : { external_links: sentLinks },
49481
+ ...rank === undefined ? {} : { rank },
49482
+ actor
49483
+ });
49484
+ } catch (error) {
49485
+ if (error instanceof DispatchWriteLandedError)
49486
+ throw error;
49487
+ const answered = error instanceof DispatchWriteUnsettledError ? error.last : error;
49488
+ const taken = dispatchAnswered(answered, 500) && newLinks.length > 0 ? `one of ${newLinks.join(", ")} may already be linked from another issue (a URL links exactly one issue)` : "";
49489
+ if (closingNote === undefined) {
49490
+ if (taken !== "" && !(error instanceof DispatchServiceError)) {
49491
+ throw withAccount(error, taken);
49492
+ }
49493
+ throw refusalWithCode(error, taken);
49494
+ }
49495
+ const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
49496
+ const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
49497
+ const landed = writeMayHaveLanded(error) ? `${posted}, and the close may or may not have taken effect. Read the issue's status before retrying: done means it closed; otherwise retry with a reason that points at message ${closingNote.id}, since retrying this call posts its reason again` : `${posted} but the issue did not close. Retrying this call posts its reason again, so ${fix}retry with a reason that points at message ${closingNote.id}`;
49498
+ if (error instanceof DispatchServiceError)
49499
+ throw refusalWithCode(error, taken, landed);
49500
+ throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
49501
+ }
49502
+ refuseUnsavedRepository("updated", after, repo);
49503
+ const links = after.external_links ?? [];
49504
+ const linkCount = `(${links.length} ${links.length === 1 ? "link" : "links"})`;
49505
+ const stated = (after.advances ?? []).filter((advance) => !advance.inherited).map((advance) => advance.id);
49506
+ const changes = [
49507
+ ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
49508
+ ...status === undefined ? [] : [`status ${before.status} -> ${after.status}`],
49509
+ ...title === undefined ? [] : [`title "${after.title}"`],
49510
+ ...labels === undefined ? [] : [
49511
+ (after.labels ?? []).length === 0 ? "labels cleared" : `labels ${(after.labels ?? []).join(", ")}`
49512
+ ],
49513
+ ...priority === undefined ? [] : [after.priority === null ? "priority cleared" : `priority -> P${after.priority}`],
49514
+ ...assignee === undefined ? [] : [after.assignee === null ? "assignee cleared" : `assignee -> ${after.assignee}`],
49515
+ ...rank === undefined ? [] : [
49516
+ `rank -> ${[
49517
+ ...rankAfter === undefined ? [] : [`after ${rankAfter}`],
49518
+ ...rankBefore === undefined ? [] : [`before ${rankBefore}`]
49519
+ ].join(", ")}`
49520
+ ],
49521
+ ...requestedLinks === undefined ? [] : [
49522
+ requestedLinks.length === 0 ? "external links cleared" : newLinks.length === 0 ? `already linked ${requestedLinks.join(", ")} ${linkCount}` : `linked ${newLinks.join(", ")} ${linkCount}`
49523
+ ],
49524
+ ...route === undefined ? [] : [after.route === null ? "route cleared" : `route ${after.route}`],
49525
+ ...parent === undefined ? [] : [after.parent === null ? "parent cleared" : `parent -> ${after.parent}`],
49526
+ ...blockedBy === undefined ? [] : [
49527
+ (after.blocked_by ?? []).length === 0 ? "blocked_by cleared" : `blocked by ${(after.blocked_by ?? []).join(", ")}`
49528
+ ],
49529
+ ...advances === undefined ? [] : [stated.length === 0 ? "advances cleared" : `advances ${stated.join(", ")}`],
49530
+ ...components === undefined ? [] : [componentsChange(components, after.components)],
49531
+ ...repo === undefined ? [] : [
49532
+ after.repo === null ? `repo cleared (resolves to ${after.resolved_repo ?? "none"})` : `repo -> ${after.repo}`
49533
+ ]
49534
+ ];
49535
+ const adviceLines = renderAdvice(input.tool, after.key, after.advice, {
49536
+ setsStatus: status !== undefined
49554
49537
  });
49555
- const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
49556
- const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
49557
- const asked = waitsOnPerson(ask);
49558
49538
  return {
49559
49539
  text: [
49560
- `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
49561
- ...checkLines,
49562
- ...declinedLines,
49563
- await followsAsk(askOwner, input.subscriptions),
49540
+ `${after.key}: ${changes.join("; ")}${await notSubscribed(issueTopic(after.key), input.subscriptions)}`,
49564
49541
  ...adviceLines
49565
49542
  ].join(`
49566
49543
  `),
49567
49544
  details: {
49568
- ...await followedAskDetails(client, ask, resolved?.artifact),
49569
- ...ask.advice === undefined ? {} : { advice: ask.advice }
49545
+ issue: after.key,
49546
+ status: after.status,
49547
+ external_links: (after.external_links ?? []).map((link) => link.url),
49548
+ ...closingNote === undefined ? {} : { message: closingNote.id },
49549
+ ...after.advice === undefined ? {} : { advice: after.advice }
49570
49550
  }
49571
49551
  };
49572
49552
  }
49573
- async function editAskCommand(context) {
49574
- const { args, client, actor, input } = context;
49575
- const question = optionalString(args, "question");
49576
- const options = args.options;
49577
- const multiple = optionalBoolean(args, "multiple");
49578
- const urgency = askUrgency(args);
49579
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
49580
- const ask = await client.editAsk(id, {
49581
- ...question === undefined ? {} : { question },
49582
- ...Array.isArray(options) ? { options } : {},
49583
- ...multiple === undefined ? {} : { multiple },
49584
- ...urgency === undefined ? {} : { urgency },
49585
- actor
49586
- });
49587
- return {
49588
- text: `Ask edited: ${ask.question}`,
49589
- details: await askOwnerDetails(client, ask)
49590
- };
49591
- }
49592
- async function resolveAskCommand(context) {
49593
- const { args, client, actor, input } = context;
49594
- const kind = stringArg(args, "kind");
49595
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
49596
- const ask = await client.resolveAsk(id, {
49597
- kind,
49598
- reason: stringArg(args, "reason"),
49599
- actor
49600
- });
49601
- if (ask.resolution === undefined)
49602
- throw new Error("resolved ask is missing its resolution");
49603
- return {
49604
- text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
49605
- details: await askOwnerDetails(client, ask)
49606
- };
49607
- }
49608
- async function followCommand(context) {
49609
- const { args, client, actor, input } = context;
49610
- const sessionId = input.sessionId?.trim();
49611
- if (!sessionId)
49612
- throw new Error("host session id is required for dispatch follow");
49613
- const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
49614
- const action = stringArg(args, "action");
49615
- if (action === "unfollow") {
49616
- await client.unfollowAsk(ask, sessionId, actor);
49617
- return { text: `Unfollowed ask ${ask}.`, details: { ask } };
49553
+ async function claimCommand(context) {
49554
+ const { args, client, actor, input, issue } = context;
49555
+ const issueKey = issue();
49556
+ const release = optionalBoolean(args, "release") ?? false;
49557
+ let after;
49558
+ try {
49559
+ after = release ? await client.releaseIssueClaim(issueKey, { actor }) : await client.claimIssue(issueKey, { actor });
49560
+ } catch (error) {
49561
+ throw refusalWithCode(error);
49562
+ }
49563
+ const held = after.claim;
49564
+ const legionManaged = after.legion_managed_status === true;
49565
+ let text;
49566
+ if (release) {
49567
+ const released = `${issueKey}: claim released; nobody is working it now. Its status is still ${after.status}`;
49568
+ text = legionManaged ? `${released}; ${LEGION_OWNS_STATUS}` : `${released} \u2014 move it yourself if that is no longer where the work is.`;
49569
+ } else {
49570
+ if (held === null) {
49571
+ throw new Error(`Dispatch claimed ${issueKey} but answered with no claim`);
49572
+ }
49573
+ const claimed = `${issueKey}: claimed by you since ${held.at}. Its status is ${after.status}`;
49574
+ const reaches = `A person's answers, comments and messages on ${issueKey} now reach you directly.`;
49575
+ text = legionManaged ? `${claimed}; ${LEGION_OWNS_STATUS} Release the claim when you stop. ${reaches}` : `${claimed}; a claim moves nothing, so move it to in_progress with dispatch issue-update when you start, and release the claim when you stop. ${reaches}`;
49618
49576
  }
49619
- const read = refRead ?? await client.getAsk(ask);
49620
- await client.followAsk(ask, sessionId, actor);
49621
49577
  return {
49622
- text: `Following ask ${ask}: its answer and replies reach this session directly.`,
49623
- details: await followedAskDetails(client, read.ask)
49578
+ text: `${text}${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
49579
+ details: { issue: issueKey, status: after.status, claim: held }
49624
49580
  };
49625
49581
  }
49626
-
49627
- // ../envoy-client/src/dispatch-commands/conversation.ts
49628
- async function resolveCommentCommand(context) {
49629
- const { args, client, actor, input } = context;
49630
- const reference = stringArg(args, "comment");
49631
- const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
49632
- let id = reference;
49633
- let document;
49634
- if (ref?.owner.kind === "issue") {
49635
- const issueKey = ref.owner.issue;
49636
- id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
49637
- } else if (ref !== null) {
49638
- const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
49639
- document = artifact;
49640
- id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
49641
- }
49642
- if (ref !== null) {
49643
- const read = await client.getComment(id);
49644
- await refuseItemOffRef(input.tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
49645
- }
49646
- const comment = await client.resolveComment(id, actor);
49647
- const { label, details } = await commentOwnerResult(client, comment, document);
49648
- return { text: `Resolved comment ${comment.id} on ${label}.`, details };
49582
+ async function searchCommand(context) {
49583
+ const { args, client, linkBase } = context;
49584
+ const query = stringArg(args, "query");
49585
+ const project = optionalString(args, "project");
49586
+ const limit = optionalNumber(args, "limit");
49587
+ const offset = optionalNumber(args, "offset");
49588
+ const search = await client.search(query, {
49589
+ ...project === undefined ? {} : { project },
49590
+ ...limit === undefined ? {} : { limit },
49591
+ ...offset === undefined ? {} : { offset }
49592
+ });
49593
+ return searchAnswer(search, query, offset, linkBase);
49649
49594
  }
49650
- async function commentCommand(context) {
49651
- const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
49652
- const artifactReference = optionalString(args, "artifact");
49653
- const owner = documentOwner();
49654
- const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
49655
- const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
49656
- const replyTo = itemReplyTo(args, "reply_to");
49657
- const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
49658
- const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
49659
- const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
49660
- const requestedTurn = optionalString(args, "turn");
49661
- const body = await writePictures(resolved, stringArg(args, "body"));
49662
- const commentInput = {
49663
- body,
49664
- ...anchored === undefined ? {} : { anchor: anchored },
49665
- ...replyTo === undefined ? {} : { reply_to: replyTo.id },
49666
- ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
49667
- ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
49668
- ...requestedTurn === undefined ? {} : { turn: requestedTurn },
49669
- actor
49670
- };
49671
- const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
49672
- const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
49673
- const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
49674
- const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
49675
- isAskReply: replyToAsk !== undefined,
49676
- replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
49595
+ async function relatedCommand(context) {
49596
+ const { args, client, linkBase } = context;
49597
+ const project = stringArg(args, "project");
49598
+ const title = optionalString(args, "title");
49599
+ const text = optionalString(args, "text");
49600
+ const excludeIssues = optionalStringArray(args, "exclude_issues");
49601
+ const keywordsOnly = optionalBoolean(args, "keywords_only");
49602
+ const suggestions = await client.related(project, {
49603
+ ...title === undefined ? {} : { title },
49604
+ ...text === undefined ? {} : { text },
49605
+ ...excludeIssues === undefined ? {} : { exclude_issues: excludeIssues },
49606
+ ...keywordsOnly === undefined ? {} : { keywords_only: keywordsOnly }
49677
49607
  });
49678
- if (replyToAsk !== undefined) {
49679
- const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
49680
- const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
49681
- return {
49682
- text: [
49683
- `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
49684
- ...moved === undefined ? [] : [moved],
49685
- ...adviceLines
49686
- ].join(`
49687
- `),
49688
- details: {
49689
- ...commentDetails,
49690
- ask: replyToAsk,
49691
- follows: { ask: replyToAsk },
49692
- ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
49693
- ...comment.advice === undefined ? {} : { advice: comment.advice }
49694
- }
49695
- };
49696
- }
49697
49608
  return {
49698
- text: [
49699
- `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
49700
- ...adviceLines
49701
- ].join(`
49609
+ text: relatedCheckLines(suggestions, {
49610
+ project,
49611
+ text: [title, text].filter((part) => part !== undefined).join(`
49702
49612
  `),
49703
- details: {
49704
- ...commentDetails,
49705
- ...comment.advice === undefined ? {} : { advice: comment.advice }
49706
- }
49613
+ linkBase
49614
+ }).join(`
49615
+ `),
49616
+ details: { project, suggestions }
49707
49617
  };
49708
49618
  }
49709
- async function suggestCommand(context) {
49710
- const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
49711
- const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
49712
- const anchored = anchor(resolved.artifact, args);
49713
- if (anchored === undefined)
49714
- throw new Error("quote is required");
49715
- const body = optionalString(args, "body");
49716
- const suggestionInput = {
49717
- ...body === undefined ? {} : { body },
49718
- anchor: anchored,
49719
- replace_with: stringArg(args, "replace_with"),
49720
- actor
49619
+ async function issuesCommand(context) {
49620
+ const { args, client } = context;
49621
+ const project = stringArg(args, "project");
49622
+ const status = optionalString(args, "status");
49623
+ const parent = optionalString(args, "parent");
49624
+ const label = optionalString(args, "label");
49625
+ const priority = optionalPriorityFilter(args, "priority");
49626
+ const updatedSince = optionalString(args, "updated_since");
49627
+ const routeStatus = optionalString(args, "route_status");
49628
+ const filters = {
49629
+ project,
49630
+ ...status === undefined ? {} : { status },
49631
+ ...parent === undefined ? {} : { parent },
49632
+ ...label === undefined ? {} : { label },
49633
+ ...priority === undefined ? {} : { priority },
49634
+ ...updatedSince === undefined ? {} : { updated_since: updatedSince },
49635
+ ...routeStatus === undefined ? {} : { route_status: routeStatus }
49721
49636
  };
49722
- const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
49637
+ const page = optionalBoolean(args, "all") === true ? await client.listAllIssues(filters).then((issues) => ({
49638
+ issues,
49639
+ total: issues.length,
49640
+ limit: issues.length,
49641
+ offset: 0
49642
+ })) : await client.listIssuePage(filters, {
49643
+ limit: optionalNumber(args, "limit") ?? DEFAULT_ISSUE_PAGE_LIMIT,
49644
+ offset: optionalNumber(args, "offset") ?? 0
49645
+ });
49646
+ const { total, limit, offset } = page;
49647
+ const rows = (page.issues ?? []).map((row) => ({
49648
+ key: row.key,
49649
+ title: row.title,
49650
+ status: row.status,
49651
+ priority: row.priority,
49652
+ parent: row.parent,
49653
+ labels: row.labels ?? [],
49654
+ open_asks: row.open_asks,
49655
+ claim: row.claim ?? null,
49656
+ route: row.route ?? null,
49657
+ route_status: row.route_status ?? null,
49658
+ route_holder: row.route_holder ?? null,
49659
+ route_status_reason: row.route_status_reason ?? null,
49660
+ updated_at: row.updated_at,
49661
+ progress: row.progress
49662
+ }));
49663
+ const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
49664
+ const isPartial = offset !== 0 || rows.length !== total;
49665
+ const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
49723
49666
  return {
49724
- text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
49725
- details: writeResultDetails(resolved, { comment: comment.id })
49667
+ text: rows.length === 0 ? `No issues in ${project}.${isPartial ? ` (${showing})` : ""}` : [
49668
+ `${rows.length} ${rows.length === 1 ? "issue" : "issues"} in ${project}` + (isPartial ? ` (${showing})` : ""),
49669
+ ...rows.map((row) => {
49670
+ const progress = progressText(row.progress, " \xB7 ");
49671
+ return `${row.key} [${row.status}]${row.priority === null ? "" : ` P${row.priority}`} ${row.title}` + (row.open_asks === 0 ? "" : ` \xB7 ${row.open_asks} open ${row.open_asks === 1 ? "ask" : "asks"}`) + (row.claim === null ? "" : ` \xB7 claimed by ${claimText(row.claim, agents)}`) + (progress === "" ? "" : ` \xB7 ${progress}`) + (row.route === null || row.route_status === "live" || row.route_status === null ? "" : ` \xB7 route ${routeText(row)}`);
49672
+ })
49673
+ ].join(`
49674
+ `),
49675
+ details: { issues: rows, total, offset, limit }
49726
49676
  };
49727
49677
  }
49728
- function conversationReadBack(messageId) {
49729
- return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
49678
+ var BRIEF_READING_CHARACTERS = 200;
49679
+ var COMPARISON_REASONS = {
49680
+ no_pull_request_or_branch: "the issue has no pull request and no branch to compare with",
49681
+ repository_unreadable: "Dispatch cannot read the repository",
49682
+ read_failed: "a read Dispatch made did not answer"
49683
+ };
49684
+ function learnedText(learned) {
49685
+ if (learned.kind === "read_at")
49686
+ return `Dispatch read it ${learned.at}`;
49687
+ return `GitHub updated it ${learned.at}`;
49730
49688
  }
49731
- async function messageCommand(context) {
49732
- const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
49733
- const target = messageInReplyTo(args);
49734
- const inReplyTo = target?.id;
49735
- const written = stringArg(args, "body");
49736
- if (owner === null && inReplyTo !== undefined) {
49737
- let body = written;
49738
- if (pictures.length > 0) {
49739
- const sessionId = input.sessionId?.trim();
49740
- if (!sessionId) {
49741
- throw new Error("host session id is required to send pictures in a direct-message reply");
49742
- }
49743
- body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
49744
- }
49745
- const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
49746
- if (reply.duplicate === true && reply.body === body) {
49747
- return {
49748
- text: `Dispatch already has this exact text in the conversation (message ${reply.id}); ` + "nothing new was posted. Send different text if you have more to say.",
49749
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
49750
- };
49751
- }
49752
- if (reply.body !== body) {
49753
- return {
49754
- text: `Message ${inReplyTo} was already answered by message ${reply.id}; Dispatch kept ` + "that reply and posted nothing. Wait for their next message rather than answering " + "this one again.",
49755
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
49756
- };
49757
- }
49758
- const readBack = conversationReadBack(inReplyTo);
49759
- const parent = reply.in_reply_to ?? undefined;
49760
- const follows = parent === inReplyTo ? undefined : parent;
49689
+ function basisText(basis) {
49690
+ const learned = basis.learned_at === undefined ? "" : ` (${learnedText(basis.learned_at)})`;
49691
+ if (basis.kind === "pull_request") {
49692
+ const number = basis.pull_request === undefined ? "" : `#${basis.pull_request} `;
49693
+ return `the head of pull request ${number}at ${basis.commit ?? "an unnamed commit"}${learned}`;
49694
+ }
49695
+ if (basis.kind === "branch")
49696
+ return `branch ${basis.branch ?? "unnamed"}${learned}`;
49697
+ return `the commit you named, ${basis.commit ?? ""}${learned}`;
49698
+ }
49699
+ function basisPlace(basis) {
49700
+ if (basis.kind === "pull_request") {
49701
+ return basis.pull_request === undefined ? "the head of a pull request" : `the head of pull request #${basis.pull_request}`;
49702
+ }
49703
+ if (basis.kind === "branch")
49704
+ return `on branch ${basis.branch ?? "unnamed"}`;
49705
+ return "the commit you named";
49706
+ }
49707
+ function commitStandsText(stands) {
49708
+ if (stands === undefined) {
49709
+ return "Where that commit stands is not known: this Dispatch server does not say";
49710
+ }
49711
+ if (stands.answer === "at_basis") {
49712
+ return stands.basis === undefined ? "That commit is one of the compared commits" : `That commit is ${basisPlace(stands.basis)}`;
49713
+ }
49714
+ if (stands.answer === "other_commit")
49715
+ return "That commit is none of the compared commits";
49716
+ return stands.reason === undefined ? "Where that commit stands is not known" : `Where that commit stands is not known: ${COMPARISON_REASONS[stands.reason]}`;
49717
+ }
49718
+ function checkWordsText(check, result) {
49719
+ const versions = `result version ${result.check_version}, check version ${check.version}`;
49720
+ if (result.check_words_moved === undefined) {
49721
+ return `Whether the check's words moved is not known (${versions})`;
49722
+ }
49723
+ return result.check_words_moved ? `The check's words moved after this result (${versions})` : `The check's words did not move after this result (${versions})`;
49724
+ }
49725
+ function passStandsText(pass) {
49726
+ if (pass === undefined)
49727
+ return "Whether a pass stands is not known: this Dispatch server does not say";
49728
+ if (pass.answer === "yes") {
49729
+ const roles = pass.roles ?? [];
49730
+ return roles.length === 0 ? "A pass stands: yes" : `A pass stands: yes, from ${roles.join(", ")}`;
49731
+ }
49732
+ if (pass.answer === "no")
49733
+ return "A pass stands: no";
49734
+ return "A pass stands: not known";
49735
+ }
49736
+ function readingLines(result, brief, indent = " ") {
49737
+ const observed = result.observed;
49738
+ if (observed === "")
49739
+ return [`${indent}The role recorded no reading.`];
49740
+ const cut = brief && result.commit_stands?.answer !== "at_basis";
49741
+ if (cut && observed.length > BRIEF_READING_CHARACTERS) {
49742
+ return [
49743
+ `${indent}Reading: ${observed.slice(0, BRIEF_READING_CHARACTERS)}\u2026 (result ${result.id})`
49744
+ ];
49745
+ }
49746
+ return [`${indent}Reading: ${observed}`];
49747
+ }
49748
+ function resultLines(check, result, brief) {
49749
+ const lines = [
49750
+ ` - ${result.verdict} by ${result.role} at ${result.commit_sha}. ${commitStandsText(result.commit_stands)}. ${checkWordsText(check, result)}. Recorded ${result.created_at}. Result ${result.id}.`
49751
+ ];
49752
+ const retracted = result.retracted;
49753
+ if (retracted !== undefined) {
49754
+ lines.push(` Retracted by ${actorText(retracted.actor)} at ${retracted.created_at}. The reason: ${retracted.reason}`);
49755
+ }
49756
+ return [...lines, ...readingLines(result, brief)];
49757
+ }
49758
+ function ciCheckLines(check, ci, brief) {
49759
+ const passStandsLine = ` ${passStandsText(check.pass_stands)}.`;
49760
+ const pullRequestLine = ` Pull request line: ${ci.line}`;
49761
+ const derived = check.results?.[0];
49762
+ if (derived === undefined) {
49763
+ return [
49764
+ `- ${check.block_id} (${check.when}): no result: ${ci.detail} ${check.text}`,
49765
+ passStandsLine,
49766
+ pullRequestLine
49767
+ ];
49768
+ }
49769
+ const stands = commitStandsText(derived.commit_stands);
49770
+ return [
49771
+ `- ${check.block_id} (${check.when}): ${derived.verdict} at ${derived.commit_sha} by ${derived.role} (CI run ${ci.run}, ${ci.case}), ${stands.charAt(0).toLowerCase()}${stands.slice(1)}. ${check.text}`,
49772
+ passStandsLine,
49773
+ pullRequestLine,
49774
+ ...readingLines(derived, brief, " ")
49775
+ ];
49776
+ }
49777
+ function checkLines(check, brief) {
49778
+ if (check.ci !== undefined)
49779
+ return ciCheckLines(check, check.ci, brief);
49780
+ const bases = check.compared_with ?? [];
49781
+ const reason = check.compared_nothing;
49782
+ const compared = bases.length > 0 ? `Compared with ${bases.map(basisText).join(", ")}` : reason === undefined ? "Compared with nothing, and this Dispatch server does not say why" : `Compared with nothing: ${COMPARISON_REASONS[reason]}`;
49783
+ const results = check.results ?? [];
49784
+ return [
49785
+ `- ${check.block_id} (${check.when}). ${compared}. ${passStandsText(check.pass_stands)}.`,
49786
+ ` The check's words: ${check.text}`,
49787
+ ...results.length === 0 ? [" No result is recorded for this check."] : results.flatMap((result) => resultLines(check, result, brief))
49788
+ ];
49789
+ }
49790
+ function formatCheckResults(results, brief = false) {
49791
+ if (results.verification_artifact_id === "") {
49792
+ return `${results.issue} has no Verification document, so it has no checks. Write one (verification.md) with a check block per thing that must be proved.`;
49793
+ }
49794
+ const checks = results.checks ?? [];
49795
+ if (checks.length === 0) {
49796
+ return `${results.issue}'s Verification document holds no check blocks.`;
49797
+ }
49798
+ const blocks = checks.map((check) => checkLines(check, brief).join(`
49799
+ `));
49800
+ return [`Checks of ${results.issue}:`, ...blocks].join(`
49801
+
49802
+ `);
49803
+ }
49804
+ function dryRunAsksDispatch(tool, args) {
49805
+ return tool === "dispatch_result" && args["retract"] === undefined;
49806
+ }
49807
+ async function resultCommand(context) {
49808
+ const { args, client, actor } = context;
49809
+ const retract = optionalString(args, "retract");
49810
+ if (retract !== undefined) {
49811
+ const retraction = await client.retractResult(retract, {
49812
+ actor,
49813
+ reason: stringArg(args, "reason")
49814
+ });
49761
49815
  return {
49762
- text: follows === undefined ? `Replied to message ${inReplyTo} with message ${reply.id}. ${readBack}` : `Replied to message ${inReplyTo} with message ${reply.id}, a follow-up threaded ` + `under your reply ${follows}. ${readBack}`,
49816
+ text: `Retracted result ${retraction.result_id}. ${actorText(retraction.actor)} retracted it at ${retraction.created_at}. The reason: ${retraction.reason}
49817
+
49818
+ The result stays readable, and it proves nothing from now on. Record a new result where the check still needs one.`,
49763
49819
  details: {
49764
- message: reply.id,
49765
- in_reply_to: inReplyTo,
49766
- posted: true,
49767
- ...follows === undefined ? {} : { follows }
49820
+ result: retraction.result_id,
49821
+ reason: retraction.reason,
49822
+ created_at: retraction.created_at
49768
49823
  }
49769
49824
  };
49770
49825
  }
49771
- const issueKey = issue();
49772
- const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
49773
- const message = await client.message(issueKey, {
49774
- body,
49775
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
49776
- ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
49777
- actor
49778
- });
49779
- const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
49780
- const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
49826
+ const issue = stringArg(args, "issue");
49827
+ const optional = {
49828
+ ...defined("surface", optionalString(args, "surface")),
49829
+ ...defined("run", optionalString(args, "run")),
49830
+ ...defined("observed", optionalString(args, "observed")),
49831
+ ...defined("negative_control", optionalString(args, "negative_control")),
49832
+ ...defined("failed", optionalNumber(args, "failed")),
49833
+ ...defined("skipped", optionalNumber(args, "skipped")),
49834
+ ...defined("excluded", optionalNumber(args, "excluded")),
49835
+ ...defined("screenshots", optionalStringArray(args, "screenshots"))
49836
+ };
49837
+ const input = {
49838
+ actor,
49839
+ check: stringArg(args, "check"),
49840
+ role: stringArg(args, "role"),
49841
+ verdict: stringArg(args, "verdict"),
49842
+ commit: stringArg(args, "commit"),
49843
+ ...optional
49844
+ };
49845
+ if (context.input.dryRun === true) {
49846
+ const dry = await client.dryRunResult(issue, input);
49847
+ return {
49848
+ text: `Nothing was recorded: this is a dry run.
49849
+
49850
+ Pull request body line:
49851
+ ${dry.line}`,
49852
+ details: { issue, check: input.check, verdict: input.verdict, line: dry.line }
49853
+ };
49854
+ }
49855
+ let recorded;
49856
+ try {
49857
+ recorded = await client.recordResult(issue, input);
49858
+ } catch (error) {
49859
+ if (dispatchAnswered(error, 409) && error.code === "CHECK_CONTENDED") {
49860
+ throw refusalWithCode(error, "the check moved twice while this result was being written, and nothing was recorded: run the same dispatch result command again");
49861
+ }
49862
+ throw error;
49863
+ }
49781
49864
  return {
49782
- text: [
49783
- `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
49784
- ...adviceLines
49785
- ].join(`
49786
- `),
49865
+ text: `Recorded ${recorded.result.verdict} for check ${recorded.result.check_block_id} of ${recorded.result.check_issue_key} at ${recorded.result.commit_sha}, as ${recorded.result.role}.
49866
+
49867
+ Pull request body line:
49868
+ ${recorded.line}`,
49787
49869
  details: {
49788
- issue: issueKey,
49789
- message: message.id,
49790
- ...message.advice === undefined ? {} : { advice: message.advice }
49870
+ issue,
49871
+ result: recorded.result.id,
49872
+ check: recorded.result.check_block_id,
49873
+ verdict: recorded.result.verdict,
49874
+ line: recorded.line
49791
49875
  }
49792
49876
  };
49793
49877
  }
49794
- function arrivalText(attempt) {
49795
- if (attempt === undefined)
49796
- return "Dispatch recorded no delivery attempt for it";
49797
- if (attempt.state === "failed") {
49798
- return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
49799
- }
49800
- if (attempt.state === "pending")
49801
- return "its delivery is still on its way";
49802
- if (attempt.state === "queued") {
49803
- return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
49804
- }
49805
- return `it reached that session as ${attempt.delivery}`;
49806
- }
49807
- async function sendToAgentCommand(context) {
49878
+ async function resultsCommand(context) {
49808
49879
  const { args, client } = context;
49809
- const session = stringArg(args, "session");
49810
- const inReplyTo = optionalString(args, "in_reply_to");
49811
- const message = await client.agentMessage(session, {
49812
- body: stringArg(args, "body"),
49813
- delivery: stringArg(args, "delivery"),
49814
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
49815
- });
49816
- const attempt = message.deliveries?.at(-1);
49817
- const readBack = conversationReadBack(message.id);
49818
- const arrival = arrivalText(attempt);
49880
+ const issue = stringArg(args, "issue");
49881
+ const at = optionalString(args, "at");
49882
+ const brief = optionalBoolean(args, "brief") === true;
49883
+ const results = await client.issueResults(issue, at);
49884
+ const checks = results.checks ?? [];
49819
49885
  return {
49820
- text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
49886
+ text: formatCheckResults(results, brief),
49821
49887
  details: {
49822
- session,
49823
- message: message.id,
49824
- ...attempt === undefined ? {} : { delivery: attempt.state },
49825
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
49888
+ issue,
49889
+ checks: checks.length,
49890
+ results: checks.reduce((total, check) => total + (check.results ?? []).length, 0)
49826
49891
  }
49827
49892
  };
49828
49893
  }
49829
49894
 
49830
- // ../envoy-client/src/dispatch-commands/documents.ts
49831
- import { resolve as resolvePath2 } from "path";
49832
-
49833
- // ../contracts/src/go-blank.ts
49834
- var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
49835
-
49836
- // ../envoy-client/src/dispatch-commands/documents.ts
49837
- async function blockAsks(client, resolved, state) {
49838
- const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
49839
- return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
49895
+ // ../envoy-client/src/dispatch-commands/render-graph.ts
49896
+ function referenceLines(read) {
49897
+ if (typeof read === "string")
49898
+ return [`- ${read}`];
49899
+ const edges = read.edges ?? [];
49900
+ if (edges.length === 0)
49901
+ return ["- none"];
49902
+ return edges.map(edgeLine);
49840
49903
  }
49841
- async function readUploadedFile(client, artifact, details, requested, owner, shown) {
49842
- const versions = artifact.versions ?? [];
49843
- const latest = Math.max(0, ...versions.map((version) => version.number));
49844
- const number = requested ?? latest;
49845
- const of = number === latest ? "" : ` of ${latest}`;
49846
- const bytesRoute = `GET /api/v1/artifacts/${artifact.id}/versions/${number} serves its bytes.`;
49847
- const tooLarge = (mime, bytes) => ({
49848
- text: `${oversizePictureText(artifact.name, bytes)}, so dispatch doc-read cannot show this ` + `uploaded ${mime} picture (version ${number}${of}). ${bytesRoute}`,
49849
- details
49850
- });
49851
- const stated = versions.find((version) => version.number === number);
49852
- if (artifact.kind === "image" && stated?.size !== undefined && stated.size > PICTURE_SHOWN_MAX_BYTES) {
49853
- return tooLarge(stated.mime ?? "image", stated.size);
49854
- }
49855
- const file = await client.fileVersion(artifact.id, number);
49856
- const size = `${file.bytes.length.toLocaleString("en-US")} bytes`;
49857
- if (artifact.kind === "image") {
49858
- const image = toolImage(file.bytes);
49859
- if (image !== undefined) {
49860
- const address = `dispatch://${owner}/artifact/${artifact.slug}@v${number}`;
49861
- shown?.add(address);
49862
- return {
49863
- text: `Picture ${artifact.name}: ${image.mimeType}, version ${number}${of}, ${size}.
49864
- ` + shownPictureLine(1, address, artifact.name, image.mimeType, file.bytes.length),
49865
- details,
49866
- images: [image]
49867
- };
49868
- }
49869
- if (sniffPictureType(file.bytes) !== undefined)
49870
- return tooLarge(file.mime, file.bytes.length);
49904
+ function isItemKind(kind) {
49905
+ return ITEM_KINDS.some((item) => item === kind);
49906
+ }
49907
+ function edgeLine(edge) {
49908
+ const { node } = edge;
49909
+ const excerpt = edge.excerpt === undefined ? "" : `${textHead(edge.excerpt.text)} \xB7 `;
49910
+ const block = edge.block === undefined ? "" : ` (block ${edge.block.ref ?? edge.block.id})`;
49911
+ const parent = node.parent ?? undefined;
49912
+ const item = node.kind === "block" && node.document === undefined && isItemKind(parent?.kind) ? parent : undefined;
49913
+ const source = item === undefined ? `${node.kind} ${node.ref ?? node.id}` : `${item.kind} ${item.ref ?? item.id} block ${node.block_id ?? node.id}`;
49914
+ return `- ${edge.kind} ${source} (${excerpt}${edge.created_at})${block}`;
49915
+ }
49916
+ function unavailableReason(error) {
49917
+ return dispatchAnswered(error, 404) ? "unavailable" : `unavailable: ${messageFor(error)}`;
49918
+ }
49919
+ async function graphReferences(client, query) {
49920
+ try {
49921
+ return await client.getReferences(query);
49922
+ } catch (error) {
49923
+ return unavailableReason(error);
49871
49924
  }
49872
- let text;
49925
+ }
49926
+ async function issueReferencesOrUnavailable(client, key) {
49873
49927
  try {
49874
- text = new TextDecoder("utf-8", { fatal: true }).decode(file.bytes);
49875
- } catch {
49876
- return {
49877
- text: `${artifact.name} is an uploaded ${file.mime} file (version ${number}${of}, ${size}) that is not ` + `UTF-8 text, so dispatch doc-read cannot show it. ${bytesRoute}`,
49878
- details
49879
- };
49928
+ return await client.getIssueReferences(key);
49929
+ } catch (error) {
49930
+ return unavailableReason(error);
49880
49931
  }
49881
- return {
49882
- text: `File ${artifact.name}: ${file.mime}, version ${number}${of}, ${size}.
49883
-
49884
- ${text}`,
49885
- details
49886
- };
49887
49932
  }
49888
- var BLOCK_OPENING_CHARS = 60;
49889
- async function listDocumentBlocks(client, artifact) {
49890
- const live = await liveBlocks(client, artifact);
49891
- const { bytes, blocks } = live;
49892
- const decoder = new TextDecoder;
49893
- const lines = [
49894
- `Blocks of ${artifact.name}, in document order, each indented under the block holding it: id, type, (token; anchored comments and asks), opening words, then a typed block's serves and needs. A table lists its rows by the index delete_row takes and its cells by the row and the column delete_column takes.`
49895
- ];
49896
- const holders = [];
49897
- for (const block of blocks) {
49898
- while (holders.length > 0 && block.from >= (holders.at(-1)?.to ?? 0))
49899
- holders.pop();
49900
- const indent = " ".repeat(holders.length);
49901
- const flat = decoder.decode(bytes.subarray(block.from, block.to)).replace(/\s+/g, " ").trim();
49902
- const points = Array.from(flat);
49903
- const opening = points.length > BLOCK_OPENING_CHARS ? `${points.slice(0, BLOCK_OPENING_CHARS).join("")}\u2026` : flat;
49904
- const { comments, asks } = block.references;
49905
- lines.push(`${indent}${block.id} ${block.type} (${block.token ?? "no token"}; ${comments} comment${comments === 1 ? "" : "s"}, ${asks} ask${asks === 1 ? "" : "s"}): ${opening}`);
49906
- for (const attribute of block.attributes ?? []) {
49907
- if (attribute.kind === "block[]" && attribute.value !== "") {
49908
- lines.push(`${indent} ${attribute.name}: ${attribute.value}`);
49909
- }
49910
- }
49911
- if (block.type === "table") {
49912
- if (block.table === undefined) {
49913
- lines.push(`${indent} This Dispatch does not report table rows yet, so no row or column index is listed.`);
49914
- } else {
49915
- for (const row of block.table.rows ?? []) {
49916
- lines.push(`${indent} row ${row.index}, ${row.id === "" ? "no id yet" : `id ${row.id}`}`);
49917
- for (const cell of row.cells ?? []) {
49918
- const under = cell.header === "" ? "" : `, under ${JSON.stringify(cell.header)}`;
49919
- lines.push(`${indent} row ${cell.row} column ${cell.column}, ${cell.id === "" ? "no id yet" : `id ${cell.id}`}${under}: ${cell.text === "" ? "(empty)" : cell.text}`);
49920
- }
49921
- }
49922
- }
49923
- }
49924
- holders.push(block);
49933
+ async function issueCoverageOrReason(client, key) {
49934
+ try {
49935
+ return await client.issueCoverage(key);
49936
+ } catch (error) {
49937
+ return unavailableReason(error);
49925
49938
  }
49926
- return { text: lines.join(`
49927
- `), token: live.token, version: live.version };
49928
49939
  }
49929
- async function refuseOpenDecisionBlocks(client, tool, resolved) {
49930
- const artifact = resolved.artifact;
49931
- const latest = artifact.approval?.latest_version;
49932
- if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
49933
- return;
49934
- const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
49935
- if (blocks.length === 0)
49936
- return;
49937
- const [documentAsks, version] = await Promise.all([
49938
- blockAsks(client, resolved),
49939
- client.docRead(artifact.id, latest)
49940
+ async function graphSections(client, ref) {
49941
+ const [incoming, outgoing] = await Promise.all([
49942
+ graphReferences(client, { to: ref }),
49943
+ graphReferences(client, { from: ref })
49940
49944
  ]);
49941
- const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
49942
- const lines = version.markdown.split(`
49943
- `);
49944
- const stillOpen = (named, state) => state === "answered" ? `${named}, answered but still open in version ${latest}: it settles into a version on its own in about two seconds; wait for that version` : `${named}, ${state} but still open in version ${latest}: write the decision into the text with dispatch doc-edit, which writes a version that carries it`;
49945
- const open = blocks.flatMap((block) => {
49946
- const ask = asks.get(block.id);
49947
- const id = typedBlockIdAttribute(block.id);
49948
- const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
49949
- const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
49950
- const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
49951
- if (states.length === 0)
49952
- return [`${named}, which version ${latest} does not hold yet`];
49953
- if (!states.includes("open") && states.some((state) => state !== undefined))
49954
- return [];
49955
- if (ask !== undefined)
49956
- return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
49957
- const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
49958
- const sourceId = attribute("copied_from");
49959
- const document = attribute("copied_from_document");
49960
- if (sourceId === undefined || document === undefined) {
49961
- return [`${named}, whose ask Dispatch has not opened yet`];
49962
- }
49963
- const source = parseDispatchRef(document);
49964
- const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
49965
- const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
49966
- return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
49967
- });
49968
- if (open.length === 0)
49969
- return;
49970
- const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
49971
- throw new Error([
49972
- `dispatch ${commandName(tool)} was not called: ${artifact.name} (version ${latest}) has ${count}. Answering one writes a new version, which would move this request to that version and leave it waiting on you.`,
49973
- ...open.map((line) => `- ${line}`),
49974
- "Do not request approval over an open block, even when a human asked for it. Tell the human which block is open and ask them to answer it or to waive it. Once it is answered, it settles into a version on its own in about two seconds. When the human approved an earlier version and their answer is the whole change since it, Dispatch carries the approval to the new version in their name: request nothing. When the answer changes design text outside the block, rewrite that text (never to restate the answer), then request approval again once the human has agreed to every point in the new version, with a one-sentence --summary naming what changed since the earlier approval. On a document nobody has approved, wait for that version, then request. If they waive it, close the block with dispatch resolve-ask (--kind resolved, their words as the --reason), write their decision into the text with dispatch doc-edit, then request approval again once the human has agreed to every point in the new version. The call opens the request, or hands an open one back to the human."
49975
- ].join(`
49976
- `));
49945
+ return graphSectionLines(incoming, outgoing);
49977
49946
  }
49978
- async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
49979
- const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
49980
- if (removing.length === 0)
49981
- return;
49982
- const artifact = resolved.artifact;
49983
- const blocks = await client.artifactBlocks(artifact.id);
49984
- const askBlocks = blocks.filter((block) => block.type === "ask");
49985
- const removed = new Set;
49986
- for (const operation of removing) {
49987
- const target = blocks.find((block) => block.id === operation.block);
49988
- if (target === undefined)
49989
- continue;
49990
- for (const block of askBlocks) {
49991
- if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
49992
- removed.add(block.id);
49993
- }
49994
- }
49995
- }
49996
- if (removed.size === 0)
49947
+ function graphSectionLines(incoming, outgoing) {
49948
+ return [
49949
+ ...typeof incoming === "string" ? [] : nodeLine(incoming.node),
49950
+ "Referenced by:",
49951
+ ...referenceLines(incoming),
49952
+ "Links:",
49953
+ ...referenceLines(outgoing)
49954
+ ];
49955
+ }
49956
+ function nodeLine(node) {
49957
+ if (node.made_by === undefined)
49958
+ return [];
49959
+ const fact = (by, time) => `${by == null || by.length === 0 ? "nobody recorded" : by.map(actorText).join(", ")}${time == null ? "" : ` at ${time}`}`;
49960
+ const made = fact(node.made_by, node.made_at);
49961
+ const changed = fact(node.changed_by, node.changed_at);
49962
+ const { parent } = node;
49963
+ const partOf = parent == null ? "" : ` \xB7 part of ${parent.ref ?? `${parent.kind} ${parent.id}`}${node.parent_version == null ? "" : ` (${isItemKind(parent.kind) ? "revision" : "version"} ${node.parent_version})`}`;
49964
+ return [
49965
+ `Node: ${node.kind} ${node.ref ?? node.id} \xB7 made by ${made} \xB7 changed by ${changed}${partOf}`
49966
+ ];
49967
+ }
49968
+ function blockLines(node, ref, typed, noun = "Block") {
49969
+ const unit = ref.item === undefined ? "version" : "revision";
49970
+ const blockID = node.block_id ?? ref.block;
49971
+ const head = ref.item === undefined ? [
49972
+ `Block: ${blockID}`,
49973
+ ...typed === undefined ? [] : [`Type: ${typed.type}`],
49974
+ `Document: ${node.document ?? ref.document}`,
49975
+ ...(typed?.attributes ?? []).map((attribute) => `${attribute.name}: ${attribute.value === "" ? "(empty)" : attribute.value}`),
49976
+ ...node.changed_version === undefined ? [] : [`Changed in version: ${node.changed_version}`],
49977
+ ...node.text === undefined ? [] : ["Text:", node.text]
49978
+ ] : [
49979
+ `${noun} ${blockID} of ${ref.item.kind} ${ref.item.id}${node.changed_version === undefined ? "" : ` (changed in revision ${node.changed_version})`}:`,
49980
+ ...node.text === undefined ? [] : [node.text]
49981
+ ];
49982
+ const { pin } = node;
49983
+ if (pin === undefined)
49984
+ return head;
49985
+ const state = pin.state === "unchanged" ? `Unchanged since ${unit} ${pin.version}.` : pin.state === "changed" ? `Changed since ${unit} ${pin.version}; last changed in ${unit} ${node.changed_version}.` : `Removed in ${unit} ${pin.removed_version}.`;
49986
+ return [
49987
+ ...head,
49988
+ `Pinned to ${unit}: ${pin.version}`,
49989
+ state,
49990
+ `Text at ${unit} ${pin.version}:`,
49991
+ pin.text
49992
+ ];
49993
+ }
49994
+ async function typedBlockOf(client, ref) {
49995
+ if (ref.item !== undefined || ref.block === undefined)
49997
49996
  return;
49998
- const asks = await blockAsks(client, resolved, "open");
49999
- const open = asks.filter((ask) => removed.has(ask.block_id));
50000
- if (open.length === 0)
49997
+ try {
49998
+ const blocks = ref.owner.kind === "project" ? await client.projectArtifactBlocks(ref.owner.project, ref.id) : await client.issueArtifactBlocks(ref.owner.issue, ref.id);
49999
+ return blocks.find((block) => block.id === ref.block);
50000
+ } catch {
50001
50001
  return;
50002
- const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
50003
- throw new Error([
50004
- `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
50005
- ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
50006
- "A decision block leaves the document once its ask is answered or resolved. Until then, reword it with replace, relocate it with move, or change its question, options, urgency or multiple with dispatch edit-ask if you asked it; each keeps it."
50007
- ].join(`
50008
- `));
50002
+ }
50009
50003
  }
50010
- async function docEditCommand(context) {
50011
- const { args, client, actor, input, linkBase, documentOwner, resolveDocument } = context;
50012
- const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
50013
- const ops = args.ops;
50014
- const summary = optionalString(args, "summary");
50015
- const { precondition: rawPrecondition } = args;
50016
- const precondition = rawPrecondition;
50017
- await refuseRemovingOpenDecisionBlocks(client, input.tool, resolved, ops);
50018
- const edited = await client.docEdit(resolved.artifact.id, {
50019
- ops,
50020
- ...summary === undefined ? {} : { summary },
50021
- ...precondition === undefined ? {} : { precondition },
50022
- actor
50023
- });
50024
- const retyped = ops.filter((operation) => operation.op === "retype").length;
50025
- const versionText = edited.version === null ? "no new version" : `version ${edited.version.number}`;
50026
- const retypedText = retyped === 0 ? "" : `; retyped ${retyped} block${retyped === 1 ? "" : "s"}`;
50027
- const nothingChanged = edited.changed === false;
50028
- const head = nothingChanged ? `Applied ${edited.applied} ops${retypedText}; nothing changed (${versionText})` : `Applied ${edited.applied} ops${retypedText} (${versionText})`;
50029
- const unchangedOps = edited.unchanged_ops ?? [];
50030
- const unchangedText = unchangedOps.length === 0 ? "" : `; ${unchangedOps.length === 1 ? "operation" : "operations"} ${unchangedOps.join(", ")} changed nothing`;
50031
- const lostOps = edited.lost_ops;
50032
- const lostText = lostOps === undefined || lostOps !== null && lostOps.length === 0 ? "" : lostOps === null ? "; could not confirm this edit survived, because the live document is being reloaded or holds a tree too deep to read \u2014 re-read it" : `; ${versionText} carries text the live document no longer has: a concurrent change removed what ${lostOps.length === 1 ? "operation" : "operations"} ${lostOps.join(", ")} wrote \u2014 re-read the document`;
50033
- const applied = `${head}${unchangedText}${lostText}`;
50034
- const editAskText = ops.map((operation) => /^:{3,}ask\{.*\n([\s\S]*)/mu.exec(operation.markdown ?? operation.with ?? "")?.[1]).find((text) => text !== undefined) ?? resolved.issue?.title ?? "";
50035
- const checkLines = decisionBlockLines(edited.advice, {
50036
- project: resolved.artifact.project,
50037
- text: editAskText,
50038
- linkBase
50039
- });
50040
- const declinedLines = resolved.issue === undefined ? [] : declinedAskLines(edited.advice, resolved.issue.key, linkBase);
50041
- const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, resolvedTopic(resolved).label, edited.advice, {
50042
- isPlan: documentPlaysPlan(resolved.artifact)
50043
- }));
50044
- const written = edited.written;
50045
- const writtenLines = written === undefined || written === "" ? [] : [written];
50046
- const tokenTrailer = edited.token === undefined ? [] : [`Document token: ${edited.token}`];
50047
- return {
50048
- text: [
50049
- `${applied}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
50050
- ...checkLines,
50051
- ...declinedLines,
50052
- ...writtenLines,
50053
- ...tokenTrailer,
50054
- ...adviceLines
50055
- ].join(`
50056
- `),
50057
- details: writeResultDetails(resolved, {
50058
- applied: edited.applied,
50059
- ...edited.version === null ? {} : { version: edited.version.number },
50060
- ...nothingChanged ? { changed: false } : {},
50061
- ...lostOps === undefined ? {} : { lost_ops: lostOps },
50062
- ...edited.token === undefined ? {} : { token: edited.token },
50063
- ...edited.advice === undefined ? {} : { advice: edited.advice }
50064
- })
50065
- };
50004
+ function askPartNoun(ask, node, blockID) {
50005
+ if (ask.answer?.id === blockID)
50006
+ return "Answer";
50007
+ if ((ask.options ?? []).some((option) => option.id === blockID))
50008
+ return "Option";
50009
+ const placed = (ask.revision ?? 0) > 0 && (ask.options ?? []).every((option) => option.id !== undefined) && (ask.answer === null || ask.answer.id !== undefined);
50010
+ return placed && node.pin?.state !== "removed" ? "Question" : "Part";
50066
50011
  }
50067
- async function docReadCommand(context) {
50068
- const { args, client, ownerArguments, shown, documentOwner, resolveDocument } = context;
50069
- const { agentArtifact } = ownerArguments;
50070
- if (agentArtifact !== undefined) {
50071
- const artifact = await client.getAgentArtifact(agentArtifact.session, agentArtifact.slug);
50072
- if (optionalBoolean(args, "blocks") === true) {
50073
- throw new Error(`${artifact.name} is an uploaded ${artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
50074
- }
50075
- return readUploadedFile(client, artifact, { session: agentArtifact.session, artifact: artifact.slug }, optionalNumber(args, "version") ?? agentArtifact.version, `agent/${agentArtifact.session}`, shown);
50076
- }
50077
- const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
50078
- const resolved = await resolveDocument(documentOwner(), artifactReference);
50079
- const version = optionalNumber(args, "version") ?? ownerArguments.ref?.version;
50080
- if (optionalBoolean(args, "blocks") === true) {
50081
- if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
50082
- throw new Error(`${resolved.artifact.name} is an uploaded ${resolved.artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
50083
- }
50084
- const listed = await listDocumentBlocks(client, resolved.artifact);
50085
- const trailer = [
50086
- ...listed.token === undefined ? [] : [`Document token: ${listed.token}`],
50087
- `Document version: ${listed.version === null ? "none yet" : listed.version}`
50088
- ];
50089
- return {
50090
- text: `${listed.text}
50091
-
50092
- ${trailer.join(`
50093
- `)}`,
50094
- details: resolved.owner.kind === "project" ? {
50095
- project: resolved.artifact.project,
50096
- document: documentLabel(resolved.artifact.project, resolved.artifact.slug)
50097
- } : { issue: resolved.issue?.key }
50098
- };
50099
- }
50100
- if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
50101
- const { artifact } = resolved;
50102
- return readUploadedFile(client, artifact, resolved.owner.kind === "project" ? {
50103
- project: artifact.project,
50104
- document: documentLabel(artifact.project, artifact.slug)
50105
- } : { issue: resolved.issue?.key }, version, resolved.owner.kind === "project" ? resolved.owner.project : resolved.owner.issue, shown);
50106
- }
50107
- const documentPromise = client.docRead(resolved.artifact.id, version);
50108
- const threadsPromise = openAnchoredThreads(client, resolved);
50109
- const threadsResultPromise = threadsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
50110
- const document = await documentPromise;
50111
- const threadsResult = await threadsResultPromise;
50112
- if (threadsResult.status === "rejected")
50113
- throw threadsResult.reason;
50114
- const threads = threadsResult.value;
50115
- const approval = approvalLine(resolved.artifact, typeof resolved.issue?.closed_at === "string");
50116
- const trailer = [
50117
- ..."token" in document && document.token !== undefined ? [`Document token: ${document.token}`] : [],
50118
- ..."sha256" in document && document.sha256 !== undefined ? [`Content: sha256:${document.sha256}`] : [],
50119
- ...approval === undefined ? [] : [approval]
50120
- ];
50121
- return {
50122
- text: [
50123
- document.markdown,
50124
- ...trailer.length === 0 ? [] : [trailer.join(`
50125
- `)],
50126
- ...threads.length === 0 ? [] : ["Open anchored threads:", ...threads]
50127
- ].join(`
50128
50012
 
50129
- `),
50130
- details: resolved.owner.kind === "project" ? {
50131
- project: resolved.artifact.project,
50132
- document: `${resolved.artifact.project}/${resolved.artifact.slug}`
50133
- } : { issue: resolved.issue?.key }
50134
- };
50135
- }
50136
- async function requestApprovalCommand(context) {
50137
- const { args, client, actor, input, ownerArguments, documentOwner, resolveDocument } = context;
50138
- const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
50139
- const resolved = await resolveDocument(documentOwner(), artifactReference);
50140
- await refuseOpenDecisionBlocks(client, input.tool, resolved);
50141
- const includeVerification = optionalBoolean(args, "include_verification") === true;
50142
- const result = await client.requestApproval(resolved.artifact.id, {
50143
- actor,
50144
- summary: stringArg(args, "summary"),
50145
- ...includeVerification ? { include_verification: true } : {}
50146
- });
50147
- const gaps = result.coverage ?? [];
50148
- const coverageLines = result.coverage_unread ? [
50149
- `Coverage of ${resolved.artifact.name}: unread. Dispatch could not read what the spec's requirements lack, so no line here says there is no gap; the request is recorded either way. Read the coverage again with dispatch read --issue, and mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
50150
- ] : gaps.length === 0 ? [] : [
50151
- `Coverage of ${resolved.artifact.name}: ${gaps.map((gap) => `${gap}.`).join(" ")} Mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
50152
- ];
50153
- if (result.ask === null) {
50154
- return {
50155
- text: [
50156
- `${resolved.artifact.name} (document id ${resolved.artifact.id}) is already approved at version ${result.version} by ${result.approval.by?.id ?? "unknown"}; no new request was opened. A change outside the decision blocks after approval makes it stale, so request again only for such a version, once the human has agreed to every point in it, with a --summary naming what changed since version ${result.version}; the human's own answer to a decision block carries the approval when that answer is the whole change.`,
50157
- ...coverageLines
50158
- ].join(`
50159
- `),
50160
- details: {
50161
- ...resolved.owner.kind === "project" ? documentResultDetails(resolved.artifact) : { issue: resolved.issue?.key },
50162
- artifact: resolved.artifact.id,
50163
- version: result.version
50164
- }
50165
- };
50166
- }
50167
- const details = await followedAskDetails(client, result.ask, resolved.artifact);
50168
- const outcome = result.recorded ? `Approval requested for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}).` : `The approval request for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}) already waits on the human, so this call changed nothing: nothing since it last reached the human (a newer version, a human's reply in its thread, or your progress note) left it waiting on you.`;
50169
- const waitsOn = waitsOnPerson(result.ask);
50170
- return {
50171
- text: [
50172
- `${outcome}${waitsOn === undefined ? "" : ` It waits on ${waitsOn}.`} The human's Inbox asks: ${JSON.stringify(result.ask.question)}. The answer arrives as artifact.approved or artifact.changes_requested. An edit before the answer moves this request to the new version and leaves it waiting on you, and a change outside the decision blocks after approval makes the approval stale: either way, request again for the new version once the human has agreed to every point in it, which hands this request back or opens a new one, with a --summary naming what changed since the earlier approval. The human's own answer to a decision block carries the approval when that answer is the whole change since the approved version, and answers an open request Approve in their name: request nothing then.`,
50173
- ...coverageLines
50174
- ].join(`
50175
- `),
50176
- details: { ...details, artifact: resolved.artifact.id, version: result.version }
50177
- };
50178
- }
50179
- async function planApproveCommand(context) {
50180
- const { args, client, actor, documentOwner, resolveDocument } = context;
50181
- const planOwner = documentOwner();
50182
- const named = optionalString(args, "artifact");
50183
- const byRole = named === undefined && planOwner.kind === "issue" ? (await client.getIssue(planOwner.issue)).plan_artifact_id ?? "" : "";
50184
- const resolved = await resolveDocument(planOwner, named ?? (byRole || "plan.md"));
50185
- const version = numberArg(args, "version");
50186
- const review = await client.planApprove(resolved.artifact.id, { actor, version });
50187
- return {
50188
- text: `The plan review approved ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${review.version}; no human is asked to approve a plan. A later plan version makes this approval stale: run the review again and record it the same way.`,
50189
- details: {
50190
- issue: resolved.issue?.key,
50191
- artifact: resolved.artifact.id,
50192
- version: review.version
50193
- }
50194
- };
50195
- }
50196
- function artifactUnderName(artifacts, name) {
50197
- const written = name.trim();
50198
- return artifacts.find((held) => held.slug === written) ?? artifacts.find((held) => held.name === written);
50199
- }
50200
- function artifactNameExistsProblem(held, owner) {
50201
- const versions = held.versions ?? [];
50202
- const newest = versions[versions.length - 1];
50203
- if (newest === undefined) {
50204
- return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}), which has no version yet and which ${actorText(held.created_by)} created. ${ARTIFACT_NAME_EXISTS_RULE}`;
50205
- }
50206
- const authors = (newest.authors ?? []).map(actorText);
50207
- const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
50208
- return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${ARTIFACT_NAME_EXISTS_RULE}`;
50209
- }
50210
- var STORED_LINE_QUOTED = 200;
50211
- function quotedStoredLine(line) {
50212
- if (line.length <= STORED_LINE_QUOTED)
50213
- return JSON.stringify(line);
50214
- const head = JSON.stringify(line.slice(0, STORED_LINE_QUOTED));
50215
- return `${head} (cut after ${STORED_LINE_QUOTED} of its ${line.length} characters)`;
50216
- }
50217
- function firstStoredDifference(given, stored) {
50218
- const written = given.split(`
50219
- `);
50220
- const holds = stored.split(`
50221
- `);
50222
- for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
50223
- const wrote = written[line];
50224
- const held = holds[line];
50225
- if (wrote === held)
50226
- continue;
50227
- if (wrote === undefined && held !== undefined) {
50228
- return `the store writes a line ${line + 1}, ${quotedStoredLine(held)}`;
50229
- }
50230
- if (held === undefined && wrote !== undefined) {
50231
- return `the store drops line ${line + 1}, ${quotedStoredLine(wrote)}`;
50232
- }
50233
- if (wrote !== undefined && held !== undefined) {
50234
- return `line ${line + 1} reads ${quotedStoredLine(wrote)} and is stored as ${quotedStoredLine(held)}`;
50235
- }
50236
- }
50237
- return "the stored text differs from the text given";
50238
- }
50239
- var STORED_TEXT_PRINTED = 2000;
50240
- function storedTextPrinted(stored) {
50241
- if (stored.length <= STORED_TEXT_PRINTED)
50242
- return { text: stored, cut: "" };
50243
- const head = stored.slice(0, STORED_TEXT_PRINTED);
50244
- const lastLineFeed = head.lastIndexOf(`
50245
- `);
50246
- const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
50247
- return {
50248
- text,
50249
- cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
50250
- };
50251
- }
50252
- function storedTextProblem(given, stored, name) {
50253
- const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
50254
- const printed = storedTextPrinted(stored);
50013
+ // ../envoy-client/src/dispatch-commands/render-item.ts
50014
+ function askSummary({ ask, replies, answers }, askRef, pictures, incoming, outgoing) {
50015
+ const answer = ask.answer;
50016
+ const earlierAnswers = (answers ?? []).slice(0, -1);
50017
+ const parts = askPartEdges(ask, incoming);
50018
+ const partRef = (id) => `${askRef}#b-${encodeBlockId(id)}`;
50019
+ const chain = (replies ?? []).flatMap((reply) => [
50020
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
50021
+ `Body: ${reply.body}`
50022
+ ]);
50023
+ const resolutionWords = dispatchWordsText(ask.resolution?.dispatch_words);
50255
50024
  return [
50256
- `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
50257
- ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
50258
- `${printed.cut}
50259
- --- the text Dispatch stores ---
50260
- ${printed.text}`,
50261
- "--- end of the text Dispatch stores ---"
50262
- ].join("");
50263
- }
50264
- function storedTextCheckFailed(error, name) {
50265
- 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)}.`;
50266
- if (!dispatchAnswered(error, 413)) {
50267
- return `${failure} Send the upload again once that call is answered.`;
50268
- }
50269
- const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
50270
- 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}`;
50271
- }
50272
- function roundTripRouteAbsent(error) {
50273
- return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
50274
- }
50275
- function withoutFinalLineFeed(text) {
50276
- return text.endsWith(`
50277
- `) ? text.slice(0, -1) : text;
50278
- }
50279
- async function artifactCommand(context) {
50280
- const { args, client, actor, input, documentOwner, issue } = context;
50281
- const summary = optionalString(args, "summary");
50282
- const name = stringArg(args, "name");
50283
- const content = optionalString(args, "content");
50284
- const path = optionalString(args, "path");
50285
- const options = { name, ...summary === undefined ? {} : { summary }, actor };
50286
- const artifactOwner = documentOwner();
50287
- const blank = content === undefined || goBlankPattern.test(content);
50288
- if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
50289
- const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
50290
- if (held !== undefined) {
50291
- throw new ToolInputError(input.tool, [
50292
- artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`)
50293
- ]);
50294
- }
50295
- }
50296
- if (!blank) {
50297
- let stored;
50298
- try {
50299
- stored = await client.markdownRoundTrip(content);
50300
- } catch (error) {
50301
- if (!roundTripRouteAbsent(error)) {
50302
- throw new Error(storedTextCheckFailed(error, name), { cause: error });
50303
- }
50304
- }
50305
- if (stored !== undefined && withoutFinalLineFeed(stored) !== withoutFinalLineFeed(content)) {
50306
- throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
50307
- }
50308
- }
50309
- const artifactInput = path !== undefined ? {
50310
- ...options,
50311
- file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
50312
- type: Bun.file(resolvePath2(input.cwd, path)).type
50313
- })
50314
- } : content !== undefined ? { ...options, content } : options;
50315
- const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
50316
- const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
50317
- const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
50318
- const adviceLines = renderAdvice(input.tool, uploadOwner.label, result.advice, {
50319
- isPrimarySpec: result.artifact.primary || result.artifact.name === "spec.md",
50320
- isPlan: documentPlaysPlan(result.artifact)
50321
- });
50322
- return {
50323
- text: [
50324
- path === undefined && content === undefined ? `Made ${result.artifact.name} as an empty document (artifact slug ${result.artifact.slug}; ${artifactRef}). Write in it with dispatch doc-edit.${await notSubscribed(uploadOwner, input.subscriptions)}` : `Uploaded ${result.artifact.name} as version ${result.version.number} (artifact slug ${result.artifact.slug}; ${artifactRef})${await notSubscribed(uploadOwner, input.subscriptions)}`,
50325
- ...adviceLines
50326
- ].join(`
50327
- `),
50328
- details: artifactOwner.kind === "project" ? {
50329
- ...documentResultDetails(result.artifact),
50330
- version: result.version.number,
50331
- ...result.advice === undefined ? {} : { advice: result.advice }
50332
- } : {
50333
- issue: issue(),
50334
- artifact: result.artifact.id,
50335
- version: result.version.number,
50336
- ...result.advice === undefined ? {} : { advice: result.advice }
50337
- }
50338
- };
50339
- }
50340
-
50341
- // ../envoy-client/src/dispatch-commands/handoffs.ts
50342
- async function handoffWriteCommand(context) {
50343
- const { args, client, actor, input, issue } = context;
50344
- if (!input.sessionId?.trim()) {
50345
- throw new Error("host session id is required for dispatch handoff-write");
50346
- }
50347
- let recorded;
50348
- try {
50349
- recorded = await client.writeHandoff(issue(), stringArg(args, "phase"), {
50350
- actor,
50351
- body: stringArg(args, "body")
50352
- });
50353
- } catch (error) {
50354
- throw refusalWithCode(error);
50355
- }
50356
- return {
50357
- text: `Recorded the ${recorded.phase} handoff of ${recorded.issue_key}, version ${recorded.version} (id ${recorded.id})`,
50358
- details: {
50359
- issue: recorded.issue_key,
50360
- phase: recorded.phase,
50361
- version: recorded.version,
50362
- handoff: recorded.id
50363
- }
50364
- };
50025
+ `Question: ${ask.question}`,
50026
+ ...anchorLines(ask),
50027
+ "Options:",
50028
+ ...(ask.options ?? []).length === 0 ? ["- none"] : (ask.options ?? []).flatMap((option) => [
50029
+ `- ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}${option.id === undefined ? "" : ` (${partRef(option.id)})`}`,
50030
+ ...partReferenceLines(parts.at, option.id)
50031
+ ]),
50032
+ `State: ${ask.state}`,
50033
+ `Ask id: ${ask.id}`,
50034
+ "Answer:",
50035
+ ...answer === null ? ["- none"] : [
50036
+ `- By: ${actorActText(answer.user, answer.act)}`,
50037
+ `- Selected: ${(answer.selected ?? []).length === 0 ? "none" : (answer.selected ?? []).join(", ")}`,
50038
+ ...answer.text === null ? [] : [`- Text: ${answer.text}`],
50039
+ ...answer.id === undefined ? [] : [`- Reference: ${partRef(answer.id)}`],
50040
+ ...partReferenceLines(parts.at, answer.id)
50041
+ ],
50042
+ ...earlierAnswers.length === 0 ? [] : [
50043
+ "Earlier answers:",
50044
+ ...earlierAnswers.map((earlier) => `- ${earlier.at} \xB7 ${actorActText(earlier.user, earlier.act)} \xB7 ${askAnswerText(earlier)}`)
50045
+ ],
50046
+ ...ask.resolution === undefined ? [] : [
50047
+ "Resolution:",
50048
+ `- By: ${ask.resolution.actor.id}`,
50049
+ `- Kind: ${ask.resolution.kind}`,
50050
+ ...ask.resolution.reason === "" ? [] : [`- Reason: ${ask.resolution.reason}`],
50051
+ ...resolutionWords === undefined ? [] : [`- ${resolutionWords}`]
50052
+ ],
50053
+ "Replies:",
50054
+ ...chain.length === 0 ? ["- none"] : chain,
50055
+ ...pictures,
50056
+ ...graphSectionLines(parts.rest, outgoing)
50057
+ ].join(`
50058
+ `);
50365
50059
  }
50366
- async function handoffReadCommand(context) {
50367
- const { args, client, issue } = context;
50368
- const issueKey = issue();
50369
- const phase = stringArg(args, "phase");
50370
- const version = optionalNumber(args, "version");
50371
- let handoff;
50372
- try {
50373
- if (version === undefined) {
50374
- handoff = await client.latestHandoff(issueKey, phase);
50375
- } else {
50376
- const listed = await client.listHandoffs(issueKey);
50377
- const ofPhase = listed.filter((summary) => summary.phase === phase);
50378
- const match = ofPhase.find((summary) => summary.version === version);
50379
- if (match === undefined) {
50380
- const newest = Math.max(0, ...ofPhase.map((summary) => summary.version));
50381
- throw new Error(`HANDOFF_NOT_FOUND: issue ${issueKey} has no ${phase} handoff version ${version}; ${newest === 0 ? `it has no ${phase} handoff at all` : `its newest ${phase} handoff is version ${newest}`}`);
50382
- }
50383
- handoff = await client.handoff(match.id);
50060
+ function askPartEdges(ask, incoming) {
50061
+ const ids = new Set([...(ask.options ?? []).map((option) => option.id), ask.answer?.id].filter((id) => id !== undefined));
50062
+ const at = new Map;
50063
+ if (typeof incoming === "string" || ids.size === 0)
50064
+ return { at, rest: incoming };
50065
+ const rest = [];
50066
+ for (const edge of incoming.edges ?? []) {
50067
+ const part = edge.block?.block_id;
50068
+ if (part === undefined || !ids.has(part)) {
50069
+ rest.push(edge);
50070
+ continue;
50384
50071
  }
50385
- } catch (error) {
50386
- throw refusalWithCode(error);
50072
+ const { block: _block, ...atPart } = edge;
50073
+ const held = at.get(part);
50074
+ if (held === undefined)
50075
+ at.set(part, [atPart]);
50076
+ else
50077
+ held.push(atPart);
50387
50078
  }
50388
- return {
50389
- text: `${handoff.issue_key} ${handoff.phase} handoff, version ${handoff.version} (id ${handoff.id}), written by ${actorText(handoff.author)} at ${handoff.created_at}
50390
- ${handoff.body}`,
50391
- details: {
50392
- issue: handoff.issue_key,
50393
- phase: handoff.phase,
50394
- version: handoff.version,
50395
- handoff: handoff.id
50396
- }
50397
- };
50079
+ return { at, rest: { node: incoming.node, edges: rest } };
50398
50080
  }
50399
-
50400
- // ../envoy-client/src/dispatch-commands/render-issue.ts
50401
- function componentsLine(components) {
50402
- const ids = components.ids ?? [];
50403
- const unknown = components.unknown ?? [];
50404
- const inherited = components.inherited_from === null ? "" : ` (inherited from ${components.inherited_from})`;
50405
- const retired = unknown.length === 0 ? "" : ` (retired: ${unknown.join(", ")})`;
50406
- switch (components.mode) {
50407
- case "explicit":
50408
- return `Components: ${ids.length === 0 ? "none live" : ids.join(", ")}${inherited}${retired}`;
50409
- case "none":
50410
- return `Components: none \u2014 ${components.reason ?? ""}${inherited}`;
50411
- case "inherit":
50412
- return "Components: unassigned";
50413
- default:
50414
- return `Components: ${components.mode}${inherited}${retired}`;
50415
- }
50081
+ function partReferenceLines(at, id) {
50082
+ const edges = id === undefined ? undefined : at.get(id);
50083
+ if (edges === undefined || edges.length === 0)
50084
+ return [];
50085
+ return [" Referenced by:", ...edges.map((edge) => ` ${edgeLine(edge)}`)];
50416
50086
  }
50417
- function advanceText(advance) {
50418
- return `${advance.id} (${advance.inherited ? "inherited" : "own"})`;
50087
+ function openAskAge(ageSeconds) {
50088
+ const seconds = Math.max(0, Math.floor(ageSeconds));
50089
+ if (seconds < 60)
50090
+ return `${seconds}s`;
50091
+ const minutes = Math.floor(seconds / 60);
50092
+ if (minutes < 60)
50093
+ return `${minutes}m${seconds % 60 === 0 ? "" : ` ${seconds % 60}s`}`;
50094
+ const hours = Math.floor(minutes / 60);
50095
+ if (hours < 24)
50096
+ return `${hours}h${minutes % 60 === 0 ? "" : ` ${minutes % 60}m`}`;
50097
+ const days = Math.floor(hours / 24);
50098
+ return `${days}d${hours % 24 === 0 ? "" : ` ${hours % 24}h`}`;
50419
50099
  }
50420
- function advancesLine(issue) {
50421
- if (issue.advances === undefined) {
50422
- return "Advances: unknown (this Dispatch server predates priorities; upgrade it)";
50423
- }
50424
- const advances = issue.advances ?? [];
50425
- if (advances.length === 0)
50426
- return "Advances: no priority";
50427
- return `Advances: ${advances.map(advanceText).join(", ")}`;
50100
+ function namedPerson(person) {
50101
+ return person === undefined || person === "" ? undefined : person;
50428
50102
  }
50429
- function claimText(claim, agents, read = {}) {
50430
- const titles = agents?.titles;
50431
- const liveness = holderLiveness(claim, agents, read);
50432
- const holding = claimHolds(claim, titles, liveness);
50433
- const takeableAt = claimTakeableAt(liveness);
50434
- const unresponsive = liveness.holder_state === "unresponsive" && liveness.last_seen != null ? ` \xB7 unresponsive since ${liveness.last_seen}${takeableAt === null ? "" : `, takeable at ${takeableAt}`}` : " \xB7 unresponsive";
50435
- const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : holding === "unresponsive" ? unresponsive : "";
50436
- return `${actorLabel(claim.actor, titles)} since ${claim.at}${marker}`;
50103
+ function waitsOnPerson(ask) {
50104
+ return namedPerson(ask.waiting_on_person);
50437
50105
  }
50438
- function holderLiveness(claim, agents, read) {
50439
- if (claim.actor.kind !== "session")
50440
- return read;
50441
- const row = agents?.liveness.get(claim.actor.id);
50442
- if (row === undefined)
50443
- return read;
50444
- const holderState = read.holder_state ?? row.holder_state;
50445
- const lastSeen = read.last_seen ?? row.last_seen;
50446
- const takeableAt = read.takeable_at ?? row.takeable_at;
50447
- return {
50448
- ...holderState === undefined ? {} : { holder_state: holderState },
50449
- ...lastSeen === undefined ? {} : { last_seen: lastSeen },
50450
- ...takeableAt === undefined ? {} : { takeable_at: takeableAt }
50451
- };
50106
+ function openAskLine(ask, linkBase) {
50107
+ const priority = ask.priority === null ? "" : `P${ask.priority} \xB7 `;
50108
+ return `- ${openAskAge(ask.age_seconds)} \xB7 ${priority}${ownerTitle(ask.owner)} \xB7 asked of ${waitsOnPerson(ask) ?? "nobody"} \xB7 ${ask.question} \xB7 ${linkFor(ask.ref, linkBase)}`;
50452
50109
  }
50453
- async function liveAgents(client, needed) {
50454
- if (!needed) {
50455
- return;
50456
- }
50457
- try {
50458
- const agents = await client.listAgents();
50459
- return {
50460
- titles: new Map(agents.map((agent) => [agent.session_id, agent.title])),
50461
- liveness: new Map(agents.map((agent) => [agent.session_id, agentLiveness(agent)]))
50462
- };
50463
- } catch {
50464
- return;
50110
+ function formatOpenAsksSummary(response, linkBase) {
50111
+ const scope = "active open asks you authored on open issues and project documents";
50112
+ if (response.count === 0) {
50113
+ return ["There are no unanswered asks for this session.", `Scope: ${scope}.`].join(`
50114
+ `);
50465
50115
  }
50116
+ const waitingOnHuman = (response.asks ?? []).filter((ask) => ask.waiting_on === "human");
50117
+ const waitingOnAgent = (response.asks ?? []).filter((ask) => ask.waiting_on === "agent");
50118
+ return [
50119
+ `${response.count} unanswered ${response.count === 1 ? "ask" : "asks"} you authored on active issues and project documents.`,
50120
+ "",
50121
+ `Waiting on human (${waitingOnHuman.length}):`,
50122
+ ...waitingOnHuman.map((ask) => openAskLine(ask, linkBase)),
50123
+ "",
50124
+ `Waiting on agent (${waitingOnAgent.length}):`,
50125
+ ...waitingOnAgent.map((ask) => openAskLine(ask, linkBase))
50126
+ ].join(`
50127
+ `);
50466
50128
  }
50467
- function agentLiveness(agent) {
50468
- return {
50469
- ...agent.state === undefined ? {} : { holder_state: agent.state },
50470
- ...agent.last_seen > 0 ? { last_seen: new Date(agent.last_seen).toISOString() } : {}
50471
- };
50129
+ function commentSummary({ comment, replies }, graph) {
50130
+ const root = [
50131
+ `${comment.id} \xB7 ${actorText(comment.author)}`,
50132
+ ...anchorLines(comment),
50133
+ ...replyBlockLines(comment),
50134
+ `Body: ${comment.body}`
50135
+ ];
50136
+ const chain = (replies ?? []).flatMap((reply) => [
50137
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
50138
+ ...anchorLines(reply),
50139
+ ...replyBlockLines(reply),
50140
+ ...reply.answers != null && reply.answers !== comment.id ? [`Answers: ${reply.answers}`] : [],
50141
+ `Body: ${reply.body}`
50142
+ ]);
50143
+ return [
50144
+ "Comment:",
50145
+ ...root,
50146
+ "Reply chain:",
50147
+ ...chain.length === 0 ? ["- none"] : chain,
50148
+ ...graph
50149
+ ].join(`
50150
+ `);
50472
50151
  }
50473
- function holdsSession(claim) {
50474
- return claim?.actor.kind === "session";
50152
+ function replyBlockLines(record) {
50153
+ const block = record.reply_block;
50154
+ if (block === undefined || block === null)
50155
+ return [];
50156
+ return [
50157
+ block.removed ? `Re: block ${block.block_id} (removed)` : `Re: block ${block.block_id}: ${textHead(block.text)}`
50158
+ ];
50475
50159
  }
50476
- function isRouteStatus(value) {
50477
- return ISSUE_ROUTE_STATUSES.some((status) => status === value);
50160
+ function anchorLines(record) {
50161
+ return [
50162
+ ...record.anchor?.quote === undefined ? [] : [`> ${record.anchor.quote}`],
50163
+ ...record.anchor_block === undefined ? [] : [`Position: ${positionText(record.anchor_block)}`],
50164
+ ...record.anchor_block_error === undefined ? [] : [`Position: unavailable (${record.anchor_block_error})`]
50165
+ ];
50478
50166
  }
50479
- function routeHeldBySession(issue) {
50480
- return issue.route_status === "live" && issue.route?.startsWith("role:") === true;
50167
+ function positionText(block) {
50168
+ const { table, path } = block;
50169
+ const segments = (path ?? []).map((entry) => `${entry.type}[${entry.index}]`);
50170
+ if (table === undefined || table.row === null)
50171
+ return segments.join(" \u203A ");
50172
+ const tableAt = (path ?? []).findIndex((entry) => entry.type === "table");
50173
+ const cells = table.cells ?? [];
50174
+ const label = (table.column === null ? cells : cells.slice(0, table.column)).map((cell) => cell.trim()).filter((cell) => cell !== "" && !/^\d+$/.test(cell)).join(" \xB7 ");
50175
+ const row = label === "" ? `row ${table.row}` : `row ${table.row} (${label})`;
50176
+ const header = table.header === null || table.header === "" ? String(table.column) : table.header;
50177
+ return [
50178
+ ...segments.slice(0, tableAt + 1),
50179
+ table.column === null ? row : `${row}, column ${header}`
50180
+ ].join(" \u203A ");
50481
50181
  }
50482
- function routeText(issue, titles) {
50483
- if (issue.route === null)
50484
- return "none";
50485
- const holder = issue.route_holder ?? null;
50486
- const reach = {
50487
- live: routeHeldBySession(issue) && holder !== null ? ` (held by ${titles?.get(holder) ?? holder})` : "",
50488
- holder_unresponsive: issue.route.startsWith("role:") ? ` (its holder${holder === null ? "" : ` ${titles?.get(holder) ?? holder}`} is unresponsive: messages wait for it)` : " (that session is unresponsive: messages wait for it)",
50489
- no_holder: issue.route.startsWith("role:") ? " (nobody holds it right now)" : " (that session is not running right now)",
50490
- unknown: issue.route_status_reason === "refilling" ? " (the Envoy listener's agent list is refilling, so whether it reaches anyone is unknown; try again in a moment)" : " (the Envoy listener did not answer, so whether it reaches anyone is unknown)"
50491
- };
50492
- const status = issue.route_status;
50493
- return issue.route + (status != null && isRouteStatus(status) ? reach[status] : "");
50182
+ function messageSummary({ message, replies }, graph) {
50183
+ const root = [
50184
+ `${message.id} \xB7 ${actorText(message.author)}`,
50185
+ ...replyBlockLines(message),
50186
+ `Body: ${message.body}`
50187
+ ];
50188
+ const chain = (replies ?? []).flatMap((reply) => [
50189
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
50190
+ ...replyBlockLines(reply),
50191
+ `Body: ${reply.body}`
50192
+ ]);
50193
+ return [
50194
+ "Message:",
50195
+ ...root,
50196
+ "Reply chain:",
50197
+ ...chain.length === 0 ? ["- none"] : chain,
50198
+ ...graph
50199
+ ].join(`
50200
+ `);
50494
50201
  }
50495
- function progressText(progress, sep) {
50496
- if (progress === undefined)
50497
- return "";
50498
- const parts = [];
50499
- if (progress.tasks !== null)
50500
- parts.push(`tasks ${progress.tasks.done}/${progress.tasks.total}`);
50501
- if (progress.children !== null) {
50502
- parts.push(`children ${progress.children.done}/${progress.children.total}`);
50202
+ async function openAnchoredThreads(client, resolved) {
50203
+ const asksPromise = resolved.owner.kind === "project" ? client.getArtifactAsks(resolved.artifact.id) : Promise.resolve(resolved.issue?.open_asks ?? []);
50204
+ const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "");
50205
+ const commentsResultPromise = commentsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
50206
+ const asks = (await asksPromise).filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id);
50207
+ const commentsResult = await commentsResultPromise;
50208
+ if (commentsResult.status === "rejected" && !dispatchAnswered(commentsResult.reason, 404)) {
50209
+ throw commentsResult.reason;
50503
50210
  }
50504
- return parts.join(sep);
50211
+ const comments = commentsResult.status === "fulfilled" ? commentsResult.value : [];
50212
+ const askReplies = new Map(asks.map((ask) => [ask.id, []]));
50213
+ for (const comment of comments) {
50214
+ if (comment.ask_id)
50215
+ askReplies.get(comment.ask_id)?.push(comment);
50216
+ }
50217
+ const askThreads = asks.map((ask) => [
50218
+ `ask ${ask.id} \xB7 ${actorText(ask.author)} \xB7 ${ask.created_at}`,
50219
+ ...anchorLines(ask),
50220
+ `Question: ${ask.question}`,
50221
+ ...threadReplyLines(askReplies.get(ask.id) ?? [])
50222
+ ].join(`
50223
+ `));
50224
+ const byId = new Map(comments.map((comment) => [comment.id, comment]));
50225
+ const roots = comments.filter((comment) => comment.reply_to === null && !comment.ask_id && !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id);
50226
+ const replies = new Map(roots.map((root) => [root.id, []]));
50227
+ for (const comment of comments) {
50228
+ const root = comment.reply_to === null ? undefined : threadRootId(comment, byId);
50229
+ if (root !== undefined)
50230
+ replies.get(root)?.push(comment);
50231
+ }
50232
+ const commentThreads = roots.map((root) => [
50233
+ `comment ${root.id} \xB7 ${actorText(root.author)} \xB7 ${root.created_at}`,
50234
+ ...anchorLines(root),
50235
+ `Body: ${root.body}`,
50236
+ ...threadReplyLines(replies.get(root.id) ?? [])
50237
+ ].join(`
50238
+ `));
50239
+ return [...askThreads, ...commentThreads];
50505
50240
  }
50506
- function repositoryLine(issue) {
50507
- if (issue.resolved_repo === undefined) {
50508
- return "Repository: unknown (this Dispatch server predates repository fields; upgrade it)";
50241
+ function threadReplyLines(replies) {
50242
+ return replies.flatMap((reply) => [
50243
+ `reply ${reply.id} \xB7 ${actorText(reply.author)} \xB7 ${reply.created_at}`,
50244
+ `Body: ${reply.body}`
50245
+ ]);
50246
+ }
50247
+ function threadRootId(comment, byId) {
50248
+ const seen = new Set;
50249
+ let current = comment;
50250
+ while (current.reply_to !== null) {
50251
+ if (seen.has(current.id))
50252
+ return;
50253
+ seen.add(current.id);
50254
+ const parent = byId.get(current.reply_to);
50255
+ if (parent === undefined)
50256
+ return;
50257
+ current = parent;
50509
50258
  }
50510
- if (issue.resolved_repo === null)
50511
- return "Repository: none";
50512
- if (issue.repo !== null && issue.repo !== undefined)
50513
- return `Repository: ${issue.repo} (own)`;
50514
- return `Repository: ${issue.resolved_repo} (inherited or project default)`;
50259
+ return current.id;
50515
50260
  }
50516
- function olderServerWarnings(issue) {
50517
- const warnings = [
50518
- ...issue.resolved_repo !== undefined ? [] : [
50519
- `dispatch: warning: Dispatch issue is missing resolved_repo: this Dispatch server predates repository fields, so ${issue.key}'s repository is unknown; upgrade the server`
50520
- ],
50521
- ...issue.advances !== undefined ? [] : [
50522
- `dispatch: warning: Dispatch issue is missing advances: this Dispatch server predates priorities, so the priorities ${issue.key} advances are unknown; upgrade the server`
50523
- ]
50261
+
50262
+ // ../envoy-client/src/dispatch-commands/asks.ts
50263
+ function askUrgency(args) {
50264
+ const value = args.urgency;
50265
+ return ASK_URGENCIES.find((urgency) => urgency === value);
50266
+ }
50267
+ var askHintLimit = 8;
50268
+ function openAskChoices(asks, owner) {
50269
+ if (asks.length === 0)
50270
+ return `${owner} holds no open ask.`;
50271
+ const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)}\u2026 ${textHead(ask.question)}`);
50272
+ return `The open asks of ${owner} are: ${hints.join(", ")}.`;
50273
+ }
50274
+ function askIDInputProblem(asks, owner) {
50275
+ return `ask ids are uuids. Write the whole id, or at least its first 8 characters. ${openAskChoices(asks, owner)}`;
50276
+ }
50277
+ async function movedApprovalLine(client, askID) {
50278
+ const ask = (await client.getAsk(askID).catch(() => {
50279
+ return;
50280
+ }))?.ask;
50281
+ const approval = ask?.approval;
50282
+ if (ask?.kind !== "approval" || approval === undefined)
50283
+ return;
50284
+ const listed = approval.documents ?? [];
50285
+ const documents = listed.length > 0 ? listed : [
50286
+ {
50287
+ name: approval.name,
50288
+ requested_version: approval.requested_version,
50289
+ version: approval.version
50290
+ }
50524
50291
  ];
50525
- return warnings.length === 0 ? {} : { warnings };
50292
+ const moved = movedApprovalDocuments(documents);
50293
+ if (moved.length === 0)
50294
+ return;
50295
+ const firstMoved = moved[0];
50296
+ if (firstMoved === undefined)
50297
+ return;
50298
+ const command = handBackApprovalCommand({
50299
+ owner: ask.issue_key === null ? { kind: "project", key: ask.approval_artifact?.project ?? "<project>" } : { kind: "issue", key: ask.issue_key },
50300
+ artifactID: approval.artifact_id,
50301
+ primary: ask.approval_artifact?.primary === true,
50302
+ verification: documents.length > 1 && ask.approval_artifact?.primary === true,
50303
+ summaryVersion: firstMoved.requested_version
50304
+ });
50305
+ return "The reply did not hand the ask to the human: it is an open approval request, and " + `${movedApprovalClauses(moved)}. No reply hands a moved approval request back. Once the ` + `human has agreed to every point in it, run: ${command}`;
50526
50306
  }
50527
- function issueSummary(issue, events, references, graph, linkBase, coverage, agents) {
50528
- const asks = issue.open_asks ?? [];
50529
- const labels = issue.labels ?? [];
50530
- const links = issue.external_links ?? [];
50531
- const members = typeof references === "string" ? [] : references.members ?? [];
50532
- const spec = issue.artifacts?.find((artifact) => artifact.primary);
50533
- const specApproval = spec === undefined ? undefined : approvalLine(spec, typeof issue.closed_at === "string");
50534
- if (issue.priority === undefined)
50535
- throw new Error("Dispatch issue is missing priority");
50536
- if (issue.assignee === undefined)
50537
- throw new Error("Dispatch issue is missing assignee");
50538
- if (issue.components === undefined)
50539
- throw new Error("Dispatch issue is missing components");
50540
- if (issue.claim === undefined)
50541
- throw new Error("Dispatch issue is missing claim");
50542
- if (issue.external_links === undefined) {
50543
- throw new Error("Dispatch issue is missing external_links");
50307
+ async function replyToAskCandidates(client, owner, resolved) {
50308
+ if (owner.kind === "issue") {
50309
+ const issue = resolved?.issue ?? await client.getIssue(owner.issue);
50310
+ return { asks: issue.open_asks ?? [], owner: "this issue" };
50544
50311
  }
50545
- return [
50546
- `Title: ${issue.title}`,
50547
- `Key: ${issue.key}`,
50548
- `Link: ${linkFor(`/issues/${encodeURIComponent(issue.key)}`, linkBase)}`,
50549
- `Status: ${issue.status}`,
50550
- `Assignee: ${issue.assignee ?? "unassigned"}`,
50551
- `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, agents, issue)}`,
50552
- ...issue.priority === null ? [] : [`Priority: P${issue.priority}`],
50553
- `Labels: ${labels.length === 0 ? "none" : labels.join(", ")}`,
50554
- componentsLine(issue.components),
50555
- advancesLine(issue),
50556
- `Route: ${routeText(issue, agents?.titles)}`,
50557
- repositoryLine(issue),
50558
- `Progress: ${progressText(issue.progress, ", ") || "none"}`,
50559
- ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
50560
- ...typeof coverage === "string" ? [`Coverage: ${coverage}`] : (coverage.gaps ?? []).map((gap) => `Coverage: ${gap}`),
50561
- "External links:",
50562
- ...links.length === 0 ? ["- none"] : links.map((link) => `- ${link.url}${link.kind === undefined ? "" : ` (${link.kind})`}`),
50563
- "Documents:",
50564
- ...documentListLines(issue.artifacts ?? []),
50565
- "Open asks:",
50566
- ...asks.length === 0 ? ["- none"] : asks.map((ask) => `- ${ask.id}: ${ask.question}`),
50567
- "References:",
50568
- ...typeof references === "string" ? [`- ${references}`] : members.length === 0 ? ["- none"] : members.map(({ artifact, depth, via }) => `- ${artifact.project}/${artifact.slug} \xB7 depth ${depth} via ${via.kind} ${via.id}`),
50569
- ...typeof references === "string" || !references.truncated ? [] : ["- more references beyond 8 hops"],
50570
- "Events:",
50571
- ...events.length === 0 ? ["- none"] : events.map(eventLine),
50572
- ...graph
50573
- ].join(`
50574
- `);
50312
+ if (resolved === undefined)
50313
+ throw new Error("project document is missing its resolved artifact");
50314
+ return {
50315
+ asks: await client.getArtifactAsks(resolved.artifact.id, "open"),
50316
+ owner: "this document"
50317
+ };
50575
50318
  }
50576
- function logSummary(issue, events) {
50577
- return [
50578
- `Key: ${issue.key}`,
50579
- "Events:",
50580
- ...events.length === 0 ? ["- none"] : events.map(eventLine)
50581
- ].join(`
50582
- `);
50319
+ async function resolveReplyToAsk(tool, client, target, resolved, id) {
50320
+ const whole = normalizeUUID(id);
50321
+ if (whole !== undefined)
50322
+ return whole;
50323
+ const { asks, owner } = await replyToAskCandidates(client, target, resolved);
50324
+ if (!isIdPrefix(id)) {
50325
+ throw new ToolInputError(tool, [askIDInputProblem(asks, owner)], { aboutAFlag: false });
50326
+ }
50327
+ return resolveIdPrefix(tool, "ask", id, owner, async () => asks, {
50328
+ refusal: (found, all) => found.length === 0 ? `reply_to_ask ${id} names no open ask of ${owner}. ${openAskChoices(all, owner)}` : `reply_to_ask ${id} names ${found.length} open asks of ${owner}. Write more of the id. ${openAskChoices(all, owner)}`
50329
+ });
50583
50330
  }
50584
- function eventHead(event) {
50585
- switch (event.type) {
50586
- case "ask.opened":
50587
- case "ask.anchor_refreshed":
50588
- case "ask.edited":
50589
- case "ask.handed_back":
50590
- case "ask.resolved":
50591
- return textHead(event.payload.question);
50592
- case "ask.answered": {
50593
- const previousAnswer = event.payload.previous_answer;
50594
- return `${textHead(event.payload.question)} -> ${textHead(askAnswerText(event.payload.answer))}${previousAnswer === undefined ? "" : ` (was: ${textHead(askAnswerText(previousAnswer))})`}`;
50595
- }
50596
- case "ask.asked_of":
50597
- return `${textHead(event.payload.question)} -> asked of ${event.payload.asked_of ?? "the assignee of its issue"}`;
50598
- case "comment.created":
50599
- case "comment.answered":
50600
- case "comment.anchor_refreshed":
50601
- case "comment.edited":
50602
- case "comment.resolved":
50603
- case "comment.reopened":
50604
- case "suggestion.accepted":
50605
- case "suggestion.rejected":
50606
- case "message.created":
50607
- case "message.answered":
50608
- return textHead(event.payload.body);
50609
- case "artifact.version":
50610
- return textHead(`${event.payload.name} v${event.payload.version.number}${event.payload.version.summary ? `: ${event.payload.version.summary}` : ""}`);
50611
- case "artifact.approved":
50612
- case "artifact.changes_requested": {
50613
- const { name, version, kind, reason } = event.payload;
50614
- const verb = event.type === "artifact.approved" ? "approved" : "changes requested";
50615
- const reviewer = kind === "plan_review" ? " by plan review" : kind === "person" ? " by a person" : "";
50616
- return textHead(`${name} v${version} ${verb}${reviewer}${reason ? `: ${reason}` : ""}`);
50331
+ var askIdShapeProblem = "ask ids are uuids (a prefix of at least 8 hex characters works)";
50332
+ async function readAskRef(tool, id, ownerName, client, list) {
50333
+ const fullID = normalizeUUID(id);
50334
+ if (fullID !== undefined) {
50335
+ try {
50336
+ return await client.getAsk(fullID);
50337
+ } catch (error) {
50338
+ if (!(error instanceof DispatchServiceError) || error.status !== 404)
50339
+ throw error;
50340
+ const blocks = (await list()).filter((ask) => ask.block_id?.toLowerCase() === fullID);
50341
+ if (blocks.length !== 1 || blocks[0] === undefined)
50342
+ throw error;
50343
+ return client.getAsk(blocks[0].id);
50617
50344
  }
50618
- case "artifact.human_edited":
50619
- return textHead(humanEditHead(event.payload));
50620
- case "issue.created": {
50621
- const forced = event.payload.forced;
50622
- const head = `status ${event.payload.status}`;
50623
- if (forced === undefined)
50624
- return head;
50625
- return forced.past.length === 0 ? `${head} \xB7 forced, the near-copy check did not answer` : `${head} \xB7 forced past ${forced.past.join(", ")}`;
50345
+ }
50346
+ const asks = await list();
50347
+ let matches = asks.filter((ask) => ask.block_id === id);
50348
+ if (matches.length === 0) {
50349
+ if (!isIdPrefix(id)) {
50350
+ throw new ToolInputError(tool, [
50351
+ `ask id ${id} must be a full uuid, a prefix of at least 8 hex characters, or the id of an :::ask block on ${ownerName}`
50352
+ ]);
50626
50353
  }
50627
- case "issue.updated":
50628
- case "issue.closed":
50629
- return `status ${event.payload.status}`;
50630
- default:
50354
+ const prefix = id.toLowerCase();
50355
+ matches = asks.filter((ask) => ask.id.toLowerCase().startsWith(prefix) || (ask.block_id?.toLowerCase().startsWith(prefix) ?? false));
50356
+ }
50357
+ if (matches.length === 1 && matches[0] !== undefined)
50358
+ return client.getAsk(matches[0].id);
50359
+ throw new ToolInputError(tool, [
50360
+ matches.length === 0 ? `ask id ${id} matches none of the asks on ${ownerName}; use the full id` : `ask id ${id} matches ${matches.length} asks on ${ownerName}; use the full id`
50361
+ ]);
50362
+ }
50363
+ async function sessionOpenAsks(client, sessionId) {
50364
+ const session = sessionId?.trim();
50365
+ if (!session)
50366
+ throw new Error("host session id is required to read this session's open asks");
50367
+ return (await client.openAsks(session)).asks ?? [];
50368
+ }
50369
+ function openAskHints(asks) {
50370
+ if (asks.length === 0)
50371
+ return "you have no open asks";
50372
+ const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)} \u2014 ${textHead(ask.question)}`);
50373
+ return `your open asks: ${hints.join("; ")}`;
50374
+ }
50375
+ async function resolveAskArgument(tool, args, client, sessionId) {
50376
+ const id = askId(args);
50377
+ if (normalizeUUID(id) === undefined && !isIdPrefix(id)) {
50378
+ const asks = await sessionOpenAsks(client, sessionId).catch(() => {
50631
50379
  return;
50380
+ });
50381
+ throw new ToolInputError(tool, [
50382
+ asks === undefined ? askIdShapeProblem : `${askIdShapeProblem}; ${openAskHints(asks)}`
50383
+ ]);
50632
50384
  }
50385
+ const resolved = await resolveIdPrefix(tool, "ask", id, "this session", () => sessionOpenAsks(client, sessionId));
50386
+ const reference = stringArg(args, "ask");
50387
+ const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
50388
+ if (ref === null)
50389
+ return { id: resolved };
50390
+ const read = await client.getAsk(resolved);
50391
+ await refuseItemOffRef(tool, "ask", ref, reference, read.ask, async () => {
50392
+ const document = await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true });
50393
+ return document.artifact.id;
50394
+ });
50395
+ return { id: resolved, read };
50633
50396
  }
50634
- function eventRef(event) {
50635
- const payload = event.payload;
50636
- const id = typeof payload === "object" && payload !== null && "id" in payload ? payload.id : undefined;
50637
- if (typeof id !== "string" || id === "" || event.issue_key === null)
50638
- return;
50639
- const kind = event.type.startsWith("message.") ? "message" : event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("ask.") ? "ask" : undefined;
50640
- return kind === undefined ? undefined : `dispatch://${event.issue_key}/${kind}/${id}`;
50397
+ async function openAsksCommand(context) {
50398
+ const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
50399
+ const client = dispatchClient();
50400
+ const project = optionalString(ownerArguments.args, "project");
50401
+ if (project !== undefined) {
50402
+ const response = await client.openAsksForProject(project);
50403
+ return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
50404
+ }
50405
+ const sessionId = input.sessionId?.trim();
50406
+ if (!sessionId)
50407
+ throw new Error("host session id is required for dispatch open-asks");
50408
+ const response = await client.openAsks(sessionId);
50409
+ return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
50641
50410
  }
50642
- function eventActorText(actor) {
50643
- const title = actor.kind === "session" ? actor.origin?.session_title : undefined;
50644
- return title === undefined || title === "" ? actorText(actor) : `${actorText(actor)} (${title})`;
50411
+ async function askCommand(context) {
50412
+ const {
50413
+ args,
50414
+ client,
50415
+ actor,
50416
+ input,
50417
+ linkBase,
50418
+ documentOwner,
50419
+ resolveDocument,
50420
+ writePictures,
50421
+ issue
50422
+ } = context;
50423
+ const anchorArgs = asObject(args.anchor);
50424
+ const owner = documentOwner();
50425
+ const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
50426
+ const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
50427
+ const options = args.options;
50428
+ const multiple = optionalBoolean(args, "multiple");
50429
+ const urgency = askUrgency(args);
50430
+ const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
50431
+ const question = await writePictures(resolved, askQuestionWithRef(args));
50432
+ const askInput = {
50433
+ question,
50434
+ ...Array.isArray(options) ? { options } : {},
50435
+ ...multiple === undefined ? {} : { multiple },
50436
+ ...urgency === undefined ? {} : { urgency },
50437
+ ...anchored === undefined ? {} : { anchor: anchored },
50438
+ actor
50439
+ };
50440
+ const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
50441
+ const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
50442
+ const checkLines = relatedCheckLines(ask.advice?.suggestions, {
50443
+ project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
50444
+ text: stringArg(args, "question"),
50445
+ linkBase
50446
+ });
50447
+ const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
50448
+ const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
50449
+ const asked = waitsOnPerson(ask);
50450
+ return {
50451
+ text: [
50452
+ `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
50453
+ ...checkLines,
50454
+ ...declinedLines,
50455
+ await followsAsk(askOwner, input.subscriptions),
50456
+ ...adviceLines
50457
+ ].join(`
50458
+ `),
50459
+ details: {
50460
+ ...await followedAskDetails(client, ask, resolved?.artifact),
50461
+ ...ask.advice === undefined ? {} : { advice: ask.advice }
50462
+ }
50463
+ };
50645
50464
  }
50646
- function eventLine(event) {
50647
- const head = eventHead(event);
50648
- const ref = eventRef(event);
50649
- return `- #${event.seq} ${event.type}${ref === undefined ? "" : ` ${ref}`} \xB7 ${eventActorText(event.actor)} \xB7 ${event.created_at}${head === undefined || head === "" ? "" : ` \xB7 ${head}`}`;
50465
+ async function editAskCommand(context) {
50466
+ const { args, client, actor, input } = context;
50467
+ const question = optionalString(args, "question");
50468
+ const options = args.options;
50469
+ const multiple = optionalBoolean(args, "multiple");
50470
+ const urgency = askUrgency(args);
50471
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
50472
+ const ask = await client.editAsk(id, {
50473
+ ...question === undefined ? {} : { question },
50474
+ ...Array.isArray(options) ? { options } : {},
50475
+ ...multiple === undefined ? {} : { multiple },
50476
+ ...urgency === undefined ? {} : { urgency },
50477
+ actor
50478
+ });
50479
+ return {
50480
+ text: `Ask edited: ${ask.question}`,
50481
+ details: await askOwnerDetails(client, ask)
50482
+ };
50650
50483
  }
50651
- function childrenSummary(issue) {
50652
- return [
50653
- `Key: ${issue.key}`,
50654
- "Children:",
50655
- ...(issue.children ?? []).length === 0 ? ["- none"] : (issue.children ?? []).map((child) => `- ${child.key}: ${child.title} (${child.status})`)
50656
- ].join(`
50657
- `);
50484
+ async function resolveAskCommand(context) {
50485
+ const { args, client, actor, input } = context;
50486
+ const kind = stringArg(args, "kind");
50487
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
50488
+ const ask = await client.resolveAsk(id, {
50489
+ kind,
50490
+ reason: stringArg(args, "reason"),
50491
+ actor
50492
+ });
50493
+ if (ask.resolution === undefined)
50494
+ throw new Error("resolved ask is missing its resolution");
50495
+ return {
50496
+ text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
50497
+ details: await askOwnerDetails(client, ask)
50498
+ };
50658
50499
  }
50659
-
50660
- // ../envoy-client/src/dispatch-commands/issues.ts
50661
- function componentsChange(input, after) {
50662
- switch (input.mode) {
50663
- case "explicit":
50664
- return `components -> explicit [${(after.ids ?? []).join(", ")}]`;
50665
- case "none":
50666
- return `components -> none (${after.reason ?? input.reason ?? ""})`;
50667
- case "inherit":
50668
- return "components -> inherit";
50669
- default:
50670
- return `components -> ${input.mode}`;
50500
+ async function followCommand(context) {
50501
+ const { args, client, actor, input } = context;
50502
+ const sessionId = input.sessionId?.trim();
50503
+ if (!sessionId)
50504
+ throw new Error("host session id is required for dispatch follow");
50505
+ const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
50506
+ const action = stringArg(args, "action");
50507
+ if (action === "unfollow") {
50508
+ await client.unfollowAsk(ask, sessionId, actor);
50509
+ return { text: `Unfollowed ask ${ask}.`, details: { ask } };
50671
50510
  }
50511
+ const read = refRead ?? await client.getAsk(ask);
50512
+ await client.followAsk(ask, sessionId, actor);
50513
+ return {
50514
+ text: `Following ask ${ask}: its answer and replies reach this session directly.`,
50515
+ details: await followedAskDetails(client, read.ask)
50516
+ };
50672
50517
  }
50673
- var architectureComponentsAction = 'Review the `dispatch` skill, "Architecture components", to attach it to the parts it changes or mark it as non-architectural with a reason.';
50674
- var LEGION_OWNS_STATUS = "Legion's daemon moves this issue's status on an issue it runs, so leave it alone \u2014 a status written here is undone.";
50675
- async function architectureGuidance(client, project, components) {
50676
- if (components.mode === "none" || (components.ids ?? []).length > 0)
50677
- return;
50678
- try {
50679
- if ((await client.listArchitectureSources(project)).length === 0)
50680
- return;
50681
- return `Project ${project} has an architecture model, but this issue is not linked to any of its current components. ${architectureComponentsAction}`;
50682
- } catch (error) {
50683
- return `Could not check whether project ${project} has an architecture model: ${messageFor(error)}. ${architectureComponentsAction}`;
50518
+
50519
+ // ../envoy-client/src/dispatch-commands/conversation.ts
50520
+ async function resolveCommentCommand(context) {
50521
+ const { args, client, actor, input } = context;
50522
+ const reference = stringArg(args, "comment");
50523
+ const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
50524
+ let id = reference;
50525
+ let document;
50526
+ if (ref?.owner.kind === "issue") {
50527
+ const issueKey = ref.owner.issue;
50528
+ id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
50529
+ } else if (ref !== null) {
50530
+ const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
50531
+ document = artifact;
50532
+ id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
50684
50533
  }
50685
- }
50686
- function isDuplicateCandidate(value) {
50687
- if (typeof value !== "object" || value === null)
50688
- return false;
50689
- const candidate = value;
50690
- return typeof candidate.key === "string" && typeof candidate.title === "string" && typeof candidate.status === "string" && typeof candidate.snippet === "string" && typeof candidate.shared_terms === "number" && typeof candidate.href === "string";
50691
- }
50692
- function duplicateCandidates(error) {
50693
- if (error.candidates === undefined || !error.candidates.every(isDuplicateCandidate))
50694
- throw error;
50695
- return error.candidates;
50696
- }
50697
- function refuseUnsavedRepository(verb, issue, repo) {
50698
- if (repo === undefined || issue.repo !== undefined)
50699
- return;
50700
- const lost = repo === "" ? "the repository was not cleared" : `${repo} was not saved`;
50701
- throw new Error(`Dispatch ${verb} ${issue.key} without its repository: this Dispatch server predates repository fields, so ${lost}; upgrade the server`);
50702
- }
50703
- function advancesRevisionToSend(issue, named) {
50704
- if (issue.advances_revision === undefined) {
50705
- throw new Error(`Dispatch read ${issue.key} without its advances: this Dispatch server predates priorities, so nothing was sent; upgrade the server`);
50534
+ if (ref !== null) {
50535
+ const read = await client.getComment(id);
50536
+ await refuseItemOffRef(input.tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
50706
50537
  }
50707
- return named ?? issue.advances_revision;
50538
+ const comment = await client.resolveComment(id, actor);
50539
+ const { label, details } = await commentOwnerResult(client, comment, document);
50540
+ return { text: `Resolved comment ${comment.id} on ${label}.`, details };
50708
50541
  }
50709
- async function issueCommand(context) {
50710
- const { args, client, actor, input, linkBase } = context;
50711
- const project = stringArg(args, "project");
50712
- const title = stringArg(args, "title");
50713
- const parent = optionalString(args, "parent");
50714
- const external = optionalString(args, "external");
50715
- const force = optionalBoolean(args, "force");
50716
- const spec = optionalString(args, "spec");
50717
- const priority = optionalPriority(args, "priority");
50718
- const assignee = optionalString(args, "assignee");
50719
- const components = optionalComponents(args, "components");
50720
- const repo = optionalString(args, "repo");
50721
- const labels = args.labels;
50722
- const blockedBy = args.blocked_by;
50723
- const advances = optionalStringArray(args, "advances");
50724
- try {
50725
- const created = await client.issue({
50726
- project,
50727
- title,
50728
- ...parent === undefined ? {} : { parent },
50729
- ...Array.isArray(blockedBy) ? { blocked_by: blockedBy } : {},
50730
- ...advances === undefined ? {} : { advances },
50731
- ...external === undefined ? {} : { external },
50732
- ...force === undefined ? {} : { force },
50733
- ...spec === undefined ? {} : { spec },
50734
- ...priority === undefined ? {} : { priority },
50735
- ...assignee === undefined ? {} : { assignee },
50736
- ...components === undefined ? {} : { components },
50737
- ...repo === undefined ? {} : { repo },
50738
- ...Array.isArray(labels) ? { labels } : {},
50739
- actor
50740
- });
50741
- refuseUnsavedRepository(created.created ? "created" : "already holds", created, repo);
50742
- const adviceLines = await otherAdviceLines(async () => {
50743
- const componentGuidance = await architectureGuidance(client, created.project, created.components);
50744
- return [
50745
- ...renderAdvice(input.tool, created.key, created.advice, {
50746
- isPrimarySpec: spec !== undefined
50747
- }),
50748
- ...componentGuidance === undefined ? [] : [componentGuidance]
50749
- ];
50750
- });
50751
- const href = linkFor(`/issues/${encodeURIComponent(created.key)}`, linkBase);
50752
- const assigned = created.assignee === undefined ? "" : created.assignee === null ? "; unassigned" : `; assigned to ${created.assignee}`;
50753
- const suffixes = `${assigned}${await notSubscribed(issueTopic(created.key), input.subscriptions)}`;
50542
+ async function commentCommand(context) {
50543
+ const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
50544
+ const artifactReference = optionalString(args, "artifact");
50545
+ const owner = documentOwner();
50546
+ const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
50547
+ const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
50548
+ const replyTo = itemReplyTo(args, "reply_to");
50549
+ const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
50550
+ const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
50551
+ const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
50552
+ const requestedTurn = optionalString(args, "turn");
50553
+ const body = await writePictures(resolved, stringArg(args, "body"));
50554
+ const commentInput = {
50555
+ body,
50556
+ ...anchored === undefined ? {} : { anchor: anchored },
50557
+ ...replyTo === undefined ? {} : { reply_to: replyTo.id },
50558
+ ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
50559
+ ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
50560
+ ...requestedTurn === undefined ? {} : { turn: requestedTurn },
50561
+ actor
50562
+ };
50563
+ const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
50564
+ const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
50565
+ const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
50566
+ const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
50567
+ isAskReply: replyToAsk !== undefined,
50568
+ replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
50569
+ });
50570
+ if (replyToAsk !== undefined) {
50571
+ const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
50572
+ const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
50754
50573
  return {
50755
50574
  text: [
50756
- created.created ? `Created ${created.key}: ${created.title} \u2192 ${href}${suffixes}` : `Dispatch already holds ${created.key}: ${created.title} \u2192 ${href}; nothing was created${suffixes}`,
50757
- ...created.created ? relatedCheckLines(created.advice?.suggestions, {
50758
- project: created.project,
50759
- text: title,
50760
- linkBase
50761
- }) : [],
50575
+ `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
50576
+ ...moved === undefined ? [] : [moved],
50762
50577
  ...adviceLines
50763
50578
  ].join(`
50764
50579
  `),
50765
50580
  details: {
50766
- issue: created.key,
50767
- ...created.advice === undefined ? {} : { advice: created.advice }
50581
+ ...commentDetails,
50582
+ ask: replyToAsk,
50583
+ follows: { ask: replyToAsk },
50584
+ ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
50585
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
50586
+ }
50587
+ };
50588
+ }
50589
+ return {
50590
+ text: [
50591
+ `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
50592
+ ...adviceLines
50593
+ ].join(`
50594
+ `),
50595
+ details: {
50596
+ ...commentDetails,
50597
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
50598
+ }
50599
+ };
50600
+ }
50601
+ async function suggestCommand(context) {
50602
+ const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
50603
+ const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
50604
+ const anchored = anchor(resolved.artifact, args);
50605
+ if (anchored === undefined)
50606
+ throw new Error("quote is required");
50607
+ const body = optionalString(args, "body");
50608
+ const suggestionInput = {
50609
+ ...body === undefined ? {} : { body },
50610
+ anchor: anchored,
50611
+ replace_with: stringArg(args, "replace_with"),
50612
+ actor
50613
+ };
50614
+ const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
50615
+ return {
50616
+ text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
50617
+ details: writeResultDetails(resolved, { comment: comment.id })
50618
+ };
50619
+ }
50620
+ function conversationReadBack(messageId) {
50621
+ return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
50622
+ }
50623
+ async function messageCommand(context) {
50624
+ const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
50625
+ const target = messageInReplyTo(args);
50626
+ const inReplyTo = target?.id;
50627
+ const written = stringArg(args, "body");
50628
+ if (owner === null && inReplyTo !== undefined) {
50629
+ let body = written;
50630
+ if (pictures.length > 0) {
50631
+ const sessionId = input.sessionId?.trim();
50632
+ if (!sessionId) {
50633
+ throw new Error("host session id is required to send pictures in a direct-message reply");
50768
50634
  }
50769
- };
50770
- } catch (error) {
50771
- if (!(error instanceof DispatchServiceError) || error.code !== "POSSIBLE_DUPLICATE") {
50772
- throw error;
50635
+ body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
50773
50636
  }
50774
- const candidates = duplicateCandidates(error);
50637
+ const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
50638
+ if (reply.duplicate === true && reply.body === body) {
50639
+ return {
50640
+ text: `Dispatch already has this exact text in the conversation (message ${reply.id}); ` + "nothing new was posted. Send different text if you have more to say.",
50641
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
50642
+ };
50643
+ }
50644
+ if (reply.body !== body) {
50645
+ return {
50646
+ text: `Message ${inReplyTo} was already answered by message ${reply.id}; Dispatch kept ` + "that reply and posted nothing. Wait for their next message rather than answering " + "this one again.",
50647
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
50648
+ };
50649
+ }
50650
+ const readBack = conversationReadBack(inReplyTo);
50651
+ const parent = reply.in_reply_to ?? undefined;
50652
+ const follows = parent === inReplyTo ? undefined : parent;
50775
50653
  return {
50776
- text: [
50777
- `Not created: "${title}" is a near copy of an open issue.`,
50778
- ...candidates.map((candidate) => {
50779
- const href = linkFor(candidate.href, linkBase);
50780
- return `${candidate.key} [${candidate.status}] ${candidate.title} \u2192 ${href}`;
50781
- }),
50782
- "Read each issue above. If one is the same work, fold this into it by the duplicate rule of skill://dispatch-first.",
50783
- "If none is, run dispatch issue again with --force, and write in the new issue's spec why it is not each issue named here."
50784
- ].join(`
50785
- `),
50786
- details: { duplicates: candidates },
50787
- refused: true
50654
+ text: follows === undefined ? `Replied to message ${inReplyTo} with message ${reply.id}. ${readBack}` : `Replied to message ${inReplyTo} with message ${reply.id}, a follow-up threaded ` + `under your reply ${follows}. ${readBack}`,
50655
+ details: {
50656
+ message: reply.id,
50657
+ in_reply_to: inReplyTo,
50658
+ posted: true,
50659
+ ...follows === undefined ? {} : { follows }
50660
+ }
50788
50661
  };
50789
50662
  }
50790
- }
50791
- async function issueUpdateCommand(context) {
50792
- const { args, client, actor, input, issue } = context;
50793
50663
  const issueKey = issue();
50794
- const status = optionalString(args, "status");
50795
- const reason = optionalString(args, "reason");
50796
- const title = optionalString(args, "title");
50797
- const route = optionalString(args, "route");
50798
- const parent = optionalString(args, "parent");
50799
- const components = optionalComponents(args, "components");
50800
- const repo = optionalString(args, "repo");
50801
- const rankBefore = optionalString(args, "before");
50802
- const rankAfter = optionalString(args, "after");
50803
- const priority = optionalPriority(args, "priority");
50804
- const assignee = optionalNullableString(args, "assignee");
50805
- const labels = Array.isArray(args.labels) ? args.labels : undefined;
50806
- const blockedBy = Array.isArray(args.blocked_by) ? args.blocked_by : undefined;
50807
- const advances = optionalStringArray(args, "advances");
50808
- const advancesRevision = optionalNumber(args, "advances_revision");
50809
- const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
50810
- let before;
50811
- try {
50812
- before = await client.getIssue(issueKey);
50813
- } catch (error) {
50814
- throw refusalWithCode(error);
50664
+ const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
50665
+ const message = await client.message(issueKey, {
50666
+ body,
50667
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
50668
+ ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
50669
+ actor
50670
+ });
50671
+ const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
50672
+ const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
50673
+ return {
50674
+ text: [
50675
+ `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
50676
+ ...adviceLines
50677
+ ].join(`
50678
+ `),
50679
+ details: {
50680
+ issue: issueKey,
50681
+ message: message.id,
50682
+ ...message.advice === undefined ? {} : { advice: message.advice }
50683
+ }
50684
+ };
50685
+ }
50686
+ function arrivalText(attempt) {
50687
+ if (attempt === undefined)
50688
+ return "Dispatch recorded no delivery attempt for it";
50689
+ if (attempt.state === "failed") {
50690
+ return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
50815
50691
  }
50816
- const advancesWrite = advances === undefined ? undefined : { advances, advances_revision: advancesRevisionToSend(before, advancesRevision) };
50817
- if (status === "done" && typeof before.closed_at === "string") {
50818
- throw refusalWithCode(new DispatchServiceError("ISSUE_CLOSED", 409, "issue is closed"), `${issueKey} closed at ${before.closed_at}, so the reason was not posted and the close was not sent`);
50692
+ if (attempt.state === "pending")
50693
+ return "its delivery is still on its way";
50694
+ if (attempt.state === "queued") {
50695
+ return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
50819
50696
  }
50820
- let closingNote;
50821
- if (reason !== undefined) {
50822
- try {
50823
- const message = await client.message(issueKey, { body: reason, actor });
50824
- closingNote = {
50825
- id: message.id,
50826
- ref: dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id)
50697
+ return `it reached that session as ${attempt.delivery}`;
50698
+ }
50699
+ async function sendToAgentCommand(context) {
50700
+ const { args, client } = context;
50701
+ const session = stringArg(args, "session");
50702
+ const inReplyTo = optionalString(args, "in_reply_to");
50703
+ const message = await client.agentMessage(session, {
50704
+ body: stringArg(args, "body"),
50705
+ delivery: stringArg(args, "delivery"),
50706
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
50707
+ });
50708
+ const attempt = message.deliveries?.at(-1);
50709
+ const readBack = conversationReadBack(message.id);
50710
+ const arrival = arrivalText(attempt);
50711
+ return {
50712
+ text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
50713
+ details: {
50714
+ session,
50715
+ message: message.id,
50716
+ ...attempt === undefined ? {} : { delivery: attempt.state },
50717
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
50718
+ }
50719
+ };
50720
+ }
50721
+
50722
+ // ../envoy-client/src/dispatch-commands/documents.ts
50723
+ import { resolve as resolvePath2 } from "path";
50724
+
50725
+ // ../contracts/src/go-blank.ts
50726
+ var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
50727
+
50728
+ // ../envoy-client/src/dispatch-commands/documents.ts
50729
+ async function blockAsks(client, resolved, state) {
50730
+ const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
50731
+ return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
50732
+ }
50733
+ async function readUploadedFile(client, artifact, details, requested, owner, shown) {
50734
+ const versions = artifact.versions ?? [];
50735
+ const latest = Math.max(0, ...versions.map((version) => version.number));
50736
+ const number = requested ?? latest;
50737
+ const of = number === latest ? "" : ` of ${latest}`;
50738
+ const bytesRoute = `GET /api/v1/artifacts/${artifact.id}/versions/${number} serves its bytes.`;
50739
+ const tooLarge = (mime, bytes) => ({
50740
+ text: `${oversizePictureText(artifact.name, bytes)}, so dispatch doc-read cannot show this ` + `uploaded ${mime} picture (version ${number}${of}). ${bytesRoute}`,
50741
+ details
50742
+ });
50743
+ const stated = versions.find((version) => version.number === number);
50744
+ if (artifact.kind === "image" && stated?.size !== undefined && stated.size > PICTURE_SHOWN_MAX_BYTES) {
50745
+ return tooLarge(stated.mime ?? "image", stated.size);
50746
+ }
50747
+ const file = await client.fileVersion(artifact.id, number);
50748
+ const size = `${file.bytes.length.toLocaleString("en-US")} bytes`;
50749
+ if (artifact.kind === "image") {
50750
+ const image = toolImage(file.bytes);
50751
+ if (image !== undefined) {
50752
+ const address = `dispatch://${owner}/artifact/${artifact.slug}@v${number}`;
50753
+ shown?.add(address);
50754
+ return {
50755
+ text: `Picture ${artifact.name}: ${image.mimeType}, version ${number}${of}, ${size}.
50756
+ ` + shownPictureLine(1, address, artifact.name, image.mimeType, file.bytes.length),
50757
+ details,
50758
+ images: [image]
50827
50759
  };
50828
- } catch (error) {
50829
- if (error instanceof DispatchWriteLandedError) {
50830
- throw new Error(`${error.message} That was the closing reason, so the close was not sent: read the issue's messages for it, then close with a reason that points at it, since retrying this call posts its reason again.`, { cause: error });
50760
+ }
50761
+ if (sniffPictureType(file.bytes) !== undefined)
50762
+ return tooLarge(file.mime, file.bytes.length);
50763
+ }
50764
+ let text;
50765
+ try {
50766
+ text = new TextDecoder("utf-8", { fatal: true }).decode(file.bytes);
50767
+ } catch {
50768
+ return {
50769
+ text: `${artifact.name} is an uploaded ${file.mime} file (version ${number}${of}, ${size}) that is not ` + `UTF-8 text, so dispatch doc-read cannot show it. ${bytesRoute}`,
50770
+ details
50771
+ };
50772
+ }
50773
+ return {
50774
+ text: `File ${artifact.name}: ${file.mime}, version ${number}${of}, ${size}.
50775
+
50776
+ ${text}`,
50777
+ details
50778
+ };
50779
+ }
50780
+ var BLOCK_OPENING_CHARS = 60;
50781
+ async function listDocumentBlocks(client, artifact) {
50782
+ const live = await liveBlocks(client, artifact);
50783
+ const { bytes, blocks } = live;
50784
+ const decoder = new TextDecoder;
50785
+ const lines = [
50786
+ `Blocks of ${artifact.name}, in document order, each indented under the block holding it: id, type, (token; anchored comments and asks), opening words, then a typed block's serves and needs. A table lists its rows by the index delete_row takes and its cells by the row and the column delete_column takes.`
50787
+ ];
50788
+ const holders = [];
50789
+ for (const block of blocks) {
50790
+ while (holders.length > 0 && block.from >= (holders.at(-1)?.to ?? 0))
50791
+ holders.pop();
50792
+ const indent = " ".repeat(holders.length);
50793
+ const flat = decoder.decode(bytes.subarray(block.from, block.to)).replace(/\s+/g, " ").trim();
50794
+ const points = Array.from(flat);
50795
+ const opening = points.length > BLOCK_OPENING_CHARS ? `${points.slice(0, BLOCK_OPENING_CHARS).join("")}\u2026` : flat;
50796
+ const { comments, asks } = block.references;
50797
+ lines.push(`${indent}${block.id} ${block.type} (${block.token ?? "no token"}; ${comments} comment${comments === 1 ? "" : "s"}, ${asks} ask${asks === 1 ? "" : "s"}): ${opening}`);
50798
+ for (const attribute of block.attributes ?? []) {
50799
+ if (attribute.kind === "block[]" && attribute.value !== "") {
50800
+ lines.push(`${indent} ${attribute.name}: ${attribute.value}`);
50831
50801
  }
50832
- const told = writeMayHaveLanded(error) ? "the reason may or may not have been posted, and the close was not sent: read the issue's messages before retrying, since retrying this call posts its reason again" : "the reason was not posted, so the close was not sent";
50833
- if (error instanceof DispatchServiceError)
50834
- throw refusalWithCode(error, told);
50835
- throw withAccount(error, told);
50836
50802
  }
50837
- }
50838
- const existingLinks = before.external_links ?? [];
50839
- const linked = existingLinks.map((link) => link.url);
50840
- const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
50841
- const sentLinks = requestedLinks === undefined ? undefined : requestedLinks.length === 0 ? [] : [...existingLinks, ...newLinks.map((url) => ({ url }))];
50842
- const rank = rankBefore === undefined && rankAfter === undefined ? undefined : {
50843
- ...rankBefore === undefined ? {} : { before: rankBefore },
50844
- ...rankAfter === undefined ? {} : { after: rankAfter }
50845
- };
50846
- let after;
50847
- try {
50848
- after = await client.updateIssue(issueKey, {
50849
- ...status === undefined ? {} : { status },
50850
- ...title === undefined ? {} : { title },
50851
- ...labels === undefined ? {} : { labels },
50852
- ...priority === undefined ? {} : { priority },
50853
- ...assignee === undefined ? {} : { assignee },
50854
- ...route === undefined ? {} : { route },
50855
- ...parent === undefined ? {} : { parent: parent === "" ? null : parent },
50856
- ...blockedBy === undefined ? {} : { blocked_by: blockedBy },
50857
- ...advancesWrite,
50858
- ...components === undefined ? {} : { components },
50859
- ...repo === undefined ? {} : { repo: repo === "" ? null : repo },
50860
- ...sentLinks === undefined ? {} : { external_links: sentLinks },
50861
- ...rank === undefined ? {} : { rank },
50862
- actor
50863
- });
50864
- } catch (error) {
50865
- if (error instanceof DispatchWriteLandedError)
50866
- throw error;
50867
- const answered = error instanceof DispatchWriteUnsettledError ? error.last : error;
50868
- const taken = dispatchAnswered(answered, 500) && newLinks.length > 0 ? `one of ${newLinks.join(", ")} may already be linked from another issue (a URL links exactly one issue)` : "";
50869
- if (closingNote === undefined) {
50870
- if (taken !== "" && !(error instanceof DispatchServiceError)) {
50871
- throw withAccount(error, taken);
50803
+ if (block.type === "table") {
50804
+ if (block.table === undefined) {
50805
+ lines.push(`${indent} This Dispatch does not report table rows yet, so no row or column index is listed.`);
50806
+ } else {
50807
+ for (const row of block.table.rows ?? []) {
50808
+ lines.push(`${indent} row ${row.index}, ${row.id === "" ? "no id yet" : `id ${row.id}`}`);
50809
+ for (const cell of row.cells ?? []) {
50810
+ const under = cell.header === "" ? "" : `, under ${JSON.stringify(cell.header)}`;
50811
+ lines.push(`${indent} row ${cell.row} column ${cell.column}, ${cell.id === "" ? "no id yet" : `id ${cell.id}`}${under}: ${cell.text === "" ? "(empty)" : cell.text}`);
50812
+ }
50813
+ }
50814
+ }
50815
+ }
50816
+ holders.push(block);
50817
+ }
50818
+ return { text: lines.join(`
50819
+ `), token: live.token, version: live.version };
50820
+ }
50821
+ async function refuseOpenDecisionBlocks(client, tool, resolved) {
50822
+ const artifact = resolved.artifact;
50823
+ const latest = artifact.approval?.latest_version;
50824
+ if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
50825
+ return;
50826
+ const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
50827
+ if (blocks.length === 0)
50828
+ return;
50829
+ const [documentAsks, version] = await Promise.all([
50830
+ blockAsks(client, resolved),
50831
+ client.docRead(artifact.id, latest)
50832
+ ]);
50833
+ const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
50834
+ const lines = version.markdown.split(`
50835
+ `);
50836
+ const stillOpen = (named, state) => state === "answered" ? `${named}, answered but still open in version ${latest}: it settles into a version on its own in about two seconds; wait for that version` : `${named}, ${state} but still open in version ${latest}: write the decision into the text with dispatch doc-edit, which writes a version that carries it`;
50837
+ const open = blocks.flatMap((block) => {
50838
+ const ask = asks.get(block.id);
50839
+ const id = typedBlockIdAttribute(block.id);
50840
+ const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
50841
+ const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
50842
+ const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
50843
+ if (states.length === 0)
50844
+ return [`${named}, which version ${latest} does not hold yet`];
50845
+ if (!states.includes("open") && states.some((state) => state !== undefined))
50846
+ return [];
50847
+ if (ask !== undefined)
50848
+ return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
50849
+ const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
50850
+ const sourceId = attribute("copied_from");
50851
+ const document = attribute("copied_from_document");
50852
+ if (sourceId === undefined || document === undefined) {
50853
+ return [`${named}, whose ask Dispatch has not opened yet`];
50854
+ }
50855
+ const source = parseDispatchRef(document);
50856
+ const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
50857
+ const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
50858
+ return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
50859
+ });
50860
+ if (open.length === 0)
50861
+ return;
50862
+ const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
50863
+ throw new Error([
50864
+ `dispatch ${commandName(tool)} was not called: ${artifact.name} (version ${latest}) has ${count}. Answering one writes a new version, which would move this request to that version and leave it waiting on you.`,
50865
+ ...open.map((line) => `- ${line}`),
50866
+ "Do not request approval over an open block, even when a human asked for it. Tell the human which block is open and ask them to answer it or to waive it. Once it is answered, it settles into a version on its own in about two seconds. When the human approved an earlier version and their answer is the whole change since it, Dispatch carries the approval to the new version in their name: request nothing. When the answer changes design text outside the block, rewrite that text (never to restate the answer), then request approval again once the human has agreed to every point in the new version, with a one-sentence --summary naming what changed since the earlier approval. On a document nobody has approved, wait for that version, then request. If they waive it, close the block with dispatch resolve-ask (--kind resolved, their words as the --reason), write their decision into the text with dispatch doc-edit, then request approval again once the human has agreed to every point in the new version. The call opens the request, or hands an open one back to the human."
50867
+ ].join(`
50868
+ `));
50869
+ }
50870
+ async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
50871
+ const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
50872
+ if (removing.length === 0)
50873
+ return;
50874
+ const artifact = resolved.artifact;
50875
+ const blocks = await client.artifactBlocks(artifact.id);
50876
+ const askBlocks = blocks.filter((block) => block.type === "ask");
50877
+ const removed = new Set;
50878
+ for (const operation of removing) {
50879
+ const target = blocks.find((block) => block.id === operation.block);
50880
+ if (target === undefined)
50881
+ continue;
50882
+ for (const block of askBlocks) {
50883
+ if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
50884
+ removed.add(block.id);
50872
50885
  }
50873
- throw refusalWithCode(error, taken);
50874
50886
  }
50875
- const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
50876
- const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
50877
- const landed = writeMayHaveLanded(error) ? `${posted}, and the close may or may not have taken effect. Read the issue's status before retrying: done means it closed; otherwise retry with a reason that points at message ${closingNote.id}, since retrying this call posts its reason again` : `${posted} but the issue did not close. Retrying this call posts its reason again, so ${fix}retry with a reason that points at message ${closingNote.id}`;
50878
- if (error instanceof DispatchServiceError)
50879
- throw refusalWithCode(error, taken, landed);
50880
- throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
50881
50887
  }
50882
- refuseUnsavedRepository("updated", after, repo);
50883
- const links = after.external_links ?? [];
50884
- const linkCount = `(${links.length} ${links.length === 1 ? "link" : "links"})`;
50885
- const stated = (after.advances ?? []).filter((advance) => !advance.inherited).map((advance) => advance.id);
50886
- const changes = [
50887
- ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
50888
- ...status === undefined ? [] : [`status ${before.status} -> ${after.status}`],
50889
- ...title === undefined ? [] : [`title "${after.title}"`],
50890
- ...labels === undefined ? [] : [
50891
- (after.labels ?? []).length === 0 ? "labels cleared" : `labels ${(after.labels ?? []).join(", ")}`
50892
- ],
50893
- ...priority === undefined ? [] : [after.priority === null ? "priority cleared" : `priority -> P${after.priority}`],
50894
- ...assignee === undefined ? [] : [after.assignee === null ? "assignee cleared" : `assignee -> ${after.assignee}`],
50895
- ...rank === undefined ? [] : [
50896
- `rank -> ${[
50897
- ...rankAfter === undefined ? [] : [`after ${rankAfter}`],
50898
- ...rankBefore === undefined ? [] : [`before ${rankBefore}`]
50899
- ].join(", ")}`
50900
- ],
50901
- ...requestedLinks === undefined ? [] : [
50902
- requestedLinks.length === 0 ? "external links cleared" : newLinks.length === 0 ? `already linked ${requestedLinks.join(", ")} ${linkCount}` : `linked ${newLinks.join(", ")} ${linkCount}`
50903
- ],
50904
- ...route === undefined ? [] : [after.route === null ? "route cleared" : `route ${after.route}`],
50905
- ...parent === undefined ? [] : [after.parent === null ? "parent cleared" : `parent -> ${after.parent}`],
50906
- ...blockedBy === undefined ? [] : [
50907
- (after.blocked_by ?? []).length === 0 ? "blocked_by cleared" : `blocked by ${(after.blocked_by ?? []).join(", ")}`
50908
- ],
50909
- ...advances === undefined ? [] : [stated.length === 0 ? "advances cleared" : `advances ${stated.join(", ")}`],
50910
- ...components === undefined ? [] : [componentsChange(components, after.components)],
50911
- ...repo === undefined ? [] : [
50912
- after.repo === null ? `repo cleared (resolves to ${after.resolved_repo ?? "none"})` : `repo -> ${after.repo}`
50913
- ]
50914
- ];
50915
- const adviceLines = renderAdvice(input.tool, after.key, after.advice, {
50916
- setsStatus: status !== undefined
50888
+ if (removed.size === 0)
50889
+ return;
50890
+ const asks = await blockAsks(client, resolved, "open");
50891
+ const open = asks.filter((ask) => removed.has(ask.block_id));
50892
+ if (open.length === 0)
50893
+ return;
50894
+ const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
50895
+ throw new Error([
50896
+ `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
50897
+ ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
50898
+ "A decision block leaves the document once its ask is answered or resolved. Until then, reword it with replace, relocate it with move, or change its question, options, urgency or multiple with dispatch edit-ask if you asked it; each keeps it."
50899
+ ].join(`
50900
+ `));
50901
+ }
50902
+ async function docEditCommand(context) {
50903
+ const { args, client, actor, input, linkBase, documentOwner, resolveDocument } = context;
50904
+ const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
50905
+ const ops = args.ops;
50906
+ const summary = optionalString(args, "summary");
50907
+ const { precondition: rawPrecondition } = args;
50908
+ const precondition = rawPrecondition;
50909
+ await refuseRemovingOpenDecisionBlocks(client, input.tool, resolved, ops);
50910
+ const edited = await client.docEdit(resolved.artifact.id, {
50911
+ ops,
50912
+ ...summary === undefined ? {} : { summary },
50913
+ ...precondition === undefined ? {} : { precondition },
50914
+ actor
50915
+ });
50916
+ const retyped = ops.filter((operation) => operation.op === "retype").length;
50917
+ const versionText = edited.version === null ? "no new version" : `version ${edited.version.number}`;
50918
+ const retypedText = retyped === 0 ? "" : `; retyped ${retyped} block${retyped === 1 ? "" : "s"}`;
50919
+ const nothingChanged = edited.changed === false;
50920
+ const head = nothingChanged ? `Applied ${edited.applied} ops${retypedText}; nothing changed (${versionText})` : `Applied ${edited.applied} ops${retypedText} (${versionText})`;
50921
+ const unchangedOps = edited.unchanged_ops ?? [];
50922
+ const unchangedText = unchangedOps.length === 0 ? "" : `; ${unchangedOps.length === 1 ? "operation" : "operations"} ${unchangedOps.join(", ")} changed nothing`;
50923
+ const lostOps = edited.lost_ops;
50924
+ const lostText = lostOps === undefined || lostOps !== null && lostOps.length === 0 ? "" : lostOps === null ? "; could not confirm this edit survived, because the live document is being reloaded or holds a tree too deep to read \u2014 re-read it" : `; ${versionText} carries text the live document no longer has: a concurrent change removed what ${lostOps.length === 1 ? "operation" : "operations"} ${lostOps.join(", ")} wrote \u2014 re-read the document`;
50925
+ const applied = `${head}${unchangedText}${lostText}`;
50926
+ const editAskText = ops.map((operation) => /^:{3,}ask\{.*\n([\s\S]*)/mu.exec(operation.markdown ?? operation.with ?? "")?.[1]).find((text) => text !== undefined) ?? resolved.issue?.title ?? "";
50927
+ const checkLines = decisionBlockLines(edited.advice, {
50928
+ project: resolved.artifact.project,
50929
+ text: editAskText,
50930
+ linkBase
50917
50931
  });
50932
+ const declinedLines = resolved.issue === undefined ? [] : declinedAskLines(edited.advice, resolved.issue.key, linkBase);
50933
+ const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, resolvedTopic(resolved).label, edited.advice, {
50934
+ isPlan: documentPlaysPlan(resolved.artifact)
50935
+ }));
50936
+ const written = edited.written;
50937
+ const writtenLines = written === undefined || written === "" ? [] : [written];
50938
+ const tokenTrailer = edited.token === undefined ? [] : [`Document token: ${edited.token}`];
50918
50939
  return {
50919
50940
  text: [
50920
- `${after.key}: ${changes.join("; ")}${await notSubscribed(issueTopic(after.key), input.subscriptions)}`,
50941
+ `${applied}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
50942
+ ...checkLines,
50943
+ ...declinedLines,
50944
+ ...writtenLines,
50945
+ ...tokenTrailer,
50921
50946
  ...adviceLines
50922
50947
  ].join(`
50923
50948
  `),
50924
- details: {
50925
- issue: after.key,
50926
- status: after.status,
50927
- external_links: (after.external_links ?? []).map((link) => link.url),
50928
- ...closingNote === undefined ? {} : { message: closingNote.id },
50929
- ...after.advice === undefined ? {} : { advice: after.advice }
50930
- }
50949
+ details: writeResultDetails(resolved, {
50950
+ applied: edited.applied,
50951
+ ...edited.version === null ? {} : { version: edited.version.number },
50952
+ ...nothingChanged ? { changed: false } : {},
50953
+ ...lostOps === undefined ? {} : { lost_ops: lostOps },
50954
+ ...edited.token === undefined ? {} : { token: edited.token },
50955
+ ...edited.advice === undefined ? {} : { advice: edited.advice }
50956
+ })
50931
50957
  };
50932
50958
  }
50933
- async function claimCommand(context) {
50934
- const { args, client, actor, input, issue } = context;
50935
- const issueKey = issue();
50936
- const release = optionalBoolean(args, "release") ?? false;
50937
- let after;
50938
- try {
50939
- after = release ? await client.releaseIssueClaim(issueKey, { actor }) : await client.claimIssue(issueKey, { actor });
50940
- } catch (error) {
50941
- throw refusalWithCode(error);
50959
+ async function docReadCommand(context) {
50960
+ const { args, client, ownerArguments, shown, documentOwner, resolveDocument } = context;
50961
+ const { agentArtifact } = ownerArguments;
50962
+ if (agentArtifact !== undefined) {
50963
+ const artifact = await client.getAgentArtifact(agentArtifact.session, agentArtifact.slug);
50964
+ if (optionalBoolean(args, "blocks") === true) {
50965
+ throw new Error(`${artifact.name} is an uploaded ${artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
50966
+ }
50967
+ return readUploadedFile(client, artifact, { session: agentArtifact.session, artifact: artifact.slug }, optionalNumber(args, "version") ?? agentArtifact.version, `agent/${agentArtifact.session}`, shown);
50942
50968
  }
50943
- const held = after.claim;
50944
- const legionManaged = after.legion_managed_status === true;
50945
- let text;
50946
- if (release) {
50947
- const released = `${issueKey}: claim released; nobody is working it now. Its status is still ${after.status}`;
50948
- text = legionManaged ? `${released}; ${LEGION_OWNS_STATUS}` : `${released} \u2014 move it yourself if that is no longer where the work is.`;
50949
- } else {
50950
- if (held === null) {
50951
- throw new Error(`Dispatch claimed ${issueKey} but answered with no claim`);
50969
+ const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
50970
+ const resolved = await resolveDocument(documentOwner(), artifactReference);
50971
+ const version = optionalNumber(args, "version") ?? ownerArguments.ref?.version;
50972
+ if (optionalBoolean(args, "blocks") === true) {
50973
+ if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
50974
+ throw new Error(`${resolved.artifact.name} is an uploaded ${resolved.artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
50952
50975
  }
50953
- const claimed = `${issueKey}: claimed by you since ${held.at}. Its status is ${after.status}`;
50954
- const reaches = `A person's answers, comments and messages on ${issueKey} now reach you directly.`;
50955
- text = legionManaged ? `${claimed}; ${LEGION_OWNS_STATUS} Release the claim when you stop. ${reaches}` : `${claimed}; a claim moves nothing, so move it to in_progress with dispatch issue-update when you start, and release the claim when you stop. ${reaches}`;
50976
+ const listed = await listDocumentBlocks(client, resolved.artifact);
50977
+ const trailer = [
50978
+ ...listed.token === undefined ? [] : [`Document token: ${listed.token}`],
50979
+ `Document version: ${listed.version === null ? "none yet" : listed.version}`
50980
+ ];
50981
+ return {
50982
+ text: `${listed.text}
50983
+
50984
+ ${trailer.join(`
50985
+ `)}`,
50986
+ details: resolved.owner.kind === "project" ? {
50987
+ project: resolved.artifact.project,
50988
+ document: documentLabel(resolved.artifact.project, resolved.artifact.slug)
50989
+ } : { issue: resolved.issue?.key }
50990
+ };
50956
50991
  }
50992
+ if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
50993
+ const { artifact } = resolved;
50994
+ return readUploadedFile(client, artifact, resolved.owner.kind === "project" ? {
50995
+ project: artifact.project,
50996
+ document: documentLabel(artifact.project, artifact.slug)
50997
+ } : { issue: resolved.issue?.key }, version, resolved.owner.kind === "project" ? resolved.owner.project : resolved.owner.issue, shown);
50998
+ }
50999
+ const documentPromise = client.docRead(resolved.artifact.id, version);
51000
+ const threadsPromise = openAnchoredThreads(client, resolved);
51001
+ const threadsResultPromise = threadsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
51002
+ const document = await documentPromise;
51003
+ const threadsResult = await threadsResultPromise;
51004
+ if (threadsResult.status === "rejected")
51005
+ throw threadsResult.reason;
51006
+ const threads = threadsResult.value;
51007
+ const approval = approvalLine(resolved.artifact, typeof resolved.issue?.closed_at === "string");
51008
+ const trailer = [
51009
+ ..."token" in document && document.token !== undefined ? [`Document token: ${document.token}`] : [],
51010
+ ..."sha256" in document && document.sha256 !== undefined ? [`Content: sha256:${document.sha256}`] : [],
51011
+ ...approval === undefined ? [] : [approval]
51012
+ ];
50957
51013
  return {
50958
- text: `${text}${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
50959
- details: { issue: issueKey, status: after.status, claim: held }
50960
- };
50961
- }
50962
- async function searchCommand(context) {
50963
- const { args, client, linkBase } = context;
50964
- const query = stringArg(args, "query");
50965
- const project = optionalString(args, "project");
50966
- const limit = optionalNumber(args, "limit");
50967
- const offset = optionalNumber(args, "offset");
50968
- const search = await client.search(query, {
50969
- ...project === undefined ? {} : { project },
50970
- ...limit === undefined ? {} : { limit },
50971
- ...offset === undefined ? {} : { offset }
50972
- });
50973
- return searchAnswer(search, query, offset, linkBase);
50974
- }
50975
- async function relatedCommand(context) {
50976
- const { args, client, linkBase } = context;
50977
- const project = stringArg(args, "project");
50978
- const title = optionalString(args, "title");
50979
- const text = optionalString(args, "text");
50980
- const excludeIssues = optionalStringArray(args, "exclude_issues");
50981
- const keywordsOnly = optionalBoolean(args, "keywords_only");
50982
- const suggestions = await client.related(project, {
50983
- ...title === undefined ? {} : { title },
50984
- ...text === undefined ? {} : { text },
50985
- ...excludeIssues === undefined ? {} : { exclude_issues: excludeIssues },
50986
- ...keywordsOnly === undefined ? {} : { keywords_only: keywordsOnly }
50987
- });
50988
- return {
50989
- text: relatedCheckLines(suggestions, {
50990
- project,
50991
- text: [title, text].filter((part) => part !== undefined).join(`
50992
- `),
50993
- linkBase
50994
- }).join(`
51014
+ text: [
51015
+ document.markdown,
51016
+ ...trailer.length === 0 ? [] : [trailer.join(`
51017
+ `)],
51018
+ ...threads.length === 0 ? [] : ["Open anchored threads:", ...threads]
51019
+ ].join(`
51020
+
50995
51021
  `),
50996
- details: { project, suggestions }
51022
+ details: resolved.owner.kind === "project" ? {
51023
+ project: resolved.artifact.project,
51024
+ document: `${resolved.artifact.project}/${resolved.artifact.slug}`
51025
+ } : { issue: resolved.issue?.key }
50997
51026
  };
50998
51027
  }
50999
- async function issuesCommand(context) {
51000
- const { args, client } = context;
51001
- const project = stringArg(args, "project");
51002
- const status = optionalString(args, "status");
51003
- const parent = optionalString(args, "parent");
51004
- const label = optionalString(args, "label");
51005
- const priority = optionalPriorityFilter(args, "priority");
51006
- const updatedSince = optionalString(args, "updated_since");
51007
- const routeStatus = optionalString(args, "route_status");
51008
- const filters = {
51009
- project,
51010
- ...status === undefined ? {} : { status },
51011
- ...parent === undefined ? {} : { parent },
51012
- ...label === undefined ? {} : { label },
51013
- ...priority === undefined ? {} : { priority },
51014
- ...updatedSince === undefined ? {} : { updated_since: updatedSince },
51015
- ...routeStatus === undefined ? {} : { route_status: routeStatus }
51016
- };
51017
- const page = optionalBoolean(args, "all") === true ? await client.listAllIssues(filters).then((issues) => ({
51018
- issues,
51019
- total: issues.length,
51020
- limit: issues.length,
51021
- offset: 0
51022
- })) : await client.listIssuePage(filters, {
51023
- limit: optionalNumber(args, "limit") ?? DEFAULT_ISSUE_PAGE_LIMIT,
51024
- offset: optionalNumber(args, "offset") ?? 0
51028
+ async function requestApprovalCommand(context) {
51029
+ const { args, client, actor, input, ownerArguments, documentOwner, resolveDocument } = context;
51030
+ const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
51031
+ const resolved = await resolveDocument(documentOwner(), artifactReference);
51032
+ await refuseOpenDecisionBlocks(client, input.tool, resolved);
51033
+ const includeVerification = optionalBoolean(args, "include_verification") === true;
51034
+ const result = await client.requestApproval(resolved.artifact.id, {
51035
+ actor,
51036
+ summary: stringArg(args, "summary"),
51037
+ ...includeVerification ? { include_verification: true } : {}
51025
51038
  });
51026
- const { total, limit, offset } = page;
51027
- const rows = (page.issues ?? []).map((row) => ({
51028
- key: row.key,
51029
- title: row.title,
51030
- status: row.status,
51031
- priority: row.priority,
51032
- parent: row.parent,
51033
- labels: row.labels ?? [],
51034
- open_asks: row.open_asks,
51035
- claim: row.claim ?? null,
51036
- route: row.route ?? null,
51037
- route_status: row.route_status ?? null,
51038
- route_holder: row.route_holder ?? null,
51039
- route_status_reason: row.route_status_reason ?? null,
51040
- updated_at: row.updated_at,
51041
- progress: row.progress
51042
- }));
51043
- const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
51044
- const isPartial = offset !== 0 || rows.length !== total;
51045
- const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
51039
+ const gaps = result.coverage ?? [];
51040
+ const coverageLines = result.coverage_unread ? [
51041
+ `Coverage of ${resolved.artifact.name}: unread. Dispatch could not read what the spec's requirements lack, so no line here says there is no gap; the request is recorded either way. Read the coverage again with dispatch read --issue, and mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
51042
+ ] : gaps.length === 0 ? [] : [
51043
+ `Coverage of ${resolved.artifact.name}: ${gaps.map((gap) => `${gap}.`).join(" ")} Mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
51044
+ ];
51045
+ if (result.ask === null) {
51046
+ return {
51047
+ text: [
51048
+ `${resolved.artifact.name} (document id ${resolved.artifact.id}) is already approved at version ${result.version} by ${result.approval.by?.id ?? "unknown"}; no new request was opened. A change outside the decision blocks after approval makes it stale, so request again only for such a version, once the human has agreed to every point in it, with a --summary naming what changed since version ${result.version}; the human's own answer to a decision block carries the approval when that answer is the whole change.`,
51049
+ ...coverageLines
51050
+ ].join(`
51051
+ `),
51052
+ details: {
51053
+ ...resolved.owner.kind === "project" ? documentResultDetails(resolved.artifact) : { issue: resolved.issue?.key },
51054
+ artifact: resolved.artifact.id,
51055
+ version: result.version
51056
+ }
51057
+ };
51058
+ }
51059
+ const details = await followedAskDetails(client, result.ask, resolved.artifact);
51060
+ const outcome = result.recorded ? `Approval requested for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}).` : `The approval request for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}) already waits on the human, so this call changed nothing: nothing since it last reached the human (a newer version, a human's reply in its thread, or your progress note) left it waiting on you.`;
51061
+ const waitsOn = waitsOnPerson(result.ask);
51046
51062
  return {
51047
- text: rows.length === 0 ? `No issues in ${project}.${isPartial ? ` (${showing})` : ""}` : [
51048
- `${rows.length} ${rows.length === 1 ? "issue" : "issues"} in ${project}` + (isPartial ? ` (${showing})` : ""),
51049
- ...rows.map((row) => {
51050
- const progress = progressText(row.progress, " \xB7 ");
51051
- return `${row.key} [${row.status}]${row.priority === null ? "" : ` P${row.priority}`} ${row.title}` + (row.open_asks === 0 ? "" : ` \xB7 ${row.open_asks} open ${row.open_asks === 1 ? "ask" : "asks"}`) + (row.claim === null ? "" : ` \xB7 claimed by ${claimText(row.claim, agents)}`) + (progress === "" ? "" : ` \xB7 ${progress}`) + (row.route === null || row.route_status === "live" || row.route_status === null ? "" : ` \xB7 route ${routeText(row)}`);
51052
- })
51063
+ text: [
51064
+ `${outcome}${waitsOn === undefined ? "" : ` It waits on ${waitsOn}.`} The human's Inbox asks: ${JSON.stringify(result.ask.question)}. The answer arrives as artifact.approved or artifact.changes_requested. An edit before the answer moves this request to the new version and leaves it waiting on you, and a change outside the decision blocks after approval makes the approval stale: either way, request again for the new version once the human has agreed to every point in it, which hands this request back or opens a new one, with a --summary naming what changed since the earlier approval. The human's own answer to a decision block carries the approval when that answer is the whole change since the approved version, and answers an open request Approve in their name: request nothing then.`,
51065
+ ...coverageLines
51053
51066
  ].join(`
51054
51067
  `),
51055
- details: { issues: rows, total, offset, limit }
51068
+ details: { ...details, artifact: resolved.artifact.id, version: result.version }
51056
51069
  };
51057
51070
  }
51058
- var BRIEF_READING_CHARACTERS = 200;
51059
- var COMPARISON_REASONS = {
51060
- no_pull_request_or_branch: "the issue has no pull request and no branch to compare with",
51061
- repository_unreadable: "Dispatch cannot read the repository",
51062
- read_failed: "a read Dispatch made did not answer"
51063
- };
51064
- function learnedText(learned) {
51065
- if (learned.kind === "read_at")
51066
- return `Dispatch read it ${learned.at}`;
51067
- return `GitHub updated it ${learned.at}`;
51068
- }
51069
- function basisText(basis) {
51070
- const learned = basis.learned_at === undefined ? "" : ` (${learnedText(basis.learned_at)})`;
51071
- if (basis.kind === "pull_request") {
51072
- const number = basis.pull_request === undefined ? "" : `#${basis.pull_request} `;
51073
- return `the head of pull request ${number}at ${basis.commit ?? "an unnamed commit"}${learned}`;
51074
- }
51075
- if (basis.kind === "branch")
51076
- return `branch ${basis.branch ?? "unnamed"}${learned}`;
51077
- return `the commit you named, ${basis.commit ?? ""}${learned}`;
51071
+ async function planApproveCommand(context) {
51072
+ const { args, client, actor, documentOwner, resolveDocument } = context;
51073
+ const planOwner = documentOwner();
51074
+ const named = optionalString(args, "artifact");
51075
+ const byRole = named === undefined && planOwner.kind === "issue" ? (await client.getIssue(planOwner.issue)).plan_artifact_id ?? "" : "";
51076
+ const resolved = await resolveDocument(planOwner, named ?? (byRole || "plan.md"));
51077
+ const version = numberArg(args, "version");
51078
+ const review = await client.planApprove(resolved.artifact.id, { actor, version });
51079
+ return {
51080
+ text: `The plan review approved ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${review.version}; no human is asked to approve a plan. A later plan version makes this approval stale: run the review again and record it the same way.`,
51081
+ details: {
51082
+ issue: resolved.issue?.key,
51083
+ artifact: resolved.artifact.id,
51084
+ version: review.version
51085
+ }
51086
+ };
51078
51087
  }
51079
- function basisPlace(basis) {
51080
- if (basis.kind === "pull_request") {
51081
- return basis.pull_request === undefined ? "the head of a pull request" : `the head of pull request #${basis.pull_request}`;
51082
- }
51083
- if (basis.kind === "branch")
51084
- return `on branch ${basis.branch ?? "unnamed"}`;
51085
- return "the commit you named";
51088
+ function artifactUnderName(artifacts, name) {
51089
+ const written = name.trim();
51090
+ return artifacts.find((held) => held.slug === written) ?? artifacts.find((held) => held.name === written);
51086
51091
  }
51087
- function commitStandsText(stands) {
51088
- if (stands === undefined) {
51089
- return "Where that commit stands is not known: this Dispatch server does not say";
51090
- }
51091
- if (stands.answer === "at_basis") {
51092
- return stands.basis === undefined ? "That commit is one of the compared commits" : `That commit is ${basisPlace(stands.basis)}`;
51092
+ function artifactNameExistsProblem(held, owner) {
51093
+ const versions = held.versions ?? [];
51094
+ const newest = versions[versions.length - 1];
51095
+ if (newest === undefined) {
51096
+ return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}), which has no version yet and which ${actorText(held.created_by)} created. ${ARTIFACT_NAME_EXISTS_RULE}`;
51093
51097
  }
51094
- if (stands.answer === "other_commit")
51095
- return "That commit is none of the compared commits";
51096
- return stands.reason === undefined ? "Where that commit stands is not known" : `Where that commit stands is not known: ${COMPARISON_REASONS[stands.reason]}`;
51098
+ const authors = (newest.authors ?? []).map(actorText);
51099
+ const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
51100
+ return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${ARTIFACT_NAME_EXISTS_RULE}`;
51097
51101
  }
51098
- function checkWordsText(check, result) {
51099
- const versions = `result version ${result.check_version}, check version ${check.version}`;
51100
- if (result.check_words_moved === undefined) {
51101
- return `Whether the check's words moved is not known (${versions})`;
51102
- }
51103
- return result.check_words_moved ? `The check's words moved after this result (${versions})` : `The check's words did not move after this result (${versions})`;
51102
+ var STORED_LINE_QUOTED = 200;
51103
+ function quotedStoredLine(line) {
51104
+ if (line.length <= STORED_LINE_QUOTED)
51105
+ return JSON.stringify(line);
51106
+ const head = JSON.stringify(line.slice(0, STORED_LINE_QUOTED));
51107
+ return `${head} (cut after ${STORED_LINE_QUOTED} of its ${line.length} characters)`;
51104
51108
  }
51105
- function passStandsText(pass) {
51106
- if (pass === undefined)
51107
- return "Whether a pass stands is not known: this Dispatch server does not say";
51108
- if (pass.answer === "yes") {
51109
- const roles = pass.roles ?? [];
51110
- return roles.length === 0 ? "A pass stands: yes" : `A pass stands: yes, from ${roles.join(", ")}`;
51109
+ function firstStoredDifference(given, stored) {
51110
+ const written = given.split(`
51111
+ `);
51112
+ const holds = stored.split(`
51113
+ `);
51114
+ for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
51115
+ const wrote = written[line];
51116
+ const held = holds[line];
51117
+ if (wrote === held)
51118
+ continue;
51119
+ if (wrote === undefined && held !== undefined) {
51120
+ return `the store writes a line ${line + 1}, ${quotedStoredLine(held)}`;
51121
+ }
51122
+ if (held === undefined && wrote !== undefined) {
51123
+ return `the store drops line ${line + 1}, ${quotedStoredLine(wrote)}`;
51124
+ }
51125
+ if (wrote !== undefined && held !== undefined) {
51126
+ return `line ${line + 1} reads ${quotedStoredLine(wrote)} and is stored as ${quotedStoredLine(held)}`;
51127
+ }
51111
51128
  }
51112
- if (pass.answer === "no")
51113
- return "A pass stands: no";
51114
- return "A pass stands: not known";
51129
+ return "the stored text differs from the text given";
51115
51130
  }
51116
- function readingLines(result, brief, indent = " ") {
51117
- const observed = result.observed;
51118
- if (observed === "")
51119
- return [`${indent}The role recorded no reading.`];
51120
- const cut = brief && result.commit_stands?.answer !== "at_basis";
51121
- if (cut && observed.length > BRIEF_READING_CHARACTERS) {
51122
- return [
51123
- `${indent}Reading: ${observed.slice(0, BRIEF_READING_CHARACTERS)}\u2026 (result ${result.id})`
51124
- ];
51125
- }
51126
- return [`${indent}Reading: ${observed}`];
51131
+ var STORED_TEXT_PRINTED = 2000;
51132
+ function storedTextPrinted(stored) {
51133
+ if (stored.length <= STORED_TEXT_PRINTED)
51134
+ return { text: stored, cut: "" };
51135
+ const head = stored.slice(0, STORED_TEXT_PRINTED);
51136
+ const lastLineFeed = head.lastIndexOf(`
51137
+ `);
51138
+ const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
51139
+ return {
51140
+ text,
51141
+ cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
51142
+ };
51127
51143
  }
51128
- function resultLines(check, result, brief) {
51129
- const lines = [
51130
- ` - ${result.verdict} by ${result.role} at ${result.commit_sha}. ${commitStandsText(result.commit_stands)}. ${checkWordsText(check, result)}. Recorded ${result.created_at}. Result ${result.id}.`
51131
- ];
51132
- const retracted = result.retracted;
51133
- if (retracted !== undefined) {
51134
- lines.push(` Retracted by ${actorText(retracted.actor)} at ${retracted.created_at}. The reason: ${retracted.reason}`);
51135
- }
51136
- return [...lines, ...readingLines(result, brief)];
51144
+ function storedTextProblem(given, stored, name) {
51145
+ const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
51146
+ const printed = storedTextPrinted(stored);
51147
+ return [
51148
+ `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
51149
+ ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
51150
+ `${printed.cut}
51151
+ --- the text Dispatch stores ---
51152
+ ${printed.text}`,
51153
+ "--- end of the text Dispatch stores ---"
51154
+ ].join("");
51137
51155
  }
51138
- function ciCheckLines(check, ci, brief) {
51139
- const passStandsLine = ` ${passStandsText(check.pass_stands)}.`;
51140
- const pullRequestLine = ` Pull request line: ${ci.line}`;
51141
- const derived = check.results?.[0];
51142
- if (derived === undefined) {
51143
- return [
51144
- `- ${check.block_id} (${check.when}): no result: ${ci.detail} ${check.text}`,
51145
- passStandsLine,
51146
- pullRequestLine
51147
- ];
51156
+ function storedTextCheckFailed(error, name) {
51157
+ 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)}.`;
51158
+ if (!dispatchAnswered(error, 413)) {
51159
+ return `${failure} Send the upload again once that call is answered.`;
51148
51160
  }
51149
- const stands = commitStandsText(derived.commit_stands);
51150
- return [
51151
- `- ${check.block_id} (${check.when}): ${derived.verdict} at ${derived.commit_sha} by ${derived.role} (CI run ${ci.run}, ${ci.case}), ${stands.charAt(0).toLowerCase()}${stands.slice(1)}. ${check.text}`,
51152
- passStandsLine,
51153
- pullRequestLine,
51154
- ...readingLines(derived, brief, " ")
51155
- ];
51161
+ const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
51162
+ 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}`;
51156
51163
  }
51157
- function checkLines(check, brief) {
51158
- if (check.ci !== undefined)
51159
- return ciCheckLines(check, check.ci, brief);
51160
- const bases = check.compared_with ?? [];
51161
- const reason = check.compared_nothing;
51162
- const compared = bases.length > 0 ? `Compared with ${bases.map(basisText).join(", ")}` : reason === undefined ? "Compared with nothing, and this Dispatch server does not say why" : `Compared with nothing: ${COMPARISON_REASONS[reason]}`;
51163
- const results = check.results ?? [];
51164
- return [
51165
- `- ${check.block_id} (${check.when}). ${compared}. ${passStandsText(check.pass_stands)}.`,
51166
- ` The check's words: ${check.text}`,
51167
- ...results.length === 0 ? [" No result is recorded for this check."] : results.flatMap((result) => resultLines(check, result, brief))
51168
- ];
51164
+ function roundTripRouteAbsent(error) {
51165
+ return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
51169
51166
  }
51170
- function formatCheckResults(results, brief = false) {
51171
- if (results.verification_artifact_id === "") {
51172
- return `${results.issue} has no Verification document, so it has no checks. Write one (verification.md) with a check block per thing that must be proved.`;
51167
+ function withoutFinalLineFeed(text) {
51168
+ return text.endsWith(`
51169
+ `) ? text.slice(0, -1) : text;
51170
+ }
51171
+ async function artifactCommand(context) {
51172
+ const { args, client, actor, input, documentOwner, issue } = context;
51173
+ const summary = optionalString(args, "summary");
51174
+ const name = stringArg(args, "name");
51175
+ const content = optionalString(args, "content");
51176
+ const path = optionalString(args, "path");
51177
+ const options = { name, ...summary === undefined ? {} : { summary }, actor };
51178
+ const artifactOwner = documentOwner();
51179
+ const blank = content === undefined || goBlankPattern.test(content);
51180
+ if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
51181
+ const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
51182
+ if (held !== undefined) {
51183
+ throw new ToolInputError(input.tool, [
51184
+ artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`)
51185
+ ]);
51186
+ }
51173
51187
  }
51174
- const checks = results.checks ?? [];
51175
- if (checks.length === 0) {
51176
- return `${results.issue}'s Verification document holds no check blocks.`;
51188
+ if (!blank) {
51189
+ let stored;
51190
+ try {
51191
+ stored = await client.markdownRoundTrip(content);
51192
+ } catch (error) {
51193
+ if (!roundTripRouteAbsent(error)) {
51194
+ throw new Error(storedTextCheckFailed(error, name), { cause: error });
51195
+ }
51196
+ }
51197
+ if (stored !== undefined && withoutFinalLineFeed(stored) !== withoutFinalLineFeed(content)) {
51198
+ throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
51199
+ }
51177
51200
  }
51178
- const blocks = checks.map((check) => checkLines(check, brief).join(`
51179
- `));
51180
- return [`Checks of ${results.issue}:`, ...blocks].join(`
51181
-
51182
- `);
51201
+ const artifactInput = path !== undefined ? {
51202
+ ...options,
51203
+ file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
51204
+ type: Bun.file(resolvePath2(input.cwd, path)).type
51205
+ })
51206
+ } : content !== undefined ? { ...options, content } : options;
51207
+ const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
51208
+ const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
51209
+ const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
51210
+ const adviceLines = renderAdvice(input.tool, uploadOwner.label, result.advice, {
51211
+ isPrimarySpec: result.artifact.primary || result.artifact.name === "spec.md",
51212
+ isPlan: documentPlaysPlan(result.artifact)
51213
+ });
51214
+ return {
51215
+ text: [
51216
+ path === undefined && content === undefined ? `Made ${result.artifact.name} as an empty document (artifact slug ${result.artifact.slug}; ${artifactRef}). Write in it with dispatch doc-edit.${await notSubscribed(uploadOwner, input.subscriptions)}` : `Uploaded ${result.artifact.name} as version ${result.version.number} (artifact slug ${result.artifact.slug}; ${artifactRef})${await notSubscribed(uploadOwner, input.subscriptions)}`,
51217
+ ...adviceLines
51218
+ ].join(`
51219
+ `),
51220
+ details: artifactOwner.kind === "project" ? {
51221
+ ...documentResultDetails(result.artifact),
51222
+ version: result.version.number,
51223
+ ...result.advice === undefined ? {} : { advice: result.advice }
51224
+ } : {
51225
+ issue: issue(),
51226
+ artifact: result.artifact.id,
51227
+ version: result.version.number,
51228
+ ...result.advice === undefined ? {} : { advice: result.advice }
51229
+ }
51230
+ };
51183
51231
  }
51184
- async function resultCommand(context) {
51185
- const { args, client, actor } = context;
51186
- const retract = optionalString(args, "retract");
51187
- if (retract !== undefined) {
51188
- const retraction = await client.retractResult(retract, {
51189
- actor,
51190
- reason: stringArg(args, "reason")
51191
- });
51192
- return {
51193
- text: `Retracted result ${retraction.result_id}. ${actorText(retraction.actor)} retracted it at ${retraction.created_at}. The reason: ${retraction.reason}
51194
51232
 
51195
- The result stays readable, and it proves nothing from now on. Record a new result where the check still needs one.`,
51196
- details: {
51197
- result: retraction.result_id,
51198
- reason: retraction.reason,
51199
- created_at: retraction.created_at
51200
- }
51201
- };
51233
+ // ../envoy-client/src/dispatch-commands/handoffs.ts
51234
+ async function handoffWriteCommand(context) {
51235
+ const { args, client, actor, input, issue } = context;
51236
+ if (!input.sessionId?.trim()) {
51237
+ throw new Error("host session id is required for dispatch handoff-write");
51202
51238
  }
51203
- const issue = stringArg(args, "issue");
51204
- const optional = {
51205
- ...defined("surface", optionalString(args, "surface")),
51206
- ...defined("run", optionalString(args, "run")),
51207
- ...defined("observed", optionalString(args, "observed")),
51208
- ...defined("negative_control", optionalString(args, "negative_control")),
51209
- ...defined("failed", optionalNumber(args, "failed")),
51210
- ...defined("skipped", optionalNumber(args, "skipped")),
51211
- ...defined("excluded", optionalNumber(args, "excluded")),
51212
- ...defined("screenshots", optionalStringArray(args, "screenshots"))
51213
- };
51214
51239
  let recorded;
51215
51240
  try {
51216
- recorded = await client.recordResult(issue, {
51241
+ recorded = await client.writeHandoff(issue(), stringArg(args, "phase"), {
51217
51242
  actor,
51218
- check: stringArg(args, "check"),
51219
- role: stringArg(args, "role"),
51220
- verdict: stringArg(args, "verdict"),
51221
- commit: stringArg(args, "commit"),
51222
- ...optional
51243
+ body: stringArg(args, "body")
51223
51244
  });
51224
51245
  } catch (error) {
51225
- if (dispatchAnswered(error, 409) && error.code === "CHECK_CONTENDED") {
51226
- throw refusalWithCode(error, "the check moved twice while this result was being written, and nothing was recorded: run the same dispatch result command again");
51227
- }
51228
- throw error;
51246
+ throw refusalWithCode(error);
51229
51247
  }
51230
51248
  return {
51231
- text: `Recorded ${recorded.result.verdict} for check ${recorded.result.check_block_id} of ${recorded.result.check_issue_key} at ${recorded.result.commit_sha}, as ${recorded.result.role}.
51232
-
51233
- Pull request body line:
51234
- ${recorded.line}`,
51249
+ text: `Recorded the ${recorded.phase} handoff of ${recorded.issue_key}, version ${recorded.version} (id ${recorded.id})`,
51235
51250
  details: {
51236
- issue,
51237
- result: recorded.result.id,
51238
- check: recorded.result.check_block_id,
51239
- verdict: recorded.result.verdict,
51240
- line: recorded.line
51251
+ issue: recorded.issue_key,
51252
+ phase: recorded.phase,
51253
+ version: recorded.version,
51254
+ handoff: recorded.id
51241
51255
  }
51242
51256
  };
51243
51257
  }
51244
- async function resultsCommand(context) {
51245
- const { args, client } = context;
51246
- const issue = stringArg(args, "issue");
51247
- const at = optionalString(args, "at");
51248
- const brief = optionalBoolean(args, "brief") === true;
51249
- const results = await client.issueResults(issue, at);
51250
- const checks = results.checks ?? [];
51258
+ async function handoffReadCommand(context) {
51259
+ const { args, client, issue } = context;
51260
+ const issueKey = issue();
51261
+ const phase = stringArg(args, "phase");
51262
+ const version = optionalNumber(args, "version");
51263
+ let handoff;
51264
+ try {
51265
+ if (version === undefined) {
51266
+ handoff = await client.latestHandoff(issueKey, phase);
51267
+ } else {
51268
+ const listed = await client.listHandoffs(issueKey);
51269
+ const ofPhase = listed.filter((summary) => summary.phase === phase);
51270
+ const match = ofPhase.find((summary) => summary.version === version);
51271
+ if (match === undefined) {
51272
+ const newest = Math.max(0, ...ofPhase.map((summary) => summary.version));
51273
+ throw new Error(`HANDOFF_NOT_FOUND: issue ${issueKey} has no ${phase} handoff version ${version}; ${newest === 0 ? `it has no ${phase} handoff at all` : `its newest ${phase} handoff is version ${newest}`}`);
51274
+ }
51275
+ handoff = await client.handoff(match.id);
51276
+ }
51277
+ } catch (error) {
51278
+ throw refusalWithCode(error);
51279
+ }
51251
51280
  return {
51252
- text: formatCheckResults(results, brief),
51281
+ text: `${handoff.issue_key} ${handoff.phase} handoff, version ${handoff.version} (id ${handoff.id}), written by ${actorText(handoff.author)} at ${handoff.created_at}
51282
+ ${handoff.body}`,
51253
51283
  details: {
51254
- issue,
51255
- checks: checks.length,
51256
- results: checks.reduce((total, check) => total + (check.results ?? []).length, 0)
51284
+ issue: handoff.issue_key,
51285
+ phase: handoff.phase,
51286
+ version: handoff.version,
51287
+ handoff: handoff.id
51257
51288
  }
51258
51289
  };
51259
51290
  }
@@ -52263,6 +52294,9 @@ async function executeDispatchTool(input) {
52263
52294
  });
52264
52295
  if (checked.problems.length > 0)
52265
52296
  throw new ToolInputError(input.tool, checked.problems);
52297
+ if (input.dryRun === true && !dryRunAsksDispatch(input.tool, checked.args)) {
52298
+ throw new Error(`dispatch ${input.tool}'s dry run asks Dispatch nothing`);
52299
+ }
52266
52300
  const command = dispatchCommands[input.tool];
52267
52301
  if (command === undefined)
52268
52302
  throw new Error(`Unknown Dispatch tool: ${input.tool}`);
@@ -58386,7 +58420,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
58386
58420
 
58387
58421
  // package.json
58388
58422
  var name2 = "@sjawhar/claude-envoy";
58389
- var version2 = "4.11.1";
58423
+ var version2 = "4.11.2";
58390
58424
  var legion = {
58391
58425
  daemonApiVersion: 168
58392
58426
  };