@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.
package/dist/dispatch.js CHANGED
@@ -15932,7 +15932,7 @@ var dispatchToolSpecs = [
15932
15932
  verdict: "pass",
15933
15933
  commit: "1111111111111111111111111111111111111111"
15934
15934
  },
15935
- 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,
15935
+ 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,
15936
15936
  arguments: (z) => ({
15937
15937
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
15938
15938
  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(),
@@ -18475,7 +18475,7 @@ function flagTable(tool, fields) {
18475
18475
  add("--help", { action: "help", text: "Prints this help." });
18476
18476
  add("--dry-run", {
18477
18477
  action: "dry-run",
18478
- text: "Checks the arguments as the call would, then prints them as JSON and sends nothing."
18478
+ 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."
18479
18479
  });
18480
18480
  return flags;
18481
18481
  }
@@ -18749,7 +18749,7 @@ function commandsHelp() {
18749
18749
  return ` ${commandName(spec.name).padEnd(width)} ${sentence}`;
18750
18750
  }),
18751
18751
  "",
18752
- "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.",
18752
+ "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.",
18753
18753
  ""
18754
18754
  ].join(`
18755
18755
  `);
@@ -19923,6 +19923,9 @@ function reviewNoRouteRefusal(baseUrl, route, version) {
19923
19923
  const health = isCleanUrl(baseUrl) ? `${baseUrl}/healthz` : "/healthz on that server";
19924
19924
  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.");
19925
19925
  }
19926
+ function resultDryRunNoRouteRefusal(baseUrl, route) {
19927
+ 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.");
19928
+ }
19926
19929
  var ISSUE_EVENTS_PAGE_MAX = 200;
19927
19930
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
19928
19931
  function requestSignal(signal, deadlineMs) {
@@ -20430,6 +20433,20 @@ class DispatchClient {
20430
20433
  async recordResult(issue, input) {
20431
20434
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
20432
20435
  }
20436
+ async dryRunResult(issue, input) {
20437
+ const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "results", "dry-run"];
20438
+ try {
20439
+ const { payload } = await this.#jsonAnswer("POST", path, input, {
20440
+ writes: false
20441
+ });
20442
+ return payload;
20443
+ } catch (error) {
20444
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
20445
+ throw error;
20446
+ const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
20447
+ throw resultDryRunNoRouteRefusal(this.#baseUrl, route);
20448
+ }
20449
+ }
20433
20450
  async issueResults(issue, at) {
20434
20451
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], undefined, at === undefined ? undefined : { at });
20435
20452
  }
@@ -24417,372 +24434,265 @@ async function otherAdviceLines(render) {
24417
24434
  }
24418
24435
  }
24419
24436
 
24420
- // ../envoy-client/src/dispatch-commands/render-graph.ts
24421
- function referenceLines(read) {
24422
- if (typeof read === "string")
24423
- return [`- ${read}`];
24424
- const edges = read.edges ?? [];
24425
- if (edges.length === 0)
24426
- return ["- none"];
24427
- return edges.map(edgeLine);
24428
- }
24429
- function isItemKind(kind) {
24430
- return ITEM_KINDS.some((item) => item === kind);
24431
- }
24432
- function edgeLine(edge) {
24433
- const { node } = edge;
24434
- const excerpt = edge.excerpt === undefined ? "" : `${textHead(edge.excerpt.text)} \xB7 `;
24435
- const block = edge.block === undefined ? "" : ` (block ${edge.block.ref ?? edge.block.id})`;
24436
- const parent = node.parent ?? undefined;
24437
- const item = node.kind === "block" && node.document === undefined && isItemKind(parent?.kind) ? parent : undefined;
24438
- const source = item === undefined ? `${node.kind} ${node.ref ?? node.id}` : `${item.kind} ${item.ref ?? item.id} block ${node.block_id ?? node.id}`;
24439
- return `- ${edge.kind} ${source} (${excerpt}${edge.created_at})${block}`;
24440
- }
24441
- function unavailableReason(error) {
24442
- return dispatchAnswered(error, 404) ? "unavailable" : `unavailable: ${messageFor(error)}`;
24443
- }
24444
- async function graphReferences(client, query) {
24445
- try {
24446
- return await client.getReferences(query);
24447
- } catch (error) {
24448
- return unavailableReason(error);
24437
+ // ../envoy-client/src/dispatch-commands/render-issue.ts
24438
+ function componentsLine(components) {
24439
+ const ids = components.ids ?? [];
24440
+ const unknown = components.unknown ?? [];
24441
+ const inherited = components.inherited_from === null ? "" : ` (inherited from ${components.inherited_from})`;
24442
+ const retired = unknown.length === 0 ? "" : ` (retired: ${unknown.join(", ")})`;
24443
+ switch (components.mode) {
24444
+ case "explicit":
24445
+ return `Components: ${ids.length === 0 ? "none live" : ids.join(", ")}${inherited}${retired}`;
24446
+ case "none":
24447
+ return `Components: none \u2014 ${components.reason ?? ""}${inherited}`;
24448
+ case "inherit":
24449
+ return "Components: unassigned";
24450
+ default:
24451
+ return `Components: ${components.mode}${inherited}${retired}`;
24449
24452
  }
24450
24453
  }
24451
- async function issueReferencesOrUnavailable(client, key) {
24452
- try {
24453
- return await client.getIssueReferences(key);
24454
- } catch (error) {
24455
- return unavailableReason(error);
24456
- }
24454
+ function advanceText(advance) {
24455
+ return `${advance.id} (${advance.inherited ? "inherited" : "own"})`;
24457
24456
  }
24458
- async function issueCoverageOrReason(client, key) {
24459
- try {
24460
- return await client.issueCoverage(key);
24461
- } catch (error) {
24462
- return unavailableReason(error);
24457
+ function advancesLine(issue) {
24458
+ if (issue.advances === undefined) {
24459
+ return "Advances: unknown (this Dispatch server predates priorities; upgrade it)";
24463
24460
  }
24461
+ const advances = issue.advances ?? [];
24462
+ if (advances.length === 0)
24463
+ return "Advances: no priority";
24464
+ return `Advances: ${advances.map(advanceText).join(", ")}`;
24464
24465
  }
24465
- async function graphSections(client, ref) {
24466
- const [incoming, outgoing] = await Promise.all([
24467
- graphReferences(client, { to: ref }),
24468
- graphReferences(client, { from: ref })
24469
- ]);
24470
- return graphSectionLines(incoming, outgoing);
24471
- }
24472
- function graphSectionLines(incoming, outgoing) {
24473
- return [
24474
- ...typeof incoming === "string" ? [] : nodeLine(incoming.node),
24475
- "Referenced by:",
24476
- ...referenceLines(incoming),
24477
- "Links:",
24478
- ...referenceLines(outgoing)
24479
- ];
24480
- }
24481
- function nodeLine(node) {
24482
- if (node.made_by === undefined)
24483
- return [];
24484
- const fact = (by, time) => `${by == null || by.length === 0 ? "nobody recorded" : by.map(actorText).join(", ")}${time == null ? "" : ` at ${time}`}`;
24485
- const made = fact(node.made_by, node.made_at);
24486
- const changed = fact(node.changed_by, node.changed_at);
24487
- const { parent } = node;
24488
- 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})`}`;
24489
- return [
24490
- `Node: ${node.kind} ${node.ref ?? node.id} \xB7 made by ${made} \xB7 changed by ${changed}${partOf}`
24491
- ];
24466
+ function claimText(claim, agents, read = {}) {
24467
+ const titles = agents?.titles;
24468
+ const liveness = holderLiveness(claim, agents, read);
24469
+ const holding = claimHolds(claim, titles, liveness);
24470
+ const takeableAt = claimTakeableAt(liveness);
24471
+ const unresponsive = liveness.holder_state === "unresponsive" && liveness.last_seen != null ? ` \xB7 unresponsive since ${liveness.last_seen}${takeableAt === null ? "" : `, takeable at ${takeableAt}`}` : " \xB7 unresponsive";
24472
+ const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : holding === "unresponsive" ? unresponsive : "";
24473
+ return `${actorLabel(claim.actor, titles)} since ${claim.at}${marker}`;
24492
24474
  }
24493
- function blockLines(node, ref, typed, noun = "Block") {
24494
- const unit = ref.item === undefined ? "version" : "revision";
24495
- const blockID = node.block_id ?? ref.block;
24496
- const head = ref.item === undefined ? [
24497
- `Block: ${blockID}`,
24498
- ...typed === undefined ? [] : [`Type: ${typed.type}`],
24499
- `Document: ${node.document ?? ref.document}`,
24500
- ...(typed?.attributes ?? []).map((attribute) => `${attribute.name}: ${attribute.value === "" ? "(empty)" : attribute.value}`),
24501
- ...node.changed_version === undefined ? [] : [`Changed in version: ${node.changed_version}`],
24502
- ...node.text === undefined ? [] : ["Text:", node.text]
24503
- ] : [
24504
- `${noun} ${blockID} of ${ref.item.kind} ${ref.item.id}${node.changed_version === undefined ? "" : ` (changed in revision ${node.changed_version})`}:`,
24505
- ...node.text === undefined ? [] : [node.text]
24506
- ];
24507
- const { pin } = node;
24508
- if (pin === undefined)
24509
- return head;
24510
- 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}.`;
24511
- return [
24512
- ...head,
24513
- `Pinned to ${unit}: ${pin.version}`,
24514
- state,
24515
- `Text at ${unit} ${pin.version}:`,
24516
- pin.text
24517
- ];
24475
+ function holderLiveness(claim, agents, read) {
24476
+ if (claim.actor.kind !== "session")
24477
+ return read;
24478
+ const row = agents?.liveness.get(claim.actor.id);
24479
+ if (row === undefined)
24480
+ return read;
24481
+ const holderState = read.holder_state ?? row.holder_state;
24482
+ const lastSeen = read.last_seen ?? row.last_seen;
24483
+ const takeableAt = read.takeable_at ?? row.takeable_at;
24484
+ return {
24485
+ ...holderState === undefined ? {} : { holder_state: holderState },
24486
+ ...lastSeen === undefined ? {} : { last_seen: lastSeen },
24487
+ ...takeableAt === undefined ? {} : { takeable_at: takeableAt }
24488
+ };
24518
24489
  }
24519
- async function typedBlockOf(client, ref) {
24520
- if (ref.item !== undefined || ref.block === undefined)
24490
+ async function liveAgents(client, needed) {
24491
+ if (!needed) {
24521
24492
  return;
24493
+ }
24522
24494
  try {
24523
- const blocks = ref.owner.kind === "project" ? await client.projectArtifactBlocks(ref.owner.project, ref.id) : await client.issueArtifactBlocks(ref.owner.issue, ref.id);
24524
- return blocks.find((block) => block.id === ref.block);
24495
+ const agents = await client.listAgents();
24496
+ return {
24497
+ titles: new Map(agents.map((agent) => [agent.session_id, agent.title])),
24498
+ liveness: new Map(agents.map((agent) => [agent.session_id, agentLiveness(agent)]))
24499
+ };
24525
24500
  } catch {
24526
24501
  return;
24527
24502
  }
24528
24503
  }
24529
- function askPartNoun(ask, node, blockID) {
24530
- if (ask.answer?.id === blockID)
24531
- return "Answer";
24532
- if ((ask.options ?? []).some((option) => option.id === blockID))
24533
- return "Option";
24534
- const placed = (ask.revision ?? 0) > 0 && (ask.options ?? []).every((option) => option.id !== undefined) && (ask.answer === null || ask.answer.id !== undefined);
24535
- return placed && node.pin?.state !== "removed" ? "Question" : "Part";
24504
+ function agentLiveness(agent) {
24505
+ return {
24506
+ ...agent.state === undefined ? {} : { holder_state: agent.state },
24507
+ ...agent.last_seen > 0 ? { last_seen: new Date(agent.last_seen).toISOString() } : {}
24508
+ };
24536
24509
  }
24537
-
24538
- // ../envoy-client/src/dispatch-commands/render-item.ts
24539
- function askSummary({ ask, replies, answers }, askRef, pictures, incoming, outgoing) {
24540
- const answer = ask.answer;
24541
- const earlierAnswers = (answers ?? []).slice(0, -1);
24542
- const parts = askPartEdges(ask, incoming);
24543
- const partRef = (id) => `${askRef}#b-${encodeBlockId(id)}`;
24544
- const chain = (replies ?? []).flatMap((reply) => [
24545
- `${reply.id} \xB7 ${actorText(reply.author)}`,
24546
- `Body: ${reply.body}`
24547
- ]);
24548
- const resolutionWords = dispatchWordsText(ask.resolution?.dispatch_words);
24549
- return [
24550
- `Question: ${ask.question}`,
24551
- ...anchorLines(ask),
24552
- "Options:",
24553
- ...(ask.options ?? []).length === 0 ? ["- none"] : (ask.options ?? []).flatMap((option) => [
24554
- `- ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}${option.id === undefined ? "" : ` (${partRef(option.id)})`}`,
24555
- ...partReferenceLines(parts.at, option.id)
24556
- ]),
24557
- `State: ${ask.state}`,
24558
- `Ask id: ${ask.id}`,
24559
- "Answer:",
24560
- ...answer === null ? ["- none"] : [
24561
- `- By: ${actorActText(answer.user, answer.act)}`,
24562
- `- Selected: ${(answer.selected ?? []).length === 0 ? "none" : (answer.selected ?? []).join(", ")}`,
24563
- ...answer.text === null ? [] : [`- Text: ${answer.text}`],
24564
- ...answer.id === undefined ? [] : [`- Reference: ${partRef(answer.id)}`],
24565
- ...partReferenceLines(parts.at, answer.id)
24566
- ],
24567
- ...earlierAnswers.length === 0 ? [] : [
24568
- "Earlier answers:",
24569
- ...earlierAnswers.map((earlier) => `- ${earlier.at} \xB7 ${actorActText(earlier.user, earlier.act)} \xB7 ${askAnswerText(earlier)}`)
24570
- ],
24571
- ...ask.resolution === undefined ? [] : [
24572
- "Resolution:",
24573
- `- By: ${ask.resolution.actor.id}`,
24574
- `- Kind: ${ask.resolution.kind}`,
24575
- ...ask.resolution.reason === "" ? [] : [`- Reason: ${ask.resolution.reason}`],
24576
- ...resolutionWords === undefined ? [] : [`- ${resolutionWords}`]
24577
- ],
24578
- "Replies:",
24579
- ...chain.length === 0 ? ["- none"] : chain,
24580
- ...pictures,
24581
- ...graphSectionLines(parts.rest, outgoing)
24582
- ].join(`
24583
- `);
24510
+ function holdsSession(claim) {
24511
+ return claim?.actor.kind === "session";
24584
24512
  }
24585
- function askPartEdges(ask, incoming) {
24586
- const ids = new Set([...(ask.options ?? []).map((option) => option.id), ask.answer?.id].filter((id) => id !== undefined));
24587
- const at = new Map;
24588
- if (typeof incoming === "string" || ids.size === 0)
24589
- return { at, rest: incoming };
24590
- const rest = [];
24591
- for (const edge of incoming.edges ?? []) {
24592
- const part = edge.block?.block_id;
24593
- if (part === undefined || !ids.has(part)) {
24594
- rest.push(edge);
24595
- continue;
24596
- }
24597
- const { block: _block, ...atPart } = edge;
24598
- const held = at.get(part);
24599
- if (held === undefined)
24600
- at.set(part, [atPart]);
24601
- else
24602
- held.push(atPart);
24603
- }
24604
- return { at, rest: { node: incoming.node, edges: rest } };
24513
+ function isRouteStatus(value) {
24514
+ return ISSUE_ROUTE_STATUSES.some((status) => status === value);
24605
24515
  }
24606
- function partReferenceLines(at, id) {
24607
- const edges = id === undefined ? undefined : at.get(id);
24608
- if (edges === undefined || edges.length === 0)
24609
- return [];
24610
- return [" Referenced by:", ...edges.map((edge) => ` ${edgeLine(edge)}`)];
24516
+ function routeHeldBySession(issue) {
24517
+ return issue.route_status === "live" && issue.route?.startsWith("role:") === true;
24611
24518
  }
24612
- function openAskAge(ageSeconds) {
24613
- const seconds = Math.max(0, Math.floor(ageSeconds));
24614
- if (seconds < 60)
24615
- return `${seconds}s`;
24616
- const minutes = Math.floor(seconds / 60);
24617
- if (minutes < 60)
24618
- return `${minutes}m${seconds % 60 === 0 ? "" : ` ${seconds % 60}s`}`;
24619
- const hours = Math.floor(minutes / 60);
24620
- if (hours < 24)
24621
- return `${hours}h${minutes % 60 === 0 ? "" : ` ${minutes % 60}m`}`;
24622
- const days = Math.floor(hours / 24);
24623
- return `${days}d${hours % 24 === 0 ? "" : ` ${hours % 24}h`}`;
24519
+ function routeText(issue, titles) {
24520
+ if (issue.route === null)
24521
+ return "none";
24522
+ const holder = issue.route_holder ?? null;
24523
+ const reach = {
24524
+ live: routeHeldBySession(issue) && holder !== null ? ` (held by ${titles?.get(holder) ?? holder})` : "",
24525
+ 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)",
24526
+ no_holder: issue.route.startsWith("role:") ? " (nobody holds it right now)" : " (that session is not running right now)",
24527
+ 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)"
24528
+ };
24529
+ const status = issue.route_status;
24530
+ return issue.route + (status != null && isRouteStatus(status) ? reach[status] : "");
24624
24531
  }
24625
- function namedPerson(person) {
24626
- return person === undefined || person === "" ? undefined : person;
24532
+ function progressText(progress, sep) {
24533
+ if (progress === undefined)
24534
+ return "";
24535
+ const parts = [];
24536
+ if (progress.tasks !== null)
24537
+ parts.push(`tasks ${progress.tasks.done}/${progress.tasks.total}`);
24538
+ if (progress.children !== null) {
24539
+ parts.push(`children ${progress.children.done}/${progress.children.total}`);
24540
+ }
24541
+ return parts.join(sep);
24627
24542
  }
24628
- function waitsOnPerson(ask) {
24629
- return namedPerson(ask.waiting_on_person);
24543
+ function repositoryLine(issue) {
24544
+ if (issue.resolved_repo === undefined) {
24545
+ return "Repository: unknown (this Dispatch server predates repository fields; upgrade it)";
24546
+ }
24547
+ if (issue.resolved_repo === null)
24548
+ return "Repository: none";
24549
+ if (issue.repo !== null && issue.repo !== undefined)
24550
+ return `Repository: ${issue.repo} (own)`;
24551
+ return `Repository: ${issue.resolved_repo} (inherited or project default)`;
24630
24552
  }
24631
- function openAskLine(ask, linkBase) {
24632
- const priority = ask.priority === null ? "" : `P${ask.priority} \xB7 `;
24633
- return `- ${openAskAge(ask.age_seconds)} \xB7 ${priority}${ownerTitle(ask.owner)} \xB7 asked of ${waitsOnPerson(ask) ?? "nobody"} \xB7 ${ask.question} \xB7 ${linkFor(ask.ref, linkBase)}`;
24553
+ function olderServerWarnings(issue) {
24554
+ const warnings = [
24555
+ ...issue.resolved_repo !== undefined ? [] : [
24556
+ `dispatch: warning: Dispatch issue is missing resolved_repo: this Dispatch server predates repository fields, so ${issue.key}'s repository is unknown; upgrade the server`
24557
+ ],
24558
+ ...issue.advances !== undefined ? [] : [
24559
+ `dispatch: warning: Dispatch issue is missing advances: this Dispatch server predates priorities, so the priorities ${issue.key} advances are unknown; upgrade the server`
24560
+ ]
24561
+ ];
24562
+ return warnings.length === 0 ? {} : { warnings };
24634
24563
  }
24635
- function formatOpenAsksSummary(response, linkBase) {
24636
- const scope = "active open asks you authored on open issues and project documents";
24637
- if (response.count === 0) {
24638
- return ["There are no unanswered asks for this session.", `Scope: ${scope}.`].join(`
24639
- `);
24564
+ function issueSummary(issue, events, references, graph, linkBase, coverage, agents) {
24565
+ const asks = issue.open_asks ?? [];
24566
+ const labels = issue.labels ?? [];
24567
+ const links = issue.external_links ?? [];
24568
+ const members = typeof references === "string" ? [] : references.members ?? [];
24569
+ const spec = issue.artifacts?.find((artifact) => artifact.primary);
24570
+ const specApproval = spec === undefined ? undefined : approvalLine(spec, typeof issue.closed_at === "string");
24571
+ if (issue.priority === undefined)
24572
+ throw new Error("Dispatch issue is missing priority");
24573
+ if (issue.assignee === undefined)
24574
+ throw new Error("Dispatch issue is missing assignee");
24575
+ if (issue.components === undefined)
24576
+ throw new Error("Dispatch issue is missing components");
24577
+ if (issue.claim === undefined)
24578
+ throw new Error("Dispatch issue is missing claim");
24579
+ if (issue.external_links === undefined) {
24580
+ throw new Error("Dispatch issue is missing external_links");
24640
24581
  }
24641
- const waitingOnHuman = (response.asks ?? []).filter((ask) => ask.waiting_on === "human");
24642
- const waitingOnAgent = (response.asks ?? []).filter((ask) => ask.waiting_on === "agent");
24643
24582
  return [
24644
- `${response.count} unanswered ${response.count === 1 ? "ask" : "asks"} you authored on active issues and project documents.`,
24645
- "",
24646
- `Waiting on human (${waitingOnHuman.length}):`,
24647
- ...waitingOnHuman.map((ask) => openAskLine(ask, linkBase)),
24648
- "",
24649
- `Waiting on agent (${waitingOnAgent.length}):`,
24650
- ...waitingOnAgent.map((ask) => openAskLine(ask, linkBase))
24583
+ `Title: ${issue.title}`,
24584
+ `Key: ${issue.key}`,
24585
+ `Link: ${linkFor(`/issues/${encodeURIComponent(issue.key)}`, linkBase)}`,
24586
+ `Status: ${issue.status}`,
24587
+ `Assignee: ${issue.assignee ?? "unassigned"}`,
24588
+ `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, agents, issue)}`,
24589
+ ...issue.priority === null ? [] : [`Priority: P${issue.priority}`],
24590
+ `Labels: ${labels.length === 0 ? "none" : labels.join(", ")}`,
24591
+ componentsLine(issue.components),
24592
+ advancesLine(issue),
24593
+ `Route: ${routeText(issue, agents?.titles)}`,
24594
+ repositoryLine(issue),
24595
+ `Progress: ${progressText(issue.progress, ", ") || "none"}`,
24596
+ ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
24597
+ ...typeof coverage === "string" ? [`Coverage: ${coverage}`] : (coverage.gaps ?? []).map((gap) => `Coverage: ${gap}`),
24598
+ "External links:",
24599
+ ...links.length === 0 ? ["- none"] : links.map((link) => `- ${link.url}${link.kind === undefined ? "" : ` (${link.kind})`}`),
24600
+ "Documents:",
24601
+ ...documentListLines(issue.artifacts ?? []),
24602
+ "Open asks:",
24603
+ ...asks.length === 0 ? ["- none"] : asks.map((ask) => `- ${ask.id}: ${ask.question}`),
24604
+ "References:",
24605
+ ...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}`),
24606
+ ...typeof references === "string" || !references.truncated ? [] : ["- more references beyond 8 hops"],
24607
+ "Events:",
24608
+ ...events.length === 0 ? ["- none"] : events.map(eventLine),
24609
+ ...graph
24651
24610
  ].join(`
24652
24611
  `);
24653
24612
  }
24654
- function commentSummary({ comment, replies }, graph) {
24655
- const root = [
24656
- `${comment.id} \xB7 ${actorText(comment.author)}`,
24657
- ...anchorLines(comment),
24658
- ...replyBlockLines(comment),
24659
- `Body: ${comment.body}`
24660
- ];
24661
- const chain = (replies ?? []).flatMap((reply) => [
24662
- `${reply.id} \xB7 ${actorText(reply.author)}`,
24663
- ...anchorLines(reply),
24664
- ...replyBlockLines(reply),
24665
- ...reply.answers != null && reply.answers !== comment.id ? [`Answers: ${reply.answers}`] : [],
24666
- `Body: ${reply.body}`
24667
- ]);
24613
+ function logSummary(issue, events) {
24668
24614
  return [
24669
- "Comment:",
24670
- ...root,
24671
- "Reply chain:",
24672
- ...chain.length === 0 ? ["- none"] : chain,
24673
- ...graph
24615
+ `Key: ${issue.key}`,
24616
+ "Events:",
24617
+ ...events.length === 0 ? ["- none"] : events.map(eventLine)
24674
24618
  ].join(`
24675
24619
  `);
24676
24620
  }
24677
- function replyBlockLines(record) {
24678
- const block = record.reply_block;
24679
- if (block === undefined || block === null)
24680
- return [];
24681
- return [
24682
- block.removed ? `Re: block ${block.block_id} (removed)` : `Re: block ${block.block_id}: ${textHead(block.text)}`
24683
- ];
24621
+ function eventHead(event) {
24622
+ switch (event.type) {
24623
+ case "ask.opened":
24624
+ case "ask.anchor_refreshed":
24625
+ case "ask.edited":
24626
+ case "ask.handed_back":
24627
+ case "ask.resolved":
24628
+ return textHead(event.payload.question);
24629
+ case "ask.answered": {
24630
+ const previousAnswer = event.payload.previous_answer;
24631
+ return `${textHead(event.payload.question)} -> ${textHead(askAnswerText(event.payload.answer))}${previousAnswer === undefined ? "" : ` (was: ${textHead(askAnswerText(previousAnswer))})`}`;
24632
+ }
24633
+ case "ask.asked_of":
24634
+ return `${textHead(event.payload.question)} -> asked of ${event.payload.asked_of ?? "the assignee of its issue"}`;
24635
+ case "comment.created":
24636
+ case "comment.answered":
24637
+ case "comment.anchor_refreshed":
24638
+ case "comment.edited":
24639
+ case "comment.resolved":
24640
+ case "comment.reopened":
24641
+ case "suggestion.accepted":
24642
+ case "suggestion.rejected":
24643
+ case "message.created":
24644
+ case "message.answered":
24645
+ return textHead(event.payload.body);
24646
+ case "artifact.version":
24647
+ return textHead(`${event.payload.name} v${event.payload.version.number}${event.payload.version.summary ? `: ${event.payload.version.summary}` : ""}`);
24648
+ case "artifact.approved":
24649
+ case "artifact.changes_requested": {
24650
+ const { name, version, kind, reason } = event.payload;
24651
+ const verb = event.type === "artifact.approved" ? "approved" : "changes requested";
24652
+ const reviewer = kind === "plan_review" ? " by plan review" : kind === "person" ? " by a person" : "";
24653
+ return textHead(`${name} v${version} ${verb}${reviewer}${reason ? `: ${reason}` : ""}`);
24654
+ }
24655
+ case "artifact.human_edited":
24656
+ return textHead(humanEditHead(event.payload));
24657
+ case "issue.created": {
24658
+ const forced = event.payload.forced;
24659
+ const head = `status ${event.payload.status}`;
24660
+ if (forced === undefined)
24661
+ return head;
24662
+ return forced.past.length === 0 ? `${head} \xB7 forced, the near-copy check did not answer` : `${head} \xB7 forced past ${forced.past.join(", ")}`;
24663
+ }
24664
+ case "issue.updated":
24665
+ case "issue.closed":
24666
+ return `status ${event.payload.status}`;
24667
+ default:
24668
+ return;
24669
+ }
24684
24670
  }
24685
- function anchorLines(record) {
24686
- return [
24687
- ...record.anchor?.quote === undefined ? [] : [`> ${record.anchor.quote}`],
24688
- ...record.anchor_block === undefined ? [] : [`Position: ${positionText(record.anchor_block)}`],
24689
- ...record.anchor_block_error === undefined ? [] : [`Position: unavailable (${record.anchor_block_error})`]
24690
- ];
24671
+ function eventRef(event) {
24672
+ const payload = event.payload;
24673
+ const id = typeof payload === "object" && payload !== null && "id" in payload ? payload.id : undefined;
24674
+ if (typeof id !== "string" || id === "" || event.issue_key === null)
24675
+ return;
24676
+ const kind = event.type.startsWith("message.") ? "message" : event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("ask.") ? "ask" : undefined;
24677
+ return kind === undefined ? undefined : `dispatch://${event.issue_key}/${kind}/${id}`;
24691
24678
  }
24692
- function positionText(block) {
24693
- const { table, path } = block;
24694
- const segments = (path ?? []).map((entry) => `${entry.type}[${entry.index}]`);
24695
- if (table === undefined || table.row === null)
24696
- return segments.join(" \u203A ");
24697
- const tableAt = (path ?? []).findIndex((entry) => entry.type === "table");
24698
- const cells = table.cells ?? [];
24699
- const label = (table.column === null ? cells : cells.slice(0, table.column)).map((cell) => cell.trim()).filter((cell) => cell !== "" && !/^\d+$/.test(cell)).join(" \xB7 ");
24700
- const row = label === "" ? `row ${table.row}` : `row ${table.row} (${label})`;
24701
- const header = table.header === null || table.header === "" ? String(table.column) : table.header;
24702
- return [
24703
- ...segments.slice(0, tableAt + 1),
24704
- table.column === null ? row : `${row}, column ${header}`
24705
- ].join(" \u203A ");
24679
+ function eventActorText(actor) {
24680
+ const title = actor.kind === "session" ? actor.origin?.session_title : undefined;
24681
+ return title === undefined || title === "" ? actorText(actor) : `${actorText(actor)} (${title})`;
24706
24682
  }
24707
- function messageSummary({ message, replies }, graph) {
24708
- const root = [
24709
- `${message.id} \xB7 ${actorText(message.author)}`,
24710
- ...replyBlockLines(message),
24711
- `Body: ${message.body}`
24712
- ];
24713
- const chain = (replies ?? []).flatMap((reply) => [
24714
- `${reply.id} \xB7 ${actorText(reply.author)}`,
24715
- ...replyBlockLines(reply),
24716
- `Body: ${reply.body}`
24717
- ]);
24683
+ function eventLine(event) {
24684
+ const head = eventHead(event);
24685
+ const ref = eventRef(event);
24686
+ return `- #${event.seq} ${event.type}${ref === undefined ? "" : ` ${ref}`} \xB7 ${eventActorText(event.actor)} \xB7 ${event.created_at}${head === undefined || head === "" ? "" : ` \xB7 ${head}`}`;
24687
+ }
24688
+ function childrenSummary(issue) {
24718
24689
  return [
24719
- "Message:",
24720
- ...root,
24721
- "Reply chain:",
24722
- ...chain.length === 0 ? ["- none"] : chain,
24723
- ...graph
24690
+ `Key: ${issue.key}`,
24691
+ "Children:",
24692
+ ...(issue.children ?? []).length === 0 ? ["- none"] : (issue.children ?? []).map((child) => `- ${child.key}: ${child.title} (${child.status})`)
24724
24693
  ].join(`
24725
24694
  `);
24726
24695
  }
24727
- async function openAnchoredThreads(client, resolved) {
24728
- const asksPromise = resolved.owner.kind === "project" ? client.getArtifactAsks(resolved.artifact.id) : Promise.resolve(resolved.issue?.open_asks ?? []);
24729
- const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "");
24730
- const commentsResultPromise = commentsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
24731
- const asks = (await asksPromise).filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id);
24732
- const commentsResult = await commentsResultPromise;
24733
- if (commentsResult.status === "rejected" && !dispatchAnswered(commentsResult.reason, 404)) {
24734
- throw commentsResult.reason;
24735
- }
24736
- const comments = commentsResult.status === "fulfilled" ? commentsResult.value : [];
24737
- const askReplies = new Map(asks.map((ask) => [ask.id, []]));
24738
- for (const comment of comments) {
24739
- if (comment.ask_id)
24740
- askReplies.get(comment.ask_id)?.push(comment);
24741
- }
24742
- const askThreads = asks.map((ask) => [
24743
- `ask ${ask.id} \xB7 ${actorText(ask.author)} \xB7 ${ask.created_at}`,
24744
- ...anchorLines(ask),
24745
- `Question: ${ask.question}`,
24746
- ...threadReplyLines(askReplies.get(ask.id) ?? [])
24747
- ].join(`
24748
- `));
24749
- const byId = new Map(comments.map((comment) => [comment.id, comment]));
24750
- const roots = comments.filter((comment) => comment.reply_to === null && !comment.ask_id && !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id);
24751
- const replies = new Map(roots.map((root) => [root.id, []]));
24752
- for (const comment of comments) {
24753
- const root = comment.reply_to === null ? undefined : threadRootId(comment, byId);
24754
- if (root !== undefined)
24755
- replies.get(root)?.push(comment);
24756
- }
24757
- const commentThreads = roots.map((root) => [
24758
- `comment ${root.id} \xB7 ${actorText(root.author)} \xB7 ${root.created_at}`,
24759
- ...anchorLines(root),
24760
- `Body: ${root.body}`,
24761
- ...threadReplyLines(replies.get(root.id) ?? [])
24762
- ].join(`
24763
- `));
24764
- return [...askThreads, ...commentThreads];
24765
- }
24766
- function threadReplyLines(replies) {
24767
- return replies.flatMap((reply) => [
24768
- `reply ${reply.id} \xB7 ${actorText(reply.author)} \xB7 ${reply.created_at}`,
24769
- `Body: ${reply.body}`
24770
- ]);
24771
- }
24772
- function threadRootId(comment, byId) {
24773
- const seen = new Set;
24774
- let current = comment;
24775
- while (current.reply_to !== null) {
24776
- if (seen.has(current.id))
24777
- return;
24778
- seen.add(current.id);
24779
- const parent = byId.get(current.reply_to);
24780
- if (parent === undefined)
24781
- return;
24782
- current = parent;
24783
- }
24784
- return current.id;
24785
- }
24786
24696
 
24787
24697
  // ../envoy-client/src/dispatch-subscribe.ts
24788
24698
  function followedAsk(details) {
@@ -24911,1893 +24821,2014 @@ async function followedAskDetails(client, ask, artifact) {
24911
24821
  return { ...await askOwnerDetails(client, ask, artifact), follows: { ask: ask.id } };
24912
24822
  }
24913
24823
 
24914
- // ../envoy-client/src/dispatch-commands/asks.ts
24915
- function askUrgency(args) {
24916
- const value = args.urgency;
24917
- return ASK_URGENCIES.find((urgency) => urgency === value);
24918
- }
24919
- var askHintLimit = 8;
24920
- function openAskChoices(asks, owner) {
24921
- if (asks.length === 0)
24922
- return `${owner} holds no open ask.`;
24923
- const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)}\u2026 ${textHead(ask.question)}`);
24924
- return `The open asks of ${owner} are: ${hints.join(", ")}.`;
24925
- }
24926
- function askIDInputProblem(asks, owner) {
24927
- return `ask ids are uuids. Write the whole id, or at least its first 8 characters. ${openAskChoices(asks, owner)}`;
24928
- }
24929
- async function movedApprovalLine(client, askID) {
24930
- const ask = (await client.getAsk(askID).catch(() => {
24931
- return;
24932
- }))?.ask;
24933
- const approval = ask?.approval;
24934
- if (ask?.kind !== "approval" || approval === undefined)
24935
- return;
24936
- const listed = approval.documents ?? [];
24937
- const documents = listed.length > 0 ? listed : [
24938
- {
24939
- name: approval.name,
24940
- requested_version: approval.requested_version,
24941
- version: approval.version
24942
- }
24943
- ];
24944
- const moved = movedApprovalDocuments(documents);
24945
- if (moved.length === 0)
24946
- return;
24947
- const firstMoved = moved[0];
24948
- if (firstMoved === undefined)
24949
- return;
24950
- const command = handBackApprovalCommand({
24951
- owner: ask.issue_key === null ? { kind: "project", key: ask.approval_artifact?.project ?? "<project>" } : { kind: "issue", key: ask.issue_key },
24952
- artifactID: approval.artifact_id,
24953
- primary: ask.approval_artifact?.primary === true,
24954
- verification: documents.length > 1 && ask.approval_artifact?.primary === true,
24955
- summaryVersion: firstMoved.requested_version
24956
- });
24957
- 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}`;
24958
- }
24959
- async function replyToAskCandidates(client, owner, resolved) {
24960
- if (owner.kind === "issue") {
24961
- const issue = resolved?.issue ?? await client.getIssue(owner.issue);
24962
- return { asks: issue.open_asks ?? [], owner: "this issue" };
24963
- }
24964
- if (resolved === undefined)
24965
- throw new Error("project document is missing its resolved artifact");
24966
- return {
24967
- asks: await client.getArtifactAsks(resolved.artifact.id, "open"),
24968
- owner: "this document"
24969
- };
24970
- }
24971
- async function resolveReplyToAsk(tool, client, target, resolved, id) {
24972
- const whole = normalizeUUID(id);
24973
- if (whole !== undefined)
24974
- return whole;
24975
- const { asks, owner } = await replyToAskCandidates(client, target, resolved);
24976
- if (!isIdPrefix(id)) {
24977
- throw new ToolInputError(tool, [askIDInputProblem(asks, owner)], { aboutAFlag: false });
24824
+ // ../envoy-client/src/dispatch-commands/issues.ts
24825
+ function componentsChange(input, after) {
24826
+ switch (input.mode) {
24827
+ case "explicit":
24828
+ return `components -> explicit [${(after.ids ?? []).join(", ")}]`;
24829
+ case "none":
24830
+ return `components -> none (${after.reason ?? input.reason ?? ""})`;
24831
+ case "inherit":
24832
+ return "components -> inherit";
24833
+ default:
24834
+ return `components -> ${input.mode}`;
24978
24835
  }
24979
- return resolveIdPrefix(tool, "ask", id, owner, async () => asks, {
24980
- 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)}`
24981
- });
24982
24836
  }
24983
- var askIdShapeProblem = "ask ids are uuids (a prefix of at least 8 hex characters works)";
24984
- async function readAskRef(tool, id, ownerName, client, list) {
24985
- const fullID = normalizeUUID(id);
24986
- if (fullID !== undefined) {
24987
- try {
24988
- return await client.getAsk(fullID);
24989
- } catch (error) {
24990
- if (!(error instanceof DispatchServiceError) || error.status !== 404)
24991
- throw error;
24992
- const blocks = (await list()).filter((ask) => ask.block_id?.toLowerCase() === fullID);
24993
- if (blocks.length !== 1 || blocks[0] === undefined)
24994
- throw error;
24995
- return client.getAsk(blocks[0].id);
24996
- }
24997
- }
24998
- const asks = await list();
24999
- let matches = asks.filter((ask) => ask.block_id === id);
25000
- if (matches.length === 0) {
25001
- if (!isIdPrefix(id)) {
25002
- throw new ToolInputError(tool, [
25003
- `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}`
25004
- ]);
25005
- }
25006
- const prefix = id.toLowerCase();
25007
- matches = asks.filter((ask) => ask.id.toLowerCase().startsWith(prefix) || (ask.block_id?.toLowerCase().startsWith(prefix) ?? false));
24837
+ 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.';
24838
+ 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.";
24839
+ async function architectureGuidance(client, project, components) {
24840
+ if (components.mode === "none" || (components.ids ?? []).length > 0)
24841
+ return;
24842
+ try {
24843
+ if ((await client.listArchitectureSources(project)).length === 0)
24844
+ return;
24845
+ return `Project ${project} has an architecture model, but this issue is not linked to any of its current components. ${architectureComponentsAction}`;
24846
+ } catch (error) {
24847
+ return `Could not check whether project ${project} has an architecture model: ${messageFor(error)}. ${architectureComponentsAction}`;
25008
24848
  }
25009
- if (matches.length === 1 && matches[0] !== undefined)
25010
- return client.getAsk(matches[0].id);
25011
- throw new ToolInputError(tool, [
25012
- 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`
25013
- ]);
25014
24849
  }
25015
- async function sessionOpenAsks(client, sessionId) {
25016
- const session = sessionId?.trim();
25017
- if (!session)
25018
- throw new Error("host session id is required to read this session's open asks");
25019
- return (await client.openAsks(session)).asks ?? [];
24850
+ function isDuplicateCandidate(value) {
24851
+ if (typeof value !== "object" || value === null)
24852
+ return false;
24853
+ const candidate = value;
24854
+ 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";
25020
24855
  }
25021
- function openAskHints(asks) {
25022
- if (asks.length === 0)
25023
- return "you have no open asks";
25024
- const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)} \u2014 ${textHead(ask.question)}`);
25025
- return `your open asks: ${hints.join("; ")}`;
24856
+ function duplicateCandidates(error) {
24857
+ if (error.candidates === undefined || !error.candidates.every(isDuplicateCandidate))
24858
+ throw error;
24859
+ return error.candidates;
25026
24860
  }
25027
- async function resolveAskArgument(tool, args, client, sessionId) {
25028
- const id = askId(args);
25029
- if (normalizeUUID(id) === undefined && !isIdPrefix(id)) {
25030
- const asks = await sessionOpenAsks(client, sessionId).catch(() => {
25031
- return;
25032
- });
25033
- throw new ToolInputError(tool, [
25034
- asks === undefined ? askIdShapeProblem : `${askIdShapeProblem}; ${openAskHints(asks)}`
25035
- ]);
25036
- }
25037
- const resolved = await resolveIdPrefix(tool, "ask", id, "this session", () => sessionOpenAsks(client, sessionId));
25038
- const reference = stringArg(args, "ask");
25039
- const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
25040
- if (ref === null)
25041
- return { id: resolved };
25042
- const read = await client.getAsk(resolved);
25043
- await refuseItemOffRef(tool, "ask", ref, reference, read.ask, async () => {
25044
- const document = await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true });
25045
- return document.artifact.id;
25046
- });
25047
- return { id: resolved, read };
24861
+ function refuseUnsavedRepository(verb, issue, repo) {
24862
+ if (repo === undefined || issue.repo !== undefined)
24863
+ return;
24864
+ const lost = repo === "" ? "the repository was not cleared" : `${repo} was not saved`;
24865
+ throw new Error(`Dispatch ${verb} ${issue.key} without its repository: this Dispatch server predates repository fields, so ${lost}; upgrade the server`);
25048
24866
  }
25049
- async function openAsksCommand(context) {
25050
- const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
25051
- const client = dispatchClient();
25052
- const project = optionalString(ownerArguments.args, "project");
25053
- if (project !== undefined) {
25054
- const response = await client.openAsksForProject(project);
25055
- return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
24867
+ function advancesRevisionToSend(issue, named) {
24868
+ if (issue.advances_revision === undefined) {
24869
+ throw new Error(`Dispatch read ${issue.key} without its advances: this Dispatch server predates priorities, so nothing was sent; upgrade the server`);
25056
24870
  }
25057
- const sessionId = input.sessionId?.trim();
25058
- if (!sessionId)
25059
- throw new Error("host session id is required for dispatch open-asks");
25060
- const response = await client.openAsks(sessionId);
25061
- return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
24871
+ return named ?? issue.advances_revision;
25062
24872
  }
25063
- async function askCommand(context) {
25064
- const {
25065
- args,
25066
- client,
25067
- actor,
25068
- input,
25069
- linkBase,
25070
- documentOwner,
25071
- resolveDocument,
25072
- writePictures,
25073
- issue
25074
- } = context;
25075
- const anchorArgs = asObject(args.anchor);
25076
- const owner = documentOwner();
25077
- const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
25078
- const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
25079
- const options = args.options;
25080
- const multiple = optionalBoolean(args, "multiple");
25081
- const urgency = askUrgency(args);
25082
- const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
25083
- const question = await writePictures(resolved, askQuestionWithRef(args));
25084
- const askInput = {
25085
- question,
25086
- ...Array.isArray(options) ? { options } : {},
25087
- ...multiple === undefined ? {} : { multiple },
25088
- ...urgency === undefined ? {} : { urgency },
25089
- ...anchored === undefined ? {} : { anchor: anchored },
25090
- actor
24873
+ async function issueCommand(context) {
24874
+ const { args, client, actor, input, linkBase } = context;
24875
+ const project = stringArg(args, "project");
24876
+ const title = stringArg(args, "title");
24877
+ const parent = optionalString(args, "parent");
24878
+ const external = optionalString(args, "external");
24879
+ const force = optionalBoolean(args, "force");
24880
+ const spec = optionalString(args, "spec");
24881
+ const priority = optionalPriority(args, "priority");
24882
+ const assignee = optionalString(args, "assignee");
24883
+ const components = optionalComponents(args, "components");
24884
+ const repo = optionalString(args, "repo");
24885
+ const labels = args.labels;
24886
+ const blockedBy = args.blocked_by;
24887
+ const advances = optionalStringArray(args, "advances");
24888
+ try {
24889
+ const created = await client.issue({
24890
+ project,
24891
+ title,
24892
+ ...parent === undefined ? {} : { parent },
24893
+ ...Array.isArray(blockedBy) ? { blocked_by: blockedBy } : {},
24894
+ ...advances === undefined ? {} : { advances },
24895
+ ...external === undefined ? {} : { external },
24896
+ ...force === undefined ? {} : { force },
24897
+ ...spec === undefined ? {} : { spec },
24898
+ ...priority === undefined ? {} : { priority },
24899
+ ...assignee === undefined ? {} : { assignee },
24900
+ ...components === undefined ? {} : { components },
24901
+ ...repo === undefined ? {} : { repo },
24902
+ ...Array.isArray(labels) ? { labels } : {},
24903
+ actor
24904
+ });
24905
+ refuseUnsavedRepository(created.created ? "created" : "already holds", created, repo);
24906
+ const adviceLines = await otherAdviceLines(async () => {
24907
+ const componentGuidance = await architectureGuidance(client, created.project, created.components);
24908
+ return [
24909
+ ...renderAdvice(input.tool, created.key, created.advice, {
24910
+ isPrimarySpec: spec !== undefined
24911
+ }),
24912
+ ...componentGuidance === undefined ? [] : [componentGuidance]
24913
+ ];
24914
+ });
24915
+ const href = linkFor(`/issues/${encodeURIComponent(created.key)}`, linkBase);
24916
+ const assigned = created.assignee === undefined ? "" : created.assignee === null ? "; unassigned" : `; assigned to ${created.assignee}`;
24917
+ const suffixes = `${assigned}${await notSubscribed(issueTopic(created.key), input.subscriptions)}`;
24918
+ return {
24919
+ text: [
24920
+ created.created ? `Created ${created.key}: ${created.title} \u2192 ${href}${suffixes}` : `Dispatch already holds ${created.key}: ${created.title} \u2192 ${href}; nothing was created${suffixes}`,
24921
+ ...created.created ? relatedCheckLines(created.advice?.suggestions, {
24922
+ project: created.project,
24923
+ text: title,
24924
+ linkBase
24925
+ }) : [],
24926
+ ...adviceLines
24927
+ ].join(`
24928
+ `),
24929
+ details: {
24930
+ issue: created.key,
24931
+ ...created.advice === undefined ? {} : { advice: created.advice }
24932
+ }
24933
+ };
24934
+ } catch (error) {
24935
+ if (!(error instanceof DispatchServiceError) || error.code !== "POSSIBLE_DUPLICATE") {
24936
+ throw error;
24937
+ }
24938
+ const candidates = duplicateCandidates(error);
24939
+ return {
24940
+ text: [
24941
+ `Not created: "${title}" is a near copy of an open issue.`,
24942
+ ...candidates.map((candidate) => {
24943
+ const href = linkFor(candidate.href, linkBase);
24944
+ return `${candidate.key} [${candidate.status}] ${candidate.title} \u2192 ${href}`;
24945
+ }),
24946
+ "Read each issue above. If one is the same work, fold this into it by the duplicate rule of skill://dispatch-first.",
24947
+ "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."
24948
+ ].join(`
24949
+ `),
24950
+ details: { duplicates: candidates },
24951
+ refused: true
24952
+ };
24953
+ }
24954
+ }
24955
+ async function issueUpdateCommand(context) {
24956
+ const { args, client, actor, input, issue } = context;
24957
+ const issueKey = issue();
24958
+ const status = optionalString(args, "status");
24959
+ const reason = optionalString(args, "reason");
24960
+ const title = optionalString(args, "title");
24961
+ const route = optionalString(args, "route");
24962
+ const parent = optionalString(args, "parent");
24963
+ const components = optionalComponents(args, "components");
24964
+ const repo = optionalString(args, "repo");
24965
+ const rankBefore = optionalString(args, "before");
24966
+ const rankAfter = optionalString(args, "after");
24967
+ const priority = optionalPriority(args, "priority");
24968
+ const assignee = optionalNullableString(args, "assignee");
24969
+ const labels = Array.isArray(args.labels) ? args.labels : undefined;
24970
+ const blockedBy = Array.isArray(args.blocked_by) ? args.blocked_by : undefined;
24971
+ const advances = optionalStringArray(args, "advances");
24972
+ const advancesRevision = optionalNumber(args, "advances_revision");
24973
+ const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
24974
+ let before;
24975
+ try {
24976
+ before = await client.getIssue(issueKey);
24977
+ } catch (error) {
24978
+ throw refusalWithCode(error);
24979
+ }
24980
+ const advancesWrite = advances === undefined ? undefined : { advances, advances_revision: advancesRevisionToSend(before, advancesRevision) };
24981
+ if (status === "done" && typeof before.closed_at === "string") {
24982
+ 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`);
24983
+ }
24984
+ let closingNote;
24985
+ if (reason !== undefined) {
24986
+ try {
24987
+ const message = await client.message(issueKey, { body: reason, actor });
24988
+ closingNote = {
24989
+ id: message.id,
24990
+ ref: dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id)
24991
+ };
24992
+ } catch (error) {
24993
+ if (error instanceof DispatchWriteLandedError) {
24994
+ 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 });
24995
+ }
24996
+ 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";
24997
+ if (error instanceof DispatchServiceError)
24998
+ throw refusalWithCode(error, told);
24999
+ throw withAccount(error, told);
25000
+ }
25001
+ }
25002
+ const existingLinks = before.external_links ?? [];
25003
+ const linked = existingLinks.map((link) => link.url);
25004
+ const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
25005
+ const sentLinks = requestedLinks === undefined ? undefined : requestedLinks.length === 0 ? [] : [...existingLinks, ...newLinks.map((url) => ({ url }))];
25006
+ const rank = rankBefore === undefined && rankAfter === undefined ? undefined : {
25007
+ ...rankBefore === undefined ? {} : { before: rankBefore },
25008
+ ...rankAfter === undefined ? {} : { after: rankAfter }
25091
25009
  };
25092
- const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
25093
- const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
25094
- const checkLines = relatedCheckLines(ask.advice?.suggestions, {
25095
- project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
25096
- text: stringArg(args, "question"),
25097
- linkBase
25010
+ let after;
25011
+ try {
25012
+ after = await client.updateIssue(issueKey, {
25013
+ ...status === undefined ? {} : { status },
25014
+ ...title === undefined ? {} : { title },
25015
+ ...labels === undefined ? {} : { labels },
25016
+ ...priority === undefined ? {} : { priority },
25017
+ ...assignee === undefined ? {} : { assignee },
25018
+ ...route === undefined ? {} : { route },
25019
+ ...parent === undefined ? {} : { parent: parent === "" ? null : parent },
25020
+ ...blockedBy === undefined ? {} : { blocked_by: blockedBy },
25021
+ ...advancesWrite,
25022
+ ...components === undefined ? {} : { components },
25023
+ ...repo === undefined ? {} : { repo: repo === "" ? null : repo },
25024
+ ...sentLinks === undefined ? {} : { external_links: sentLinks },
25025
+ ...rank === undefined ? {} : { rank },
25026
+ actor
25027
+ });
25028
+ } catch (error) {
25029
+ if (error instanceof DispatchWriteLandedError)
25030
+ throw error;
25031
+ const answered = error instanceof DispatchWriteUnsettledError ? error.last : error;
25032
+ 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)` : "";
25033
+ if (closingNote === undefined) {
25034
+ if (taken !== "" && !(error instanceof DispatchServiceError)) {
25035
+ throw withAccount(error, taken);
25036
+ }
25037
+ throw refusalWithCode(error, taken);
25038
+ }
25039
+ const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
25040
+ const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
25041
+ 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}`;
25042
+ if (error instanceof DispatchServiceError)
25043
+ throw refusalWithCode(error, taken, landed);
25044
+ throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
25045
+ }
25046
+ refuseUnsavedRepository("updated", after, repo);
25047
+ const links = after.external_links ?? [];
25048
+ const linkCount = `(${links.length} ${links.length === 1 ? "link" : "links"})`;
25049
+ const stated = (after.advances ?? []).filter((advance) => !advance.inherited).map((advance) => advance.id);
25050
+ const changes = [
25051
+ ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
25052
+ ...status === undefined ? [] : [`status ${before.status} -> ${after.status}`],
25053
+ ...title === undefined ? [] : [`title "${after.title}"`],
25054
+ ...labels === undefined ? [] : [
25055
+ (after.labels ?? []).length === 0 ? "labels cleared" : `labels ${(after.labels ?? []).join(", ")}`
25056
+ ],
25057
+ ...priority === undefined ? [] : [after.priority === null ? "priority cleared" : `priority -> P${after.priority}`],
25058
+ ...assignee === undefined ? [] : [after.assignee === null ? "assignee cleared" : `assignee -> ${after.assignee}`],
25059
+ ...rank === undefined ? [] : [
25060
+ `rank -> ${[
25061
+ ...rankAfter === undefined ? [] : [`after ${rankAfter}`],
25062
+ ...rankBefore === undefined ? [] : [`before ${rankBefore}`]
25063
+ ].join(", ")}`
25064
+ ],
25065
+ ...requestedLinks === undefined ? [] : [
25066
+ requestedLinks.length === 0 ? "external links cleared" : newLinks.length === 0 ? `already linked ${requestedLinks.join(", ")} ${linkCount}` : `linked ${newLinks.join(", ")} ${linkCount}`
25067
+ ],
25068
+ ...route === undefined ? [] : [after.route === null ? "route cleared" : `route ${after.route}`],
25069
+ ...parent === undefined ? [] : [after.parent === null ? "parent cleared" : `parent -> ${after.parent}`],
25070
+ ...blockedBy === undefined ? [] : [
25071
+ (after.blocked_by ?? []).length === 0 ? "blocked_by cleared" : `blocked by ${(after.blocked_by ?? []).join(", ")}`
25072
+ ],
25073
+ ...advances === undefined ? [] : [stated.length === 0 ? "advances cleared" : `advances ${stated.join(", ")}`],
25074
+ ...components === undefined ? [] : [componentsChange(components, after.components)],
25075
+ ...repo === undefined ? [] : [
25076
+ after.repo === null ? `repo cleared (resolves to ${after.resolved_repo ?? "none"})` : `repo -> ${after.repo}`
25077
+ ]
25078
+ ];
25079
+ const adviceLines = renderAdvice(input.tool, after.key, after.advice, {
25080
+ setsStatus: status !== undefined
25098
25081
  });
25099
- const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
25100
- const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
25101
- const asked = waitsOnPerson(ask);
25102
25082
  return {
25103
25083
  text: [
25104
- `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
25105
- ...checkLines,
25106
- ...declinedLines,
25107
- await followsAsk(askOwner, input.subscriptions),
25084
+ `${after.key}: ${changes.join("; ")}${await notSubscribed(issueTopic(after.key), input.subscriptions)}`,
25108
25085
  ...adviceLines
25109
25086
  ].join(`
25110
25087
  `),
25111
25088
  details: {
25112
- ...await followedAskDetails(client, ask, resolved?.artifact),
25113
- ...ask.advice === undefined ? {} : { advice: ask.advice }
25089
+ issue: after.key,
25090
+ status: after.status,
25091
+ external_links: (after.external_links ?? []).map((link) => link.url),
25092
+ ...closingNote === undefined ? {} : { message: closingNote.id },
25093
+ ...after.advice === undefined ? {} : { advice: after.advice }
25114
25094
  }
25115
25095
  };
25116
25096
  }
25117
- async function editAskCommand(context) {
25118
- const { args, client, actor, input } = context;
25119
- const question = optionalString(args, "question");
25120
- const options = args.options;
25121
- const multiple = optionalBoolean(args, "multiple");
25122
- const urgency = askUrgency(args);
25123
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
25124
- const ask = await client.editAsk(id, {
25125
- ...question === undefined ? {} : { question },
25126
- ...Array.isArray(options) ? { options } : {},
25127
- ...multiple === undefined ? {} : { multiple },
25128
- ...urgency === undefined ? {} : { urgency },
25129
- actor
25130
- });
25131
- return {
25132
- text: `Ask edited: ${ask.question}`,
25133
- details: await askOwnerDetails(client, ask)
25134
- };
25135
- }
25136
- async function resolveAskCommand(context) {
25137
- const { args, client, actor, input } = context;
25138
- const kind = stringArg(args, "kind");
25139
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
25140
- const ask = await client.resolveAsk(id, {
25141
- kind,
25142
- reason: stringArg(args, "reason"),
25143
- actor
25144
- });
25145
- if (ask.resolution === undefined)
25146
- throw new Error("resolved ask is missing its resolution");
25147
- return {
25148
- text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
25149
- details: await askOwnerDetails(client, ask)
25150
- };
25151
- }
25152
- async function followCommand(context) {
25153
- const { args, client, actor, input } = context;
25154
- const sessionId = input.sessionId?.trim();
25155
- if (!sessionId)
25156
- throw new Error("host session id is required for dispatch follow");
25157
- const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
25158
- const action = stringArg(args, "action");
25159
- if (action === "unfollow") {
25160
- await client.unfollowAsk(ask, sessionId, actor);
25161
- return { text: `Unfollowed ask ${ask}.`, details: { ask } };
25097
+ async function claimCommand(context) {
25098
+ const { args, client, actor, input, issue } = context;
25099
+ const issueKey = issue();
25100
+ const release = optionalBoolean(args, "release") ?? false;
25101
+ let after;
25102
+ try {
25103
+ after = release ? await client.releaseIssueClaim(issueKey, { actor }) : await client.claimIssue(issueKey, { actor });
25104
+ } catch (error) {
25105
+ throw refusalWithCode(error);
25106
+ }
25107
+ const held = after.claim;
25108
+ const legionManaged = after.legion_managed_status === true;
25109
+ let text;
25110
+ if (release) {
25111
+ const released = `${issueKey}: claim released; nobody is working it now. Its status is still ${after.status}`;
25112
+ text = legionManaged ? `${released}; ${LEGION_OWNS_STATUS}` : `${released} \u2014 move it yourself if that is no longer where the work is.`;
25113
+ } else {
25114
+ if (held === null) {
25115
+ throw new Error(`Dispatch claimed ${issueKey} but answered with no claim`);
25116
+ }
25117
+ const claimed = `${issueKey}: claimed by you since ${held.at}. Its status is ${after.status}`;
25118
+ const reaches = `A person's answers, comments and messages on ${issueKey} now reach you directly.`;
25119
+ 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}`;
25162
25120
  }
25163
- const read = refRead ?? await client.getAsk(ask);
25164
- await client.followAsk(ask, sessionId, actor);
25165
25121
  return {
25166
- text: `Following ask ${ask}: its answer and replies reach this session directly.`,
25167
- details: await followedAskDetails(client, read.ask)
25122
+ text: `${text}${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
25123
+ details: { issue: issueKey, status: after.status, claim: held }
25168
25124
  };
25169
25125
  }
25170
-
25171
- // ../envoy-client/src/dispatch-commands/conversation.ts
25172
- async function resolveCommentCommand(context) {
25173
- const { args, client, actor, input } = context;
25174
- const reference = stringArg(args, "comment");
25175
- const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
25176
- let id = reference;
25177
- let document;
25178
- if (ref?.owner.kind === "issue") {
25179
- const issueKey = ref.owner.issue;
25180
- id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
25181
- } else if (ref !== null) {
25182
- const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
25183
- document = artifact;
25184
- id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
25185
- }
25186
- if (ref !== null) {
25187
- const read = await client.getComment(id);
25188
- await refuseItemOffRef(input.tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
25189
- }
25190
- const comment = await client.resolveComment(id, actor);
25191
- const { label, details } = await commentOwnerResult(client, comment, document);
25192
- return { text: `Resolved comment ${comment.id} on ${label}.`, details };
25126
+ async function searchCommand(context) {
25127
+ const { args, client, linkBase } = context;
25128
+ const query = stringArg(args, "query");
25129
+ const project = optionalString(args, "project");
25130
+ const limit = optionalNumber(args, "limit");
25131
+ const offset = optionalNumber(args, "offset");
25132
+ const search = await client.search(query, {
25133
+ ...project === undefined ? {} : { project },
25134
+ ...limit === undefined ? {} : { limit },
25135
+ ...offset === undefined ? {} : { offset }
25136
+ });
25137
+ return searchAnswer(search, query, offset, linkBase);
25193
25138
  }
25194
- async function commentCommand(context) {
25195
- const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
25196
- const artifactReference = optionalString(args, "artifact");
25197
- const owner = documentOwner();
25198
- const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
25199
- const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
25200
- const replyTo = itemReplyTo(args, "reply_to");
25201
- const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
25202
- const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
25203
- const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
25204
- const requestedTurn = optionalString(args, "turn");
25205
- const body = await writePictures(resolved, stringArg(args, "body"));
25206
- const commentInput = {
25207
- body,
25208
- ...anchored === undefined ? {} : { anchor: anchored },
25209
- ...replyTo === undefined ? {} : { reply_to: replyTo.id },
25210
- ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
25211
- ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
25212
- ...requestedTurn === undefined ? {} : { turn: requestedTurn },
25213
- actor
25214
- };
25215
- const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
25216
- const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
25217
- const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
25218
- const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
25219
- isAskReply: replyToAsk !== undefined,
25220
- replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
25139
+ async function relatedCommand(context) {
25140
+ const { args, client, linkBase } = context;
25141
+ const project = stringArg(args, "project");
25142
+ const title = optionalString(args, "title");
25143
+ const text = optionalString(args, "text");
25144
+ const excludeIssues = optionalStringArray(args, "exclude_issues");
25145
+ const keywordsOnly = optionalBoolean(args, "keywords_only");
25146
+ const suggestions = await client.related(project, {
25147
+ ...title === undefined ? {} : { title },
25148
+ ...text === undefined ? {} : { text },
25149
+ ...excludeIssues === undefined ? {} : { exclude_issues: excludeIssues },
25150
+ ...keywordsOnly === undefined ? {} : { keywords_only: keywordsOnly }
25221
25151
  });
25222
- if (replyToAsk !== undefined) {
25223
- const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
25224
- const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
25225
- return {
25226
- text: [
25227
- `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
25228
- ...moved === undefined ? [] : [moved],
25229
- ...adviceLines
25230
- ].join(`
25231
- `),
25232
- details: {
25233
- ...commentDetails,
25234
- ask: replyToAsk,
25235
- follows: { ask: replyToAsk },
25236
- ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
25237
- ...comment.advice === undefined ? {} : { advice: comment.advice }
25238
- }
25239
- };
25240
- }
25241
25152
  return {
25242
- text: [
25243
- `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
25244
- ...adviceLines
25245
- ].join(`
25153
+ text: relatedCheckLines(suggestions, {
25154
+ project,
25155
+ text: [title, text].filter((part) => part !== undefined).join(`
25246
25156
  `),
25247
- details: {
25248
- ...commentDetails,
25249
- ...comment.advice === undefined ? {} : { advice: comment.advice }
25250
- }
25157
+ linkBase
25158
+ }).join(`
25159
+ `),
25160
+ details: { project, suggestions }
25251
25161
  };
25252
25162
  }
25253
- async function suggestCommand(context) {
25254
- const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
25255
- const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
25256
- const anchored = anchor(resolved.artifact, args);
25257
- if (anchored === undefined)
25258
- throw new Error("quote is required");
25259
- const body = optionalString(args, "body");
25260
- const suggestionInput = {
25261
- ...body === undefined ? {} : { body },
25262
- anchor: anchored,
25263
- replace_with: stringArg(args, "replace_with"),
25264
- actor
25163
+ async function issuesCommand(context) {
25164
+ const { args, client } = context;
25165
+ const project = stringArg(args, "project");
25166
+ const status = optionalString(args, "status");
25167
+ const parent = optionalString(args, "parent");
25168
+ const label = optionalString(args, "label");
25169
+ const priority = optionalPriorityFilter(args, "priority");
25170
+ const updatedSince = optionalString(args, "updated_since");
25171
+ const routeStatus = optionalString(args, "route_status");
25172
+ const filters = {
25173
+ project,
25174
+ ...status === undefined ? {} : { status },
25175
+ ...parent === undefined ? {} : { parent },
25176
+ ...label === undefined ? {} : { label },
25177
+ ...priority === undefined ? {} : { priority },
25178
+ ...updatedSince === undefined ? {} : { updated_since: updatedSince },
25179
+ ...routeStatus === undefined ? {} : { route_status: routeStatus }
25265
25180
  };
25266
- const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
25181
+ const page = optionalBoolean(args, "all") === true ? await client.listAllIssues(filters).then((issues) => ({
25182
+ issues,
25183
+ total: issues.length,
25184
+ limit: issues.length,
25185
+ offset: 0
25186
+ })) : await client.listIssuePage(filters, {
25187
+ limit: optionalNumber(args, "limit") ?? DEFAULT_ISSUE_PAGE_LIMIT,
25188
+ offset: optionalNumber(args, "offset") ?? 0
25189
+ });
25190
+ const { total, limit, offset } = page;
25191
+ const rows = (page.issues ?? []).map((row) => ({
25192
+ key: row.key,
25193
+ title: row.title,
25194
+ status: row.status,
25195
+ priority: row.priority,
25196
+ parent: row.parent,
25197
+ labels: row.labels ?? [],
25198
+ open_asks: row.open_asks,
25199
+ claim: row.claim ?? null,
25200
+ route: row.route ?? null,
25201
+ route_status: row.route_status ?? null,
25202
+ route_holder: row.route_holder ?? null,
25203
+ route_status_reason: row.route_status_reason ?? null,
25204
+ updated_at: row.updated_at,
25205
+ progress: row.progress
25206
+ }));
25207
+ const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
25208
+ const isPartial = offset !== 0 || rows.length !== total;
25209
+ const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
25267
25210
  return {
25268
- text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
25269
- details: writeResultDetails(resolved, { comment: comment.id })
25211
+ text: rows.length === 0 ? `No issues in ${project}.${isPartial ? ` (${showing})` : ""}` : [
25212
+ `${rows.length} ${rows.length === 1 ? "issue" : "issues"} in ${project}` + (isPartial ? ` (${showing})` : ""),
25213
+ ...rows.map((row) => {
25214
+ const progress = progressText(row.progress, " \xB7 ");
25215
+ 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)}`);
25216
+ })
25217
+ ].join(`
25218
+ `),
25219
+ details: { issues: rows, total, offset, limit }
25270
25220
  };
25271
25221
  }
25272
- function conversationReadBack(messageId) {
25273
- return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
25222
+ var BRIEF_READING_CHARACTERS = 200;
25223
+ var COMPARISON_REASONS = {
25224
+ no_pull_request_or_branch: "the issue has no pull request and no branch to compare with",
25225
+ repository_unreadable: "Dispatch cannot read the repository",
25226
+ read_failed: "a read Dispatch made did not answer"
25227
+ };
25228
+ function learnedText(learned) {
25229
+ if (learned.kind === "read_at")
25230
+ return `Dispatch read it ${learned.at}`;
25231
+ return `GitHub updated it ${learned.at}`;
25274
25232
  }
25275
- async function messageCommand(context) {
25276
- const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
25277
- const target = messageInReplyTo(args);
25278
- const inReplyTo = target?.id;
25279
- const written = stringArg(args, "body");
25280
- if (owner === null && inReplyTo !== undefined) {
25281
- let body = written;
25282
- if (pictures.length > 0) {
25283
- const sessionId = input.sessionId?.trim();
25284
- if (!sessionId) {
25285
- throw new Error("host session id is required to send pictures in a direct-message reply");
25286
- }
25287
- body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
25288
- }
25289
- const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
25290
- if (reply.duplicate === true && reply.body === body) {
25291
- return {
25292
- 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.",
25293
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
25294
- };
25295
- }
25296
- if (reply.body !== body) {
25297
- return {
25298
- 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.",
25299
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
25300
- };
25301
- }
25302
- const readBack = conversationReadBack(inReplyTo);
25303
- const parent = reply.in_reply_to ?? undefined;
25304
- const follows = parent === inReplyTo ? undefined : parent;
25233
+ function basisText(basis) {
25234
+ const learned = basis.learned_at === undefined ? "" : ` (${learnedText(basis.learned_at)})`;
25235
+ if (basis.kind === "pull_request") {
25236
+ const number = basis.pull_request === undefined ? "" : `#${basis.pull_request} `;
25237
+ return `the head of pull request ${number}at ${basis.commit ?? "an unnamed commit"}${learned}`;
25238
+ }
25239
+ if (basis.kind === "branch")
25240
+ return `branch ${basis.branch ?? "unnamed"}${learned}`;
25241
+ return `the commit you named, ${basis.commit ?? ""}${learned}`;
25242
+ }
25243
+ function basisPlace(basis) {
25244
+ if (basis.kind === "pull_request") {
25245
+ return basis.pull_request === undefined ? "the head of a pull request" : `the head of pull request #${basis.pull_request}`;
25246
+ }
25247
+ if (basis.kind === "branch")
25248
+ return `on branch ${basis.branch ?? "unnamed"}`;
25249
+ return "the commit you named";
25250
+ }
25251
+ function commitStandsText(stands) {
25252
+ if (stands === undefined) {
25253
+ return "Where that commit stands is not known: this Dispatch server does not say";
25254
+ }
25255
+ if (stands.answer === "at_basis") {
25256
+ return stands.basis === undefined ? "That commit is one of the compared commits" : `That commit is ${basisPlace(stands.basis)}`;
25257
+ }
25258
+ if (stands.answer === "other_commit")
25259
+ return "That commit is none of the compared commits";
25260
+ return stands.reason === undefined ? "Where that commit stands is not known" : `Where that commit stands is not known: ${COMPARISON_REASONS[stands.reason]}`;
25261
+ }
25262
+ function checkWordsText(check, result) {
25263
+ const versions = `result version ${result.check_version}, check version ${check.version}`;
25264
+ if (result.check_words_moved === undefined) {
25265
+ return `Whether the check's words moved is not known (${versions})`;
25266
+ }
25267
+ 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})`;
25268
+ }
25269
+ function passStandsText(pass) {
25270
+ if (pass === undefined)
25271
+ return "Whether a pass stands is not known: this Dispatch server does not say";
25272
+ if (pass.answer === "yes") {
25273
+ const roles = pass.roles ?? [];
25274
+ return roles.length === 0 ? "A pass stands: yes" : `A pass stands: yes, from ${roles.join(", ")}`;
25275
+ }
25276
+ if (pass.answer === "no")
25277
+ return "A pass stands: no";
25278
+ return "A pass stands: not known";
25279
+ }
25280
+ function readingLines(result, brief, indent = " ") {
25281
+ const observed = result.observed;
25282
+ if (observed === "")
25283
+ return [`${indent}The role recorded no reading.`];
25284
+ const cut = brief && result.commit_stands?.answer !== "at_basis";
25285
+ if (cut && observed.length > BRIEF_READING_CHARACTERS) {
25286
+ return [
25287
+ `${indent}Reading: ${observed.slice(0, BRIEF_READING_CHARACTERS)}\u2026 (result ${result.id})`
25288
+ ];
25289
+ }
25290
+ return [`${indent}Reading: ${observed}`];
25291
+ }
25292
+ function resultLines(check, result, brief) {
25293
+ const lines = [
25294
+ ` - ${result.verdict} by ${result.role} at ${result.commit_sha}. ${commitStandsText(result.commit_stands)}. ${checkWordsText(check, result)}. Recorded ${result.created_at}. Result ${result.id}.`
25295
+ ];
25296
+ const retracted = result.retracted;
25297
+ if (retracted !== undefined) {
25298
+ lines.push(` Retracted by ${actorText(retracted.actor)} at ${retracted.created_at}. The reason: ${retracted.reason}`);
25299
+ }
25300
+ return [...lines, ...readingLines(result, brief)];
25301
+ }
25302
+ function ciCheckLines(check, ci, brief) {
25303
+ const passStandsLine = ` ${passStandsText(check.pass_stands)}.`;
25304
+ const pullRequestLine = ` Pull request line: ${ci.line}`;
25305
+ const derived = check.results?.[0];
25306
+ if (derived === undefined) {
25307
+ return [
25308
+ `- ${check.block_id} (${check.when}): no result: ${ci.detail} ${check.text}`,
25309
+ passStandsLine,
25310
+ pullRequestLine
25311
+ ];
25312
+ }
25313
+ const stands = commitStandsText(derived.commit_stands);
25314
+ return [
25315
+ `- ${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}`,
25316
+ passStandsLine,
25317
+ pullRequestLine,
25318
+ ...readingLines(derived, brief, " ")
25319
+ ];
25320
+ }
25321
+ function checkLines(check, brief) {
25322
+ if (check.ci !== undefined)
25323
+ return ciCheckLines(check, check.ci, brief);
25324
+ const bases = check.compared_with ?? [];
25325
+ const reason = check.compared_nothing;
25326
+ 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]}`;
25327
+ const results = check.results ?? [];
25328
+ return [
25329
+ `- ${check.block_id} (${check.when}). ${compared}. ${passStandsText(check.pass_stands)}.`,
25330
+ ` The check's words: ${check.text}`,
25331
+ ...results.length === 0 ? [" No result is recorded for this check."] : results.flatMap((result) => resultLines(check, result, brief))
25332
+ ];
25333
+ }
25334
+ function formatCheckResults(results, brief = false) {
25335
+ if (results.verification_artifact_id === "") {
25336
+ 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.`;
25337
+ }
25338
+ const checks = results.checks ?? [];
25339
+ if (checks.length === 0) {
25340
+ return `${results.issue}'s Verification document holds no check blocks.`;
25341
+ }
25342
+ const blocks = checks.map((check) => checkLines(check, brief).join(`
25343
+ `));
25344
+ return [`Checks of ${results.issue}:`, ...blocks].join(`
25345
+
25346
+ `);
25347
+ }
25348
+ function dryRunAsksDispatch(tool, args) {
25349
+ return tool === "dispatch_result" && args["retract"] === undefined;
25350
+ }
25351
+ async function resultCommand(context) {
25352
+ const { args, client, actor } = context;
25353
+ const retract = optionalString(args, "retract");
25354
+ if (retract !== undefined) {
25355
+ const retraction = await client.retractResult(retract, {
25356
+ actor,
25357
+ reason: stringArg(args, "reason")
25358
+ });
25305
25359
  return {
25306
- 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}`,
25360
+ text: `Retracted result ${retraction.result_id}. ${actorText(retraction.actor)} retracted it at ${retraction.created_at}. The reason: ${retraction.reason}
25361
+
25362
+ The result stays readable, and it proves nothing from now on. Record a new result where the check still needs one.`,
25307
25363
  details: {
25308
- message: reply.id,
25309
- in_reply_to: inReplyTo,
25310
- posted: true,
25311
- ...follows === undefined ? {} : { follows }
25364
+ result: retraction.result_id,
25365
+ reason: retraction.reason,
25366
+ created_at: retraction.created_at
25312
25367
  }
25313
25368
  };
25314
25369
  }
25315
- const issueKey = issue();
25316
- const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
25317
- const message = await client.message(issueKey, {
25318
- body,
25319
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
25320
- ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
25321
- actor
25322
- });
25323
- const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
25324
- const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
25370
+ const issue = stringArg(args, "issue");
25371
+ const optional = {
25372
+ ...defined("surface", optionalString(args, "surface")),
25373
+ ...defined("run", optionalString(args, "run")),
25374
+ ...defined("observed", optionalString(args, "observed")),
25375
+ ...defined("negative_control", optionalString(args, "negative_control")),
25376
+ ...defined("failed", optionalNumber(args, "failed")),
25377
+ ...defined("skipped", optionalNumber(args, "skipped")),
25378
+ ...defined("excluded", optionalNumber(args, "excluded")),
25379
+ ...defined("screenshots", optionalStringArray(args, "screenshots"))
25380
+ };
25381
+ const input = {
25382
+ actor,
25383
+ check: stringArg(args, "check"),
25384
+ role: stringArg(args, "role"),
25385
+ verdict: stringArg(args, "verdict"),
25386
+ commit: stringArg(args, "commit"),
25387
+ ...optional
25388
+ };
25389
+ if (context.input.dryRun === true) {
25390
+ const dry = await client.dryRunResult(issue, input);
25391
+ return {
25392
+ text: `Nothing was recorded: this is a dry run.
25393
+
25394
+ Pull request body line:
25395
+ ${dry.line}`,
25396
+ details: { issue, check: input.check, verdict: input.verdict, line: dry.line }
25397
+ };
25398
+ }
25399
+ let recorded;
25400
+ try {
25401
+ recorded = await client.recordResult(issue, input);
25402
+ } catch (error) {
25403
+ if (dispatchAnswered(error, 409) && error.code === "CHECK_CONTENDED") {
25404
+ throw refusalWithCode(error, "the check moved twice while this result was being written, and nothing was recorded: run the same dispatch result command again");
25405
+ }
25406
+ throw error;
25407
+ }
25325
25408
  return {
25326
- text: [
25327
- `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
25328
- ...adviceLines
25329
- ].join(`
25330
- `),
25409
+ 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}.
25410
+
25411
+ Pull request body line:
25412
+ ${recorded.line}`,
25331
25413
  details: {
25332
- issue: issueKey,
25333
- message: message.id,
25334
- ...message.advice === undefined ? {} : { advice: message.advice }
25414
+ issue,
25415
+ result: recorded.result.id,
25416
+ check: recorded.result.check_block_id,
25417
+ verdict: recorded.result.verdict,
25418
+ line: recorded.line
25335
25419
  }
25336
25420
  };
25337
25421
  }
25338
- function arrivalText(attempt) {
25339
- if (attempt === undefined)
25340
- return "Dispatch recorded no delivery attempt for it";
25341
- if (attempt.state === "failed") {
25342
- return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
25343
- }
25344
- if (attempt.state === "pending")
25345
- return "its delivery is still on its way";
25346
- if (attempt.state === "queued") {
25347
- return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
25348
- }
25349
- return `it reached that session as ${attempt.delivery}`;
25350
- }
25351
- async function sendToAgentCommand(context) {
25422
+ async function resultsCommand(context) {
25352
25423
  const { args, client } = context;
25353
- const session = stringArg(args, "session");
25354
- const inReplyTo = optionalString(args, "in_reply_to");
25355
- const message = await client.agentMessage(session, {
25356
- body: stringArg(args, "body"),
25357
- delivery: stringArg(args, "delivery"),
25358
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
25359
- });
25360
- const attempt = message.deliveries?.at(-1);
25361
- const readBack = conversationReadBack(message.id);
25362
- const arrival = arrivalText(attempt);
25424
+ const issue = stringArg(args, "issue");
25425
+ const at = optionalString(args, "at");
25426
+ const brief = optionalBoolean(args, "brief") === true;
25427
+ const results = await client.issueResults(issue, at);
25428
+ const checks = results.checks ?? [];
25363
25429
  return {
25364
- text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
25430
+ text: formatCheckResults(results, brief),
25365
25431
  details: {
25366
- session,
25367
- message: message.id,
25368
- ...attempt === undefined ? {} : { delivery: attempt.state },
25369
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
25432
+ issue,
25433
+ checks: checks.length,
25434
+ results: checks.reduce((total, check) => total + (check.results ?? []).length, 0)
25370
25435
  }
25371
25436
  };
25372
25437
  }
25373
25438
 
25374
- // ../envoy-client/src/dispatch-commands/documents.ts
25375
- import { resolve as resolvePath2 } from "path";
25376
-
25377
- // ../contracts/src/go-blank.ts
25378
- var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
25379
-
25380
- // ../envoy-client/src/dispatch-commands/documents.ts
25381
- async function blockAsks(client, resolved, state) {
25382
- const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
25383
- return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
25439
+ // ../envoy-client/src/dispatch-commands/render-graph.ts
25440
+ function referenceLines(read) {
25441
+ if (typeof read === "string")
25442
+ return [`- ${read}`];
25443
+ const edges = read.edges ?? [];
25444
+ if (edges.length === 0)
25445
+ return ["- none"];
25446
+ return edges.map(edgeLine);
25384
25447
  }
25385
- async function readUploadedFile(client, artifact, details, requested, owner, shown) {
25386
- const versions = artifact.versions ?? [];
25387
- const latest = Math.max(0, ...versions.map((version) => version.number));
25388
- const number = requested ?? latest;
25389
- const of = number === latest ? "" : ` of ${latest}`;
25390
- const bytesRoute = `GET /api/v1/artifacts/${artifact.id}/versions/${number} serves its bytes.`;
25391
- const tooLarge = (mime, bytes) => ({
25392
- text: `${oversizePictureText(artifact.name, bytes)}, so dispatch doc-read cannot show this ` + `uploaded ${mime} picture (version ${number}${of}). ${bytesRoute}`,
25393
- details
25394
- });
25395
- const stated = versions.find((version) => version.number === number);
25396
- if (artifact.kind === "image" && stated?.size !== undefined && stated.size > PICTURE_SHOWN_MAX_BYTES) {
25397
- return tooLarge(stated.mime ?? "image", stated.size);
25398
- }
25399
- const file = await client.fileVersion(artifact.id, number);
25400
- const size = `${file.bytes.length.toLocaleString("en-US")} bytes`;
25401
- if (artifact.kind === "image") {
25402
- const image = toolImage(file.bytes);
25403
- if (image !== undefined) {
25404
- const address = `dispatch://${owner}/artifact/${artifact.slug}@v${number}`;
25405
- shown?.add(address);
25406
- return {
25407
- text: `Picture ${artifact.name}: ${image.mimeType}, version ${number}${of}, ${size}.
25408
- ` + shownPictureLine(1, address, artifact.name, image.mimeType, file.bytes.length),
25409
- details,
25410
- images: [image]
25411
- };
25412
- }
25413
- if (sniffPictureType(file.bytes) !== undefined)
25414
- return tooLarge(file.mime, file.bytes.length);
25448
+ function isItemKind(kind) {
25449
+ return ITEM_KINDS.some((item) => item === kind);
25450
+ }
25451
+ function edgeLine(edge) {
25452
+ const { node } = edge;
25453
+ const excerpt = edge.excerpt === undefined ? "" : `${textHead(edge.excerpt.text)} \xB7 `;
25454
+ const block = edge.block === undefined ? "" : ` (block ${edge.block.ref ?? edge.block.id})`;
25455
+ const parent = node.parent ?? undefined;
25456
+ const item = node.kind === "block" && node.document === undefined && isItemKind(parent?.kind) ? parent : undefined;
25457
+ const source = item === undefined ? `${node.kind} ${node.ref ?? node.id}` : `${item.kind} ${item.ref ?? item.id} block ${node.block_id ?? node.id}`;
25458
+ return `- ${edge.kind} ${source} (${excerpt}${edge.created_at})${block}`;
25459
+ }
25460
+ function unavailableReason(error) {
25461
+ return dispatchAnswered(error, 404) ? "unavailable" : `unavailable: ${messageFor(error)}`;
25462
+ }
25463
+ async function graphReferences(client, query) {
25464
+ try {
25465
+ return await client.getReferences(query);
25466
+ } catch (error) {
25467
+ return unavailableReason(error);
25415
25468
  }
25416
- let text;
25469
+ }
25470
+ async function issueReferencesOrUnavailable(client, key) {
25417
25471
  try {
25418
- text = new TextDecoder("utf-8", { fatal: true }).decode(file.bytes);
25419
- } catch {
25420
- return {
25421
- 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}`,
25422
- details
25423
- };
25472
+ return await client.getIssueReferences(key);
25473
+ } catch (error) {
25474
+ return unavailableReason(error);
25424
25475
  }
25425
- return {
25426
- text: `File ${artifact.name}: ${file.mime}, version ${number}${of}, ${size}.
25427
-
25428
- ${text}`,
25429
- details
25430
- };
25431
25476
  }
25432
- var BLOCK_OPENING_CHARS = 60;
25433
- async function listDocumentBlocks(client, artifact) {
25434
- const live = await liveBlocks(client, artifact);
25435
- const { bytes, blocks } = live;
25436
- const decoder = new TextDecoder;
25437
- const lines = [
25438
- `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.`
25439
- ];
25440
- const holders = [];
25441
- for (const block of blocks) {
25442
- while (holders.length > 0 && block.from >= (holders.at(-1)?.to ?? 0))
25443
- holders.pop();
25444
- const indent = " ".repeat(holders.length);
25445
- const flat = decoder.decode(bytes.subarray(block.from, block.to)).replace(/\s+/g, " ").trim();
25446
- const points = Array.from(flat);
25447
- const opening = points.length > BLOCK_OPENING_CHARS ? `${points.slice(0, BLOCK_OPENING_CHARS).join("")}\u2026` : flat;
25448
- const { comments, asks } = block.references;
25449
- lines.push(`${indent}${block.id} ${block.type} (${block.token ?? "no token"}; ${comments} comment${comments === 1 ? "" : "s"}, ${asks} ask${asks === 1 ? "" : "s"}): ${opening}`);
25450
- for (const attribute of block.attributes ?? []) {
25451
- if (attribute.kind === "block[]" && attribute.value !== "") {
25452
- lines.push(`${indent} ${attribute.name}: ${attribute.value}`);
25453
- }
25454
- }
25455
- if (block.type === "table") {
25456
- if (block.table === undefined) {
25457
- lines.push(`${indent} This Dispatch does not report table rows yet, so no row or column index is listed.`);
25458
- } else {
25459
- for (const row of block.table.rows ?? []) {
25460
- lines.push(`${indent} row ${row.index}, ${row.id === "" ? "no id yet" : `id ${row.id}`}`);
25461
- for (const cell of row.cells ?? []) {
25462
- const under = cell.header === "" ? "" : `, under ${JSON.stringify(cell.header)}`;
25463
- lines.push(`${indent} row ${cell.row} column ${cell.column}, ${cell.id === "" ? "no id yet" : `id ${cell.id}`}${under}: ${cell.text === "" ? "(empty)" : cell.text}`);
25464
- }
25465
- }
25466
- }
25467
- }
25468
- holders.push(block);
25477
+ async function issueCoverageOrReason(client, key) {
25478
+ try {
25479
+ return await client.issueCoverage(key);
25480
+ } catch (error) {
25481
+ return unavailableReason(error);
25469
25482
  }
25470
- return { text: lines.join(`
25471
- `), token: live.token, version: live.version };
25472
25483
  }
25473
- async function refuseOpenDecisionBlocks(client, tool, resolved) {
25474
- const artifact = resolved.artifact;
25475
- const latest = artifact.approval?.latest_version;
25476
- if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
25477
- return;
25478
- const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
25479
- if (blocks.length === 0)
25480
- return;
25481
- const [documentAsks, version] = await Promise.all([
25482
- blockAsks(client, resolved),
25483
- client.docRead(artifact.id, latest)
25484
+ async function graphSections(client, ref) {
25485
+ const [incoming, outgoing] = await Promise.all([
25486
+ graphReferences(client, { to: ref }),
25487
+ graphReferences(client, { from: ref })
25484
25488
  ]);
25485
- const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
25486
- const lines = version.markdown.split(`
25487
- `);
25488
- 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`;
25489
- const open = blocks.flatMap((block) => {
25490
- const ask = asks.get(block.id);
25491
- const id = typedBlockIdAttribute(block.id);
25492
- const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
25493
- const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
25494
- const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
25495
- if (states.length === 0)
25496
- return [`${named}, which version ${latest} does not hold yet`];
25497
- if (!states.includes("open") && states.some((state) => state !== undefined))
25498
- return [];
25499
- if (ask !== undefined)
25500
- return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
25501
- const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
25502
- const sourceId = attribute("copied_from");
25503
- const document = attribute("copied_from_document");
25504
- if (sourceId === undefined || document === undefined) {
25505
- return [`${named}, whose ask Dispatch has not opened yet`];
25506
- }
25507
- const source = parseDispatchRef(document);
25508
- const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
25509
- const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
25510
- return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
25511
- });
25512
- if (open.length === 0)
25513
- return;
25514
- const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
25515
- throw new Error([
25516
- `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.`,
25517
- ...open.map((line) => `- ${line}`),
25518
- "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."
25519
- ].join(`
25520
- `));
25489
+ return graphSectionLines(incoming, outgoing);
25521
25490
  }
25522
- async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
25523
- const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
25524
- if (removing.length === 0)
25525
- return;
25526
- const artifact = resolved.artifact;
25527
- const blocks = await client.artifactBlocks(artifact.id);
25528
- const askBlocks = blocks.filter((block) => block.type === "ask");
25529
- const removed = new Set;
25530
- for (const operation of removing) {
25531
- const target = blocks.find((block) => block.id === operation.block);
25532
- if (target === undefined)
25533
- continue;
25534
- for (const block of askBlocks) {
25535
- if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
25536
- removed.add(block.id);
25537
- }
25538
- }
25539
- }
25540
- if (removed.size === 0)
25491
+ function graphSectionLines(incoming, outgoing) {
25492
+ return [
25493
+ ...typeof incoming === "string" ? [] : nodeLine(incoming.node),
25494
+ "Referenced by:",
25495
+ ...referenceLines(incoming),
25496
+ "Links:",
25497
+ ...referenceLines(outgoing)
25498
+ ];
25499
+ }
25500
+ function nodeLine(node) {
25501
+ if (node.made_by === undefined)
25502
+ return [];
25503
+ const fact = (by, time) => `${by == null || by.length === 0 ? "nobody recorded" : by.map(actorText).join(", ")}${time == null ? "" : ` at ${time}`}`;
25504
+ const made = fact(node.made_by, node.made_at);
25505
+ const changed = fact(node.changed_by, node.changed_at);
25506
+ const { parent } = node;
25507
+ 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})`}`;
25508
+ return [
25509
+ `Node: ${node.kind} ${node.ref ?? node.id} \xB7 made by ${made} \xB7 changed by ${changed}${partOf}`
25510
+ ];
25511
+ }
25512
+ function blockLines(node, ref, typed, noun = "Block") {
25513
+ const unit = ref.item === undefined ? "version" : "revision";
25514
+ const blockID = node.block_id ?? ref.block;
25515
+ const head = ref.item === undefined ? [
25516
+ `Block: ${blockID}`,
25517
+ ...typed === undefined ? [] : [`Type: ${typed.type}`],
25518
+ `Document: ${node.document ?? ref.document}`,
25519
+ ...(typed?.attributes ?? []).map((attribute) => `${attribute.name}: ${attribute.value === "" ? "(empty)" : attribute.value}`),
25520
+ ...node.changed_version === undefined ? [] : [`Changed in version: ${node.changed_version}`],
25521
+ ...node.text === undefined ? [] : ["Text:", node.text]
25522
+ ] : [
25523
+ `${noun} ${blockID} of ${ref.item.kind} ${ref.item.id}${node.changed_version === undefined ? "" : ` (changed in revision ${node.changed_version})`}:`,
25524
+ ...node.text === undefined ? [] : [node.text]
25525
+ ];
25526
+ const { pin } = node;
25527
+ if (pin === undefined)
25528
+ return head;
25529
+ 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}.`;
25530
+ return [
25531
+ ...head,
25532
+ `Pinned to ${unit}: ${pin.version}`,
25533
+ state,
25534
+ `Text at ${unit} ${pin.version}:`,
25535
+ pin.text
25536
+ ];
25537
+ }
25538
+ async function typedBlockOf(client, ref) {
25539
+ if (ref.item !== undefined || ref.block === undefined)
25541
25540
  return;
25542
- const asks = await blockAsks(client, resolved, "open");
25543
- const open = asks.filter((ask) => removed.has(ask.block_id));
25544
- if (open.length === 0)
25541
+ try {
25542
+ const blocks = ref.owner.kind === "project" ? await client.projectArtifactBlocks(ref.owner.project, ref.id) : await client.issueArtifactBlocks(ref.owner.issue, ref.id);
25543
+ return blocks.find((block) => block.id === ref.block);
25544
+ } catch {
25545
25545
  return;
25546
- const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
25547
- throw new Error([
25548
- `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
25549
- ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
25550
- "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."
25551
- ].join(`
25552
- `));
25546
+ }
25553
25547
  }
25554
- async function docEditCommand(context) {
25555
- const { args, client, actor, input, linkBase, documentOwner, resolveDocument } = context;
25556
- const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
25557
- const ops = args.ops;
25558
- const summary = optionalString(args, "summary");
25559
- const { precondition: rawPrecondition } = args;
25560
- const precondition = rawPrecondition;
25561
- await refuseRemovingOpenDecisionBlocks(client, input.tool, resolved, ops);
25562
- const edited = await client.docEdit(resolved.artifact.id, {
25563
- ops,
25564
- ...summary === undefined ? {} : { summary },
25565
- ...precondition === undefined ? {} : { precondition },
25566
- actor
25567
- });
25568
- const retyped = ops.filter((operation) => operation.op === "retype").length;
25569
- const versionText = edited.version === null ? "no new version" : `version ${edited.version.number}`;
25570
- const retypedText = retyped === 0 ? "" : `; retyped ${retyped} block${retyped === 1 ? "" : "s"}`;
25571
- const nothingChanged = edited.changed === false;
25572
- const head = nothingChanged ? `Applied ${edited.applied} ops${retypedText}; nothing changed (${versionText})` : `Applied ${edited.applied} ops${retypedText} (${versionText})`;
25573
- const unchangedOps = edited.unchanged_ops ?? [];
25574
- const unchangedText = unchangedOps.length === 0 ? "" : `; ${unchangedOps.length === 1 ? "operation" : "operations"} ${unchangedOps.join(", ")} changed nothing`;
25575
- const lostOps = edited.lost_ops;
25576
- 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`;
25577
- const applied = `${head}${unchangedText}${lostText}`;
25578
- const editAskText = ops.map((operation) => /^:{3,}ask\{.*\n([\s\S]*)/mu.exec(operation.markdown ?? operation.with ?? "")?.[1]).find((text) => text !== undefined) ?? resolved.issue?.title ?? "";
25579
- const checkLines = decisionBlockLines(edited.advice, {
25580
- project: resolved.artifact.project,
25581
- text: editAskText,
25582
- linkBase
25583
- });
25584
- const declinedLines = resolved.issue === undefined ? [] : declinedAskLines(edited.advice, resolved.issue.key, linkBase);
25585
- const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, resolvedTopic(resolved).label, edited.advice, {
25586
- isPlan: documentPlaysPlan(resolved.artifact)
25587
- }));
25588
- const written = edited.written;
25589
- const writtenLines = written === undefined || written === "" ? [] : [written];
25590
- const tokenTrailer = edited.token === undefined ? [] : [`Document token: ${edited.token}`];
25591
- return {
25592
- text: [
25593
- `${applied}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
25594
- ...checkLines,
25595
- ...declinedLines,
25596
- ...writtenLines,
25597
- ...tokenTrailer,
25598
- ...adviceLines
25599
- ].join(`
25600
- `),
25601
- details: writeResultDetails(resolved, {
25602
- applied: edited.applied,
25603
- ...edited.version === null ? {} : { version: edited.version.number },
25604
- ...nothingChanged ? { changed: false } : {},
25605
- ...lostOps === undefined ? {} : { lost_ops: lostOps },
25606
- ...edited.token === undefined ? {} : { token: edited.token },
25607
- ...edited.advice === undefined ? {} : { advice: edited.advice }
25608
- })
25609
- };
25610
- }
25611
- async function docReadCommand(context) {
25612
- const { args, client, ownerArguments, shown, documentOwner, resolveDocument } = context;
25613
- const { agentArtifact } = ownerArguments;
25614
- if (agentArtifact !== undefined) {
25615
- const artifact = await client.getAgentArtifact(agentArtifact.session, agentArtifact.slug);
25616
- if (optionalBoolean(args, "blocks") === true) {
25617
- 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.`);
25618
- }
25619
- return readUploadedFile(client, artifact, { session: agentArtifact.session, artifact: artifact.slug }, optionalNumber(args, "version") ?? agentArtifact.version, `agent/${agentArtifact.session}`, shown);
25620
- }
25621
- const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
25622
- const resolved = await resolveDocument(documentOwner(), artifactReference);
25623
- const version = optionalNumber(args, "version") ?? ownerArguments.ref?.version;
25624
- if (optionalBoolean(args, "blocks") === true) {
25625
- if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
25626
- 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.`);
25627
- }
25628
- const listed = await listDocumentBlocks(client, resolved.artifact);
25629
- const trailer = [
25630
- ...listed.token === undefined ? [] : [`Document token: ${listed.token}`],
25631
- `Document version: ${listed.version === null ? "none yet" : listed.version}`
25632
- ];
25633
- return {
25634
- text: `${listed.text}
25635
-
25636
- ${trailer.join(`
25637
- `)}`,
25638
- details: resolved.owner.kind === "project" ? {
25639
- project: resolved.artifact.project,
25640
- document: documentLabel(resolved.artifact.project, resolved.artifact.slug)
25641
- } : { issue: resolved.issue?.key }
25642
- };
25643
- }
25644
- if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
25645
- const { artifact } = resolved;
25646
- return readUploadedFile(client, artifact, resolved.owner.kind === "project" ? {
25647
- project: artifact.project,
25648
- document: documentLabel(artifact.project, artifact.slug)
25649
- } : { issue: resolved.issue?.key }, version, resolved.owner.kind === "project" ? resolved.owner.project : resolved.owner.issue, shown);
25650
- }
25651
- const documentPromise = client.docRead(resolved.artifact.id, version);
25652
- const threadsPromise = openAnchoredThreads(client, resolved);
25653
- const threadsResultPromise = threadsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
25654
- const document = await documentPromise;
25655
- const threadsResult = await threadsResultPromise;
25656
- if (threadsResult.status === "rejected")
25657
- throw threadsResult.reason;
25658
- const threads = threadsResult.value;
25659
- const approval = approvalLine(resolved.artifact, typeof resolved.issue?.closed_at === "string");
25660
- const trailer = [
25661
- ..."token" in document && document.token !== undefined ? [`Document token: ${document.token}`] : [],
25662
- ..."sha256" in document && document.sha256 !== undefined ? [`Content: sha256:${document.sha256}`] : [],
25663
- ...approval === undefined ? [] : [approval]
25664
- ];
25665
- return {
25666
- text: [
25667
- document.markdown,
25668
- ...trailer.length === 0 ? [] : [trailer.join(`
25669
- `)],
25670
- ...threads.length === 0 ? [] : ["Open anchored threads:", ...threads]
25671
- ].join(`
25672
-
25673
- `),
25674
- details: resolved.owner.kind === "project" ? {
25675
- project: resolved.artifact.project,
25676
- document: `${resolved.artifact.project}/${resolved.artifact.slug}`
25677
- } : { issue: resolved.issue?.key }
25678
- };
25679
- }
25680
- async function requestApprovalCommand(context) {
25681
- const { args, client, actor, input, ownerArguments, documentOwner, resolveDocument } = context;
25682
- const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
25683
- const resolved = await resolveDocument(documentOwner(), artifactReference);
25684
- await refuseOpenDecisionBlocks(client, input.tool, resolved);
25685
- const includeVerification = optionalBoolean(args, "include_verification") === true;
25686
- const result = await client.requestApproval(resolved.artifact.id, {
25687
- actor,
25688
- summary: stringArg(args, "summary"),
25689
- ...includeVerification ? { include_verification: true } : {}
25690
- });
25691
- const gaps = result.coverage ?? [];
25692
- const coverageLines = result.coverage_unread ? [
25693
- `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.`
25694
- ] : gaps.length === 0 ? [] : [
25695
- `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.`
25696
- ];
25697
- if (result.ask === null) {
25698
- return {
25699
- text: [
25700
- `${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.`,
25701
- ...coverageLines
25702
- ].join(`
25703
- `),
25704
- details: {
25705
- ...resolved.owner.kind === "project" ? documentResultDetails(resolved.artifact) : { issue: resolved.issue?.key },
25706
- artifact: resolved.artifact.id,
25707
- version: result.version
25708
- }
25709
- };
25710
- }
25711
- const details = await followedAskDetails(client, result.ask, resolved.artifact);
25712
- 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.`;
25713
- const waitsOn = waitsOnPerson(result.ask);
25714
- return {
25715
- text: [
25716
- `${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.`,
25717
- ...coverageLines
25718
- ].join(`
25719
- `),
25720
- details: { ...details, artifact: resolved.artifact.id, version: result.version }
25721
- };
25722
- }
25723
- async function planApproveCommand(context) {
25724
- const { args, client, actor, documentOwner, resolveDocument } = context;
25725
- const planOwner = documentOwner();
25726
- const named = optionalString(args, "artifact");
25727
- const byRole = named === undefined && planOwner.kind === "issue" ? (await client.getIssue(planOwner.issue)).plan_artifact_id ?? "" : "";
25728
- const resolved = await resolveDocument(planOwner, named ?? (byRole || "plan.md"));
25729
- const version = numberArg(args, "version");
25730
- const review = await client.planApprove(resolved.artifact.id, { actor, version });
25731
- return {
25732
- 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.`,
25733
- details: {
25734
- issue: resolved.issue?.key,
25735
- artifact: resolved.artifact.id,
25736
- version: review.version
25737
- }
25738
- };
25739
- }
25740
- function artifactUnderName(artifacts, name) {
25741
- const written = name.trim();
25742
- return artifacts.find((held) => held.slug === written) ?? artifacts.find((held) => held.name === written);
25743
- }
25744
- function artifactNameExistsProblem(held, owner) {
25745
- const versions = held.versions ?? [];
25746
- const newest = versions[versions.length - 1];
25747
- if (newest === undefined) {
25748
- 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}`;
25749
- }
25750
- const authors = (newest.authors ?? []).map(actorText);
25751
- const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
25752
- return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${ARTIFACT_NAME_EXISTS_RULE}`;
25753
- }
25754
- var STORED_LINE_QUOTED = 200;
25755
- function quotedStoredLine(line) {
25756
- if (line.length <= STORED_LINE_QUOTED)
25757
- return JSON.stringify(line);
25758
- const head = JSON.stringify(line.slice(0, STORED_LINE_QUOTED));
25759
- return `${head} (cut after ${STORED_LINE_QUOTED} of its ${line.length} characters)`;
25760
- }
25761
- function firstStoredDifference(given, stored) {
25762
- const written = given.split(`
25763
- `);
25764
- const holds = stored.split(`
25765
- `);
25766
- for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
25767
- const wrote = written[line];
25768
- const held = holds[line];
25769
- if (wrote === held)
25770
- continue;
25771
- if (wrote === undefined && held !== undefined) {
25772
- return `the store writes a line ${line + 1}, ${quotedStoredLine(held)}`;
25773
- }
25774
- if (held === undefined && wrote !== undefined) {
25775
- return `the store drops line ${line + 1}, ${quotedStoredLine(wrote)}`;
25776
- }
25777
- if (wrote !== undefined && held !== undefined) {
25778
- return `line ${line + 1} reads ${quotedStoredLine(wrote)} and is stored as ${quotedStoredLine(held)}`;
25779
- }
25780
- }
25781
- return "the stored text differs from the text given";
25782
- }
25783
- var STORED_TEXT_PRINTED = 2000;
25784
- function storedTextPrinted(stored) {
25785
- if (stored.length <= STORED_TEXT_PRINTED)
25786
- return { text: stored, cut: "" };
25787
- const head = stored.slice(0, STORED_TEXT_PRINTED);
25788
- const lastLineFeed = head.lastIndexOf(`
25789
- `);
25790
- const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
25791
- return {
25792
- text,
25793
- cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
25794
- };
25795
- }
25796
- function storedTextProblem(given, stored, name) {
25797
- const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
25798
- const printed = storedTextPrinted(stored);
25799
- return [
25800
- `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
25801
- ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
25802
- `${printed.cut}
25803
- --- the text Dispatch stores ---
25804
- ${printed.text}`,
25805
- "--- end of the text Dispatch stores ---"
25806
- ].join("");
25807
- }
25808
- function storedTextCheckFailed(error, name) {
25809
- 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)}.`;
25810
- if (!dispatchAnswered(error, 413)) {
25811
- return `${failure} Send the upload again once that call is answered.`;
25812
- }
25813
- const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
25814
- 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}`;
25815
- }
25816
- function roundTripRouteAbsent(error) {
25817
- return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
25818
- }
25819
- function withoutFinalLineFeed(text) {
25820
- return text.endsWith(`
25821
- `) ? text.slice(0, -1) : text;
25822
- }
25823
- async function artifactCommand(context) {
25824
- const { args, client, actor, input, documentOwner, issue } = context;
25825
- const summary = optionalString(args, "summary");
25826
- const name = stringArg(args, "name");
25827
- const content = optionalString(args, "content");
25828
- const path = optionalString(args, "path");
25829
- const options = { name, ...summary === undefined ? {} : { summary }, actor };
25830
- const artifactOwner = documentOwner();
25831
- const blank = content === undefined || goBlankPattern.test(content);
25832
- if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
25833
- const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
25834
- if (held !== undefined) {
25835
- throw new ToolInputError(input.tool, [
25836
- artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`)
25837
- ]);
25838
- }
25839
- }
25840
- if (!blank) {
25841
- let stored;
25842
- try {
25843
- stored = await client.markdownRoundTrip(content);
25844
- } catch (error) {
25845
- if (!roundTripRouteAbsent(error)) {
25846
- throw new Error(storedTextCheckFailed(error, name), { cause: error });
25847
- }
25848
- }
25849
- if (stored !== undefined && withoutFinalLineFeed(stored) !== withoutFinalLineFeed(content)) {
25850
- throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
25851
- }
25852
- }
25853
- const artifactInput = path !== undefined ? {
25854
- ...options,
25855
- file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
25856
- type: Bun.file(resolvePath2(input.cwd, path)).type
25857
- })
25858
- } : content !== undefined ? { ...options, content } : options;
25859
- const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
25860
- const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
25861
- const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
25862
- const adviceLines = renderAdvice(input.tool, uploadOwner.label, result.advice, {
25863
- isPrimarySpec: result.artifact.primary || result.artifact.name === "spec.md",
25864
- isPlan: documentPlaysPlan(result.artifact)
25865
- });
25866
- return {
25867
- text: [
25868
- 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)}`,
25869
- ...adviceLines
25870
- ].join(`
25871
- `),
25872
- details: artifactOwner.kind === "project" ? {
25873
- ...documentResultDetails(result.artifact),
25874
- version: result.version.number,
25875
- ...result.advice === undefined ? {} : { advice: result.advice }
25876
- } : {
25877
- issue: issue(),
25878
- artifact: result.artifact.id,
25879
- version: result.version.number,
25880
- ...result.advice === undefined ? {} : { advice: result.advice }
25881
- }
25882
- };
25548
+ function askPartNoun(ask, node, blockID) {
25549
+ if (ask.answer?.id === blockID)
25550
+ return "Answer";
25551
+ if ((ask.options ?? []).some((option) => option.id === blockID))
25552
+ return "Option";
25553
+ const placed = (ask.revision ?? 0) > 0 && (ask.options ?? []).every((option) => option.id !== undefined) && (ask.answer === null || ask.answer.id !== undefined);
25554
+ return placed && node.pin?.state !== "removed" ? "Question" : "Part";
25883
25555
  }
25884
25556
 
25885
- // ../envoy-client/src/dispatch-commands/handoffs.ts
25886
- async function handoffWriteCommand(context) {
25887
- const { args, client, actor, input, issue } = context;
25888
- if (!input.sessionId?.trim()) {
25889
- throw new Error("host session id is required for dispatch handoff-write");
25890
- }
25891
- let recorded;
25892
- try {
25893
- recorded = await client.writeHandoff(issue(), stringArg(args, "phase"), {
25894
- actor,
25895
- body: stringArg(args, "body")
25896
- });
25897
- } catch (error) {
25898
- throw refusalWithCode(error);
25899
- }
25900
- return {
25901
- text: `Recorded the ${recorded.phase} handoff of ${recorded.issue_key}, version ${recorded.version} (id ${recorded.id})`,
25902
- details: {
25903
- issue: recorded.issue_key,
25904
- phase: recorded.phase,
25905
- version: recorded.version,
25906
- handoff: recorded.id
25907
- }
25908
- };
25557
+ // ../envoy-client/src/dispatch-commands/render-item.ts
25558
+ function askSummary({ ask, replies, answers }, askRef, pictures, incoming, outgoing) {
25559
+ const answer = ask.answer;
25560
+ const earlierAnswers = (answers ?? []).slice(0, -1);
25561
+ const parts = askPartEdges(ask, incoming);
25562
+ const partRef = (id) => `${askRef}#b-${encodeBlockId(id)}`;
25563
+ const chain = (replies ?? []).flatMap((reply) => [
25564
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
25565
+ `Body: ${reply.body}`
25566
+ ]);
25567
+ const resolutionWords = dispatchWordsText(ask.resolution?.dispatch_words);
25568
+ return [
25569
+ `Question: ${ask.question}`,
25570
+ ...anchorLines(ask),
25571
+ "Options:",
25572
+ ...(ask.options ?? []).length === 0 ? ["- none"] : (ask.options ?? []).flatMap((option) => [
25573
+ `- ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}${option.id === undefined ? "" : ` (${partRef(option.id)})`}`,
25574
+ ...partReferenceLines(parts.at, option.id)
25575
+ ]),
25576
+ `State: ${ask.state}`,
25577
+ `Ask id: ${ask.id}`,
25578
+ "Answer:",
25579
+ ...answer === null ? ["- none"] : [
25580
+ `- By: ${actorActText(answer.user, answer.act)}`,
25581
+ `- Selected: ${(answer.selected ?? []).length === 0 ? "none" : (answer.selected ?? []).join(", ")}`,
25582
+ ...answer.text === null ? [] : [`- Text: ${answer.text}`],
25583
+ ...answer.id === undefined ? [] : [`- Reference: ${partRef(answer.id)}`],
25584
+ ...partReferenceLines(parts.at, answer.id)
25585
+ ],
25586
+ ...earlierAnswers.length === 0 ? [] : [
25587
+ "Earlier answers:",
25588
+ ...earlierAnswers.map((earlier) => `- ${earlier.at} \xB7 ${actorActText(earlier.user, earlier.act)} \xB7 ${askAnswerText(earlier)}`)
25589
+ ],
25590
+ ...ask.resolution === undefined ? [] : [
25591
+ "Resolution:",
25592
+ `- By: ${ask.resolution.actor.id}`,
25593
+ `- Kind: ${ask.resolution.kind}`,
25594
+ ...ask.resolution.reason === "" ? [] : [`- Reason: ${ask.resolution.reason}`],
25595
+ ...resolutionWords === undefined ? [] : [`- ${resolutionWords}`]
25596
+ ],
25597
+ "Replies:",
25598
+ ...chain.length === 0 ? ["- none"] : chain,
25599
+ ...pictures,
25600
+ ...graphSectionLines(parts.rest, outgoing)
25601
+ ].join(`
25602
+ `);
25909
25603
  }
25910
- async function handoffReadCommand(context) {
25911
- const { args, client, issue } = context;
25912
- const issueKey = issue();
25913
- const phase = stringArg(args, "phase");
25914
- const version = optionalNumber(args, "version");
25915
- let handoff;
25916
- try {
25917
- if (version === undefined) {
25918
- handoff = await client.latestHandoff(issueKey, phase);
25919
- } else {
25920
- const listed = await client.listHandoffs(issueKey);
25921
- const ofPhase = listed.filter((summary) => summary.phase === phase);
25922
- const match = ofPhase.find((summary) => summary.version === version);
25923
- if (match === undefined) {
25924
- const newest = Math.max(0, ...ofPhase.map((summary) => summary.version));
25925
- 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}`}`);
25926
- }
25927
- handoff = await client.handoff(match.id);
25928
- }
25929
- } catch (error) {
25930
- throw refusalWithCode(error);
25931
- }
25932
- return {
25933
- text: `${handoff.issue_key} ${handoff.phase} handoff, version ${handoff.version} (id ${handoff.id}), written by ${actorText(handoff.author)} at ${handoff.created_at}
25934
- ${handoff.body}`,
25935
- details: {
25936
- issue: handoff.issue_key,
25937
- phase: handoff.phase,
25938
- version: handoff.version,
25939
- handoff: handoff.id
25604
+ function askPartEdges(ask, incoming) {
25605
+ const ids = new Set([...(ask.options ?? []).map((option) => option.id), ask.answer?.id].filter((id) => id !== undefined));
25606
+ const at = new Map;
25607
+ if (typeof incoming === "string" || ids.size === 0)
25608
+ return { at, rest: incoming };
25609
+ const rest = [];
25610
+ for (const edge of incoming.edges ?? []) {
25611
+ const part = edge.block?.block_id;
25612
+ if (part === undefined || !ids.has(part)) {
25613
+ rest.push(edge);
25614
+ continue;
25940
25615
  }
25941
- };
25942
- }
25943
-
25944
- // ../envoy-client/src/dispatch-commands/render-issue.ts
25945
- function componentsLine(components) {
25946
- const ids = components.ids ?? [];
25947
- const unknown = components.unknown ?? [];
25948
- const inherited = components.inherited_from === null ? "" : ` (inherited from ${components.inherited_from})`;
25949
- const retired = unknown.length === 0 ? "" : ` (retired: ${unknown.join(", ")})`;
25950
- switch (components.mode) {
25951
- case "explicit":
25952
- return `Components: ${ids.length === 0 ? "none live" : ids.join(", ")}${inherited}${retired}`;
25953
- case "none":
25954
- return `Components: none \u2014 ${components.reason ?? ""}${inherited}`;
25955
- case "inherit":
25956
- return "Components: unassigned";
25957
- default:
25958
- return `Components: ${components.mode}${inherited}${retired}`;
25959
- }
25960
- }
25961
- function advanceText(advance) {
25962
- return `${advance.id} (${advance.inherited ? "inherited" : "own"})`;
25963
- }
25964
- function advancesLine(issue) {
25965
- if (issue.advances === undefined) {
25966
- return "Advances: unknown (this Dispatch server predates priorities; upgrade it)";
25967
- }
25968
- const advances = issue.advances ?? [];
25969
- if (advances.length === 0)
25970
- return "Advances: no priority";
25971
- return `Advances: ${advances.map(advanceText).join(", ")}`;
25972
- }
25973
- function claimText(claim, agents, read = {}) {
25974
- const titles = agents?.titles;
25975
- const liveness = holderLiveness(claim, agents, read);
25976
- const holding = claimHolds(claim, titles, liveness);
25977
- const takeableAt = claimTakeableAt(liveness);
25978
- const unresponsive = liveness.holder_state === "unresponsive" && liveness.last_seen != null ? ` \xB7 unresponsive since ${liveness.last_seen}${takeableAt === null ? "" : `, takeable at ${takeableAt}`}` : " \xB7 unresponsive";
25979
- const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : holding === "unresponsive" ? unresponsive : "";
25980
- return `${actorLabel(claim.actor, titles)} since ${claim.at}${marker}`;
25981
- }
25982
- function holderLiveness(claim, agents, read) {
25983
- if (claim.actor.kind !== "session")
25984
- return read;
25985
- const row = agents?.liveness.get(claim.actor.id);
25986
- if (row === undefined)
25987
- return read;
25988
- const holderState = read.holder_state ?? row.holder_state;
25989
- const lastSeen = read.last_seen ?? row.last_seen;
25990
- const takeableAt = read.takeable_at ?? row.takeable_at;
25991
- return {
25992
- ...holderState === undefined ? {} : { holder_state: holderState },
25993
- ...lastSeen === undefined ? {} : { last_seen: lastSeen },
25994
- ...takeableAt === undefined ? {} : { takeable_at: takeableAt }
25995
- };
25996
- }
25997
- async function liveAgents(client, needed) {
25998
- if (!needed) {
25999
- return;
26000
- }
26001
- try {
26002
- const agents = await client.listAgents();
26003
- return {
26004
- titles: new Map(agents.map((agent) => [agent.session_id, agent.title])),
26005
- liveness: new Map(agents.map((agent) => [agent.session_id, agentLiveness(agent)]))
26006
- };
26007
- } catch {
26008
- return;
25616
+ const { block: _block, ...atPart } = edge;
25617
+ const held = at.get(part);
25618
+ if (held === undefined)
25619
+ at.set(part, [atPart]);
25620
+ else
25621
+ held.push(atPart);
26009
25622
  }
25623
+ return { at, rest: { node: incoming.node, edges: rest } };
26010
25624
  }
26011
- function agentLiveness(agent) {
26012
- return {
26013
- ...agent.state === undefined ? {} : { holder_state: agent.state },
26014
- ...agent.last_seen > 0 ? { last_seen: new Date(agent.last_seen).toISOString() } : {}
26015
- };
25625
+ function partReferenceLines(at, id) {
25626
+ const edges = id === undefined ? undefined : at.get(id);
25627
+ if (edges === undefined || edges.length === 0)
25628
+ return [];
25629
+ return [" Referenced by:", ...edges.map((edge) => ` ${edgeLine(edge)}`)];
26016
25630
  }
26017
- function holdsSession(claim) {
26018
- return claim?.actor.kind === "session";
25631
+ function openAskAge(ageSeconds) {
25632
+ const seconds = Math.max(0, Math.floor(ageSeconds));
25633
+ if (seconds < 60)
25634
+ return `${seconds}s`;
25635
+ const minutes = Math.floor(seconds / 60);
25636
+ if (minutes < 60)
25637
+ return `${minutes}m${seconds % 60 === 0 ? "" : ` ${seconds % 60}s`}`;
25638
+ const hours = Math.floor(minutes / 60);
25639
+ if (hours < 24)
25640
+ return `${hours}h${minutes % 60 === 0 ? "" : ` ${minutes % 60}m`}`;
25641
+ const days = Math.floor(hours / 24);
25642
+ return `${days}d${hours % 24 === 0 ? "" : ` ${hours % 24}h`}`;
26019
25643
  }
26020
- function isRouteStatus(value) {
26021
- return ISSUE_ROUTE_STATUSES.some((status) => status === value);
25644
+ function namedPerson(person) {
25645
+ return person === undefined || person === "" ? undefined : person;
26022
25646
  }
26023
- function routeHeldBySession(issue) {
26024
- return issue.route_status === "live" && issue.route?.startsWith("role:") === true;
25647
+ function waitsOnPerson(ask) {
25648
+ return namedPerson(ask.waiting_on_person);
26025
25649
  }
26026
- function routeText(issue, titles) {
26027
- if (issue.route === null)
26028
- return "none";
26029
- const holder = issue.route_holder ?? null;
26030
- const reach = {
26031
- live: routeHeldBySession(issue) && holder !== null ? ` (held by ${titles?.get(holder) ?? holder})` : "",
26032
- 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)",
26033
- no_holder: issue.route.startsWith("role:") ? " (nobody holds it right now)" : " (that session is not running right now)",
26034
- 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)"
26035
- };
26036
- const status = issue.route_status;
26037
- return issue.route + (status != null && isRouteStatus(status) ? reach[status] : "");
25650
+ function openAskLine(ask, linkBase) {
25651
+ const priority = ask.priority === null ? "" : `P${ask.priority} \xB7 `;
25652
+ return `- ${openAskAge(ask.age_seconds)} \xB7 ${priority}${ownerTitle(ask.owner)} \xB7 asked of ${waitsOnPerson(ask) ?? "nobody"} \xB7 ${ask.question} \xB7 ${linkFor(ask.ref, linkBase)}`;
26038
25653
  }
26039
- function progressText(progress, sep) {
26040
- if (progress === undefined)
26041
- return "";
26042
- const parts = [];
26043
- if (progress.tasks !== null)
26044
- parts.push(`tasks ${progress.tasks.done}/${progress.tasks.total}`);
26045
- if (progress.children !== null) {
26046
- parts.push(`children ${progress.children.done}/${progress.children.total}`);
25654
+ function formatOpenAsksSummary(response, linkBase) {
25655
+ const scope = "active open asks you authored on open issues and project documents";
25656
+ if (response.count === 0) {
25657
+ return ["There are no unanswered asks for this session.", `Scope: ${scope}.`].join(`
25658
+ `);
26047
25659
  }
26048
- return parts.join(sep);
25660
+ const waitingOnHuman = (response.asks ?? []).filter((ask) => ask.waiting_on === "human");
25661
+ const waitingOnAgent = (response.asks ?? []).filter((ask) => ask.waiting_on === "agent");
25662
+ return [
25663
+ `${response.count} unanswered ${response.count === 1 ? "ask" : "asks"} you authored on active issues and project documents.`,
25664
+ "",
25665
+ `Waiting on human (${waitingOnHuman.length}):`,
25666
+ ...waitingOnHuman.map((ask) => openAskLine(ask, linkBase)),
25667
+ "",
25668
+ `Waiting on agent (${waitingOnAgent.length}):`,
25669
+ ...waitingOnAgent.map((ask) => openAskLine(ask, linkBase))
25670
+ ].join(`
25671
+ `);
26049
25672
  }
26050
- function repositoryLine(issue) {
26051
- if (issue.resolved_repo === undefined) {
26052
- return "Repository: unknown (this Dispatch server predates repository fields; upgrade it)";
26053
- }
26054
- if (issue.resolved_repo === null)
26055
- return "Repository: none";
26056
- if (issue.repo !== null && issue.repo !== undefined)
26057
- return `Repository: ${issue.repo} (own)`;
26058
- return `Repository: ${issue.resolved_repo} (inherited or project default)`;
25673
+ function commentSummary({ comment, replies }, graph) {
25674
+ const root = [
25675
+ `${comment.id} \xB7 ${actorText(comment.author)}`,
25676
+ ...anchorLines(comment),
25677
+ ...replyBlockLines(comment),
25678
+ `Body: ${comment.body}`
25679
+ ];
25680
+ const chain = (replies ?? []).flatMap((reply) => [
25681
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
25682
+ ...anchorLines(reply),
25683
+ ...replyBlockLines(reply),
25684
+ ...reply.answers != null && reply.answers !== comment.id ? [`Answers: ${reply.answers}`] : [],
25685
+ `Body: ${reply.body}`
25686
+ ]);
25687
+ return [
25688
+ "Comment:",
25689
+ ...root,
25690
+ "Reply chain:",
25691
+ ...chain.length === 0 ? ["- none"] : chain,
25692
+ ...graph
25693
+ ].join(`
25694
+ `);
26059
25695
  }
26060
- function olderServerWarnings(issue) {
26061
- const warnings = [
26062
- ...issue.resolved_repo !== undefined ? [] : [
26063
- `dispatch: warning: Dispatch issue is missing resolved_repo: this Dispatch server predates repository fields, so ${issue.key}'s repository is unknown; upgrade the server`
26064
- ],
26065
- ...issue.advances !== undefined ? [] : [
26066
- `dispatch: warning: Dispatch issue is missing advances: this Dispatch server predates priorities, so the priorities ${issue.key} advances are unknown; upgrade the server`
26067
- ]
25696
+ function replyBlockLines(record) {
25697
+ const block = record.reply_block;
25698
+ if (block === undefined || block === null)
25699
+ return [];
25700
+ return [
25701
+ block.removed ? `Re: block ${block.block_id} (removed)` : `Re: block ${block.block_id}: ${textHead(block.text)}`
26068
25702
  ];
26069
- return warnings.length === 0 ? {} : { warnings };
26070
25703
  }
26071
- function issueSummary(issue, events, references, graph, linkBase, coverage, agents) {
26072
- const asks = issue.open_asks ?? [];
26073
- const labels = issue.labels ?? [];
26074
- const links = issue.external_links ?? [];
26075
- const members = typeof references === "string" ? [] : references.members ?? [];
26076
- const spec = issue.artifacts?.find((artifact) => artifact.primary);
26077
- const specApproval = spec === undefined ? undefined : approvalLine(spec, typeof issue.closed_at === "string");
26078
- if (issue.priority === undefined)
26079
- throw new Error("Dispatch issue is missing priority");
26080
- if (issue.assignee === undefined)
26081
- throw new Error("Dispatch issue is missing assignee");
26082
- if (issue.components === undefined)
26083
- throw new Error("Dispatch issue is missing components");
26084
- if (issue.claim === undefined)
26085
- throw new Error("Dispatch issue is missing claim");
26086
- if (issue.external_links === undefined) {
26087
- throw new Error("Dispatch issue is missing external_links");
26088
- }
25704
+ function anchorLines(record) {
26089
25705
  return [
26090
- `Title: ${issue.title}`,
26091
- `Key: ${issue.key}`,
26092
- `Link: ${linkFor(`/issues/${encodeURIComponent(issue.key)}`, linkBase)}`,
26093
- `Status: ${issue.status}`,
26094
- `Assignee: ${issue.assignee ?? "unassigned"}`,
26095
- `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, agents, issue)}`,
26096
- ...issue.priority === null ? [] : [`Priority: P${issue.priority}`],
26097
- `Labels: ${labels.length === 0 ? "none" : labels.join(", ")}`,
26098
- componentsLine(issue.components),
26099
- advancesLine(issue),
26100
- `Route: ${routeText(issue, agents?.titles)}`,
26101
- repositoryLine(issue),
26102
- `Progress: ${progressText(issue.progress, ", ") || "none"}`,
26103
- ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
26104
- ...typeof coverage === "string" ? [`Coverage: ${coverage}`] : (coverage.gaps ?? []).map((gap) => `Coverage: ${gap}`),
26105
- "External links:",
26106
- ...links.length === 0 ? ["- none"] : links.map((link) => `- ${link.url}${link.kind === undefined ? "" : ` (${link.kind})`}`),
26107
- "Documents:",
26108
- ...documentListLines(issue.artifacts ?? []),
26109
- "Open asks:",
26110
- ...asks.length === 0 ? ["- none"] : asks.map((ask) => `- ${ask.id}: ${ask.question}`),
26111
- "References:",
26112
- ...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}`),
26113
- ...typeof references === "string" || !references.truncated ? [] : ["- more references beyond 8 hops"],
26114
- "Events:",
26115
- ...events.length === 0 ? ["- none"] : events.map(eventLine),
25706
+ ...record.anchor?.quote === undefined ? [] : [`> ${record.anchor.quote}`],
25707
+ ...record.anchor_block === undefined ? [] : [`Position: ${positionText(record.anchor_block)}`],
25708
+ ...record.anchor_block_error === undefined ? [] : [`Position: unavailable (${record.anchor_block_error})`]
25709
+ ];
25710
+ }
25711
+ function positionText(block) {
25712
+ const { table, path } = block;
25713
+ const segments = (path ?? []).map((entry) => `${entry.type}[${entry.index}]`);
25714
+ if (table === undefined || table.row === null)
25715
+ return segments.join(" \u203A ");
25716
+ const tableAt = (path ?? []).findIndex((entry) => entry.type === "table");
25717
+ const cells = table.cells ?? [];
25718
+ const label = (table.column === null ? cells : cells.slice(0, table.column)).map((cell) => cell.trim()).filter((cell) => cell !== "" && !/^\d+$/.test(cell)).join(" \xB7 ");
25719
+ const row = label === "" ? `row ${table.row}` : `row ${table.row} (${label})`;
25720
+ const header = table.header === null || table.header === "" ? String(table.column) : table.header;
25721
+ return [
25722
+ ...segments.slice(0, tableAt + 1),
25723
+ table.column === null ? row : `${row}, column ${header}`
25724
+ ].join(" \u203A ");
25725
+ }
25726
+ function messageSummary({ message, replies }, graph) {
25727
+ const root = [
25728
+ `${message.id} \xB7 ${actorText(message.author)}`,
25729
+ ...replyBlockLines(message),
25730
+ `Body: ${message.body}`
25731
+ ];
25732
+ const chain = (replies ?? []).flatMap((reply) => [
25733
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
25734
+ ...replyBlockLines(reply),
25735
+ `Body: ${reply.body}`
25736
+ ]);
25737
+ return [
25738
+ "Message:",
25739
+ ...root,
25740
+ "Reply chain:",
25741
+ ...chain.length === 0 ? ["- none"] : chain,
26116
25742
  ...graph
26117
25743
  ].join(`
26118
25744
  `);
26119
25745
  }
26120
- function logSummary(issue, events) {
26121
- return [
26122
- `Key: ${issue.key}`,
26123
- "Events:",
26124
- ...events.length === 0 ? ["- none"] : events.map(eventLine)
26125
- ].join(`
26126
- `);
25746
+ async function openAnchoredThreads(client, resolved) {
25747
+ const asksPromise = resolved.owner.kind === "project" ? client.getArtifactAsks(resolved.artifact.id) : Promise.resolve(resolved.issue?.open_asks ?? []);
25748
+ const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "");
25749
+ const commentsResultPromise = commentsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
25750
+ const asks = (await asksPromise).filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id);
25751
+ const commentsResult = await commentsResultPromise;
25752
+ if (commentsResult.status === "rejected" && !dispatchAnswered(commentsResult.reason, 404)) {
25753
+ throw commentsResult.reason;
25754
+ }
25755
+ const comments = commentsResult.status === "fulfilled" ? commentsResult.value : [];
25756
+ const askReplies = new Map(asks.map((ask) => [ask.id, []]));
25757
+ for (const comment of comments) {
25758
+ if (comment.ask_id)
25759
+ askReplies.get(comment.ask_id)?.push(comment);
25760
+ }
25761
+ const askThreads = asks.map((ask) => [
25762
+ `ask ${ask.id} \xB7 ${actorText(ask.author)} \xB7 ${ask.created_at}`,
25763
+ ...anchorLines(ask),
25764
+ `Question: ${ask.question}`,
25765
+ ...threadReplyLines(askReplies.get(ask.id) ?? [])
25766
+ ].join(`
25767
+ `));
25768
+ const byId = new Map(comments.map((comment) => [comment.id, comment]));
25769
+ const roots = comments.filter((comment) => comment.reply_to === null && !comment.ask_id && !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id);
25770
+ const replies = new Map(roots.map((root) => [root.id, []]));
25771
+ for (const comment of comments) {
25772
+ const root = comment.reply_to === null ? undefined : threadRootId(comment, byId);
25773
+ if (root !== undefined)
25774
+ replies.get(root)?.push(comment);
25775
+ }
25776
+ const commentThreads = roots.map((root) => [
25777
+ `comment ${root.id} \xB7 ${actorText(root.author)} \xB7 ${root.created_at}`,
25778
+ ...anchorLines(root),
25779
+ `Body: ${root.body}`,
25780
+ ...threadReplyLines(replies.get(root.id) ?? [])
25781
+ ].join(`
25782
+ `));
25783
+ return [...askThreads, ...commentThreads];
25784
+ }
25785
+ function threadReplyLines(replies) {
25786
+ return replies.flatMap((reply) => [
25787
+ `reply ${reply.id} \xB7 ${actorText(reply.author)} \xB7 ${reply.created_at}`,
25788
+ `Body: ${reply.body}`
25789
+ ]);
25790
+ }
25791
+ function threadRootId(comment, byId) {
25792
+ const seen = new Set;
25793
+ let current = comment;
25794
+ while (current.reply_to !== null) {
25795
+ if (seen.has(current.id))
25796
+ return;
25797
+ seen.add(current.id);
25798
+ const parent = byId.get(current.reply_to);
25799
+ if (parent === undefined)
25800
+ return;
25801
+ current = parent;
25802
+ }
25803
+ return current.id;
25804
+ }
25805
+
25806
+ // ../envoy-client/src/dispatch-commands/asks.ts
25807
+ function askUrgency(args) {
25808
+ const value = args.urgency;
25809
+ return ASK_URGENCIES.find((urgency) => urgency === value);
25810
+ }
25811
+ var askHintLimit = 8;
25812
+ function openAskChoices(asks, owner) {
25813
+ if (asks.length === 0)
25814
+ return `${owner} holds no open ask.`;
25815
+ const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)}\u2026 ${textHead(ask.question)}`);
25816
+ return `The open asks of ${owner} are: ${hints.join(", ")}.`;
26127
25817
  }
26128
- function eventHead(event) {
26129
- switch (event.type) {
26130
- case "ask.opened":
26131
- case "ask.anchor_refreshed":
26132
- case "ask.edited":
26133
- case "ask.handed_back":
26134
- case "ask.resolved":
26135
- return textHead(event.payload.question);
26136
- case "ask.answered": {
26137
- const previousAnswer = event.payload.previous_answer;
26138
- return `${textHead(event.payload.question)} -> ${textHead(askAnswerText(event.payload.answer))}${previousAnswer === undefined ? "" : ` (was: ${textHead(askAnswerText(previousAnswer))})`}`;
25818
+ function askIDInputProblem(asks, owner) {
25819
+ return `ask ids are uuids. Write the whole id, or at least its first 8 characters. ${openAskChoices(asks, owner)}`;
25820
+ }
25821
+ async function movedApprovalLine(client, askID) {
25822
+ const ask = (await client.getAsk(askID).catch(() => {
25823
+ return;
25824
+ }))?.ask;
25825
+ const approval = ask?.approval;
25826
+ if (ask?.kind !== "approval" || approval === undefined)
25827
+ return;
25828
+ const listed = approval.documents ?? [];
25829
+ const documents = listed.length > 0 ? listed : [
25830
+ {
25831
+ name: approval.name,
25832
+ requested_version: approval.requested_version,
25833
+ version: approval.version
26139
25834
  }
26140
- case "ask.asked_of":
26141
- return `${textHead(event.payload.question)} -> asked of ${event.payload.asked_of ?? "the assignee of its issue"}`;
26142
- case "comment.created":
26143
- case "comment.answered":
26144
- case "comment.anchor_refreshed":
26145
- case "comment.edited":
26146
- case "comment.resolved":
26147
- case "comment.reopened":
26148
- case "suggestion.accepted":
26149
- case "suggestion.rejected":
26150
- case "message.created":
26151
- case "message.answered":
26152
- return textHead(event.payload.body);
26153
- case "artifact.version":
26154
- return textHead(`${event.payload.name} v${event.payload.version.number}${event.payload.version.summary ? `: ${event.payload.version.summary}` : ""}`);
26155
- case "artifact.approved":
26156
- case "artifact.changes_requested": {
26157
- const { name, version, kind, reason } = event.payload;
26158
- const verb = event.type === "artifact.approved" ? "approved" : "changes requested";
26159
- const reviewer = kind === "plan_review" ? " by plan review" : kind === "person" ? " by a person" : "";
26160
- return textHead(`${name} v${version} ${verb}${reviewer}${reason ? `: ${reason}` : ""}`);
25835
+ ];
25836
+ const moved = movedApprovalDocuments(documents);
25837
+ if (moved.length === 0)
25838
+ return;
25839
+ const firstMoved = moved[0];
25840
+ if (firstMoved === undefined)
25841
+ return;
25842
+ const command = handBackApprovalCommand({
25843
+ owner: ask.issue_key === null ? { kind: "project", key: ask.approval_artifact?.project ?? "<project>" } : { kind: "issue", key: ask.issue_key },
25844
+ artifactID: approval.artifact_id,
25845
+ primary: ask.approval_artifact?.primary === true,
25846
+ verification: documents.length > 1 && ask.approval_artifact?.primary === true,
25847
+ summaryVersion: firstMoved.requested_version
25848
+ });
25849
+ 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}`;
25850
+ }
25851
+ async function replyToAskCandidates(client, owner, resolved) {
25852
+ if (owner.kind === "issue") {
25853
+ const issue = resolved?.issue ?? await client.getIssue(owner.issue);
25854
+ return { asks: issue.open_asks ?? [], owner: "this issue" };
25855
+ }
25856
+ if (resolved === undefined)
25857
+ throw new Error("project document is missing its resolved artifact");
25858
+ return {
25859
+ asks: await client.getArtifactAsks(resolved.artifact.id, "open"),
25860
+ owner: "this document"
25861
+ };
25862
+ }
25863
+ async function resolveReplyToAsk(tool, client, target, resolved, id) {
25864
+ const whole = normalizeUUID(id);
25865
+ if (whole !== undefined)
25866
+ return whole;
25867
+ const { asks, owner } = await replyToAskCandidates(client, target, resolved);
25868
+ if (!isIdPrefix(id)) {
25869
+ throw new ToolInputError(tool, [askIDInputProblem(asks, owner)], { aboutAFlag: false });
25870
+ }
25871
+ return resolveIdPrefix(tool, "ask", id, owner, async () => asks, {
25872
+ 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)}`
25873
+ });
25874
+ }
25875
+ var askIdShapeProblem = "ask ids are uuids (a prefix of at least 8 hex characters works)";
25876
+ async function readAskRef(tool, id, ownerName, client, list) {
25877
+ const fullID = normalizeUUID(id);
25878
+ if (fullID !== undefined) {
25879
+ try {
25880
+ return await client.getAsk(fullID);
25881
+ } catch (error) {
25882
+ if (!(error instanceof DispatchServiceError) || error.status !== 404)
25883
+ throw error;
25884
+ const blocks = (await list()).filter((ask) => ask.block_id?.toLowerCase() === fullID);
25885
+ if (blocks.length !== 1 || blocks[0] === undefined)
25886
+ throw error;
25887
+ return client.getAsk(blocks[0].id);
26161
25888
  }
26162
- case "artifact.human_edited":
26163
- return textHead(humanEditHead(event.payload));
26164
- case "issue.created": {
26165
- const forced = event.payload.forced;
26166
- const head = `status ${event.payload.status}`;
26167
- if (forced === undefined)
26168
- return head;
26169
- return forced.past.length === 0 ? `${head} \xB7 forced, the near-copy check did not answer` : `${head} \xB7 forced past ${forced.past.join(", ")}`;
25889
+ }
25890
+ const asks = await list();
25891
+ let matches = asks.filter((ask) => ask.block_id === id);
25892
+ if (matches.length === 0) {
25893
+ if (!isIdPrefix(id)) {
25894
+ throw new ToolInputError(tool, [
25895
+ `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}`
25896
+ ]);
26170
25897
  }
26171
- case "issue.updated":
26172
- case "issue.closed":
26173
- return `status ${event.payload.status}`;
26174
- default:
25898
+ const prefix = id.toLowerCase();
25899
+ matches = asks.filter((ask) => ask.id.toLowerCase().startsWith(prefix) || (ask.block_id?.toLowerCase().startsWith(prefix) ?? false));
25900
+ }
25901
+ if (matches.length === 1 && matches[0] !== undefined)
25902
+ return client.getAsk(matches[0].id);
25903
+ throw new ToolInputError(tool, [
25904
+ 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`
25905
+ ]);
25906
+ }
25907
+ async function sessionOpenAsks(client, sessionId) {
25908
+ const session = sessionId?.trim();
25909
+ if (!session)
25910
+ throw new Error("host session id is required to read this session's open asks");
25911
+ return (await client.openAsks(session)).asks ?? [];
25912
+ }
25913
+ function openAskHints(asks) {
25914
+ if (asks.length === 0)
25915
+ return "you have no open asks";
25916
+ const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)} \u2014 ${textHead(ask.question)}`);
25917
+ return `your open asks: ${hints.join("; ")}`;
25918
+ }
25919
+ async function resolveAskArgument(tool, args, client, sessionId) {
25920
+ const id = askId(args);
25921
+ if (normalizeUUID(id) === undefined && !isIdPrefix(id)) {
25922
+ const asks = await sessionOpenAsks(client, sessionId).catch(() => {
26175
25923
  return;
25924
+ });
25925
+ throw new ToolInputError(tool, [
25926
+ asks === undefined ? askIdShapeProblem : `${askIdShapeProblem}; ${openAskHints(asks)}`
25927
+ ]);
26176
25928
  }
25929
+ const resolved = await resolveIdPrefix(tool, "ask", id, "this session", () => sessionOpenAsks(client, sessionId));
25930
+ const reference = stringArg(args, "ask");
25931
+ const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
25932
+ if (ref === null)
25933
+ return { id: resolved };
25934
+ const read = await client.getAsk(resolved);
25935
+ await refuseItemOffRef(tool, "ask", ref, reference, read.ask, async () => {
25936
+ const document = await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true });
25937
+ return document.artifact.id;
25938
+ });
25939
+ return { id: resolved, read };
26177
25940
  }
26178
- function eventRef(event) {
26179
- const payload = event.payload;
26180
- const id = typeof payload === "object" && payload !== null && "id" in payload ? payload.id : undefined;
26181
- if (typeof id !== "string" || id === "" || event.issue_key === null)
26182
- return;
26183
- const kind = event.type.startsWith("message.") ? "message" : event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("ask.") ? "ask" : undefined;
26184
- return kind === undefined ? undefined : `dispatch://${event.issue_key}/${kind}/${id}`;
25941
+ async function openAsksCommand(context) {
25942
+ const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
25943
+ const client = dispatchClient();
25944
+ const project = optionalString(ownerArguments.args, "project");
25945
+ if (project !== undefined) {
25946
+ const response = await client.openAsksForProject(project);
25947
+ return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
25948
+ }
25949
+ const sessionId = input.sessionId?.trim();
25950
+ if (!sessionId)
25951
+ throw new Error("host session id is required for dispatch open-asks");
25952
+ const response = await client.openAsks(sessionId);
25953
+ return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
26185
25954
  }
26186
- function eventActorText(actor) {
26187
- const title = actor.kind === "session" ? actor.origin?.session_title : undefined;
26188
- return title === undefined || title === "" ? actorText(actor) : `${actorText(actor)} (${title})`;
25955
+ async function askCommand(context) {
25956
+ const {
25957
+ args,
25958
+ client,
25959
+ actor,
25960
+ input,
25961
+ linkBase,
25962
+ documentOwner,
25963
+ resolveDocument,
25964
+ writePictures,
25965
+ issue
25966
+ } = context;
25967
+ const anchorArgs = asObject(args.anchor);
25968
+ const owner = documentOwner();
25969
+ const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
25970
+ const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
25971
+ const options = args.options;
25972
+ const multiple = optionalBoolean(args, "multiple");
25973
+ const urgency = askUrgency(args);
25974
+ const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
25975
+ const question = await writePictures(resolved, askQuestionWithRef(args));
25976
+ const askInput = {
25977
+ question,
25978
+ ...Array.isArray(options) ? { options } : {},
25979
+ ...multiple === undefined ? {} : { multiple },
25980
+ ...urgency === undefined ? {} : { urgency },
25981
+ ...anchored === undefined ? {} : { anchor: anchored },
25982
+ actor
25983
+ };
25984
+ const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
25985
+ const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
25986
+ const checkLines = relatedCheckLines(ask.advice?.suggestions, {
25987
+ project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
25988
+ text: stringArg(args, "question"),
25989
+ linkBase
25990
+ });
25991
+ const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
25992
+ const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
25993
+ const asked = waitsOnPerson(ask);
25994
+ return {
25995
+ text: [
25996
+ `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
25997
+ ...checkLines,
25998
+ ...declinedLines,
25999
+ await followsAsk(askOwner, input.subscriptions),
26000
+ ...adviceLines
26001
+ ].join(`
26002
+ `),
26003
+ details: {
26004
+ ...await followedAskDetails(client, ask, resolved?.artifact),
26005
+ ...ask.advice === undefined ? {} : { advice: ask.advice }
26006
+ }
26007
+ };
26189
26008
  }
26190
- function eventLine(event) {
26191
- const head = eventHead(event);
26192
- const ref = eventRef(event);
26193
- return `- #${event.seq} ${event.type}${ref === undefined ? "" : ` ${ref}`} \xB7 ${eventActorText(event.actor)} \xB7 ${event.created_at}${head === undefined || head === "" ? "" : ` \xB7 ${head}`}`;
26009
+ async function editAskCommand(context) {
26010
+ const { args, client, actor, input } = context;
26011
+ const question = optionalString(args, "question");
26012
+ const options = args.options;
26013
+ const multiple = optionalBoolean(args, "multiple");
26014
+ const urgency = askUrgency(args);
26015
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
26016
+ const ask = await client.editAsk(id, {
26017
+ ...question === undefined ? {} : { question },
26018
+ ...Array.isArray(options) ? { options } : {},
26019
+ ...multiple === undefined ? {} : { multiple },
26020
+ ...urgency === undefined ? {} : { urgency },
26021
+ actor
26022
+ });
26023
+ return {
26024
+ text: `Ask edited: ${ask.question}`,
26025
+ details: await askOwnerDetails(client, ask)
26026
+ };
26194
26027
  }
26195
- function childrenSummary(issue) {
26196
- return [
26197
- `Key: ${issue.key}`,
26198
- "Children:",
26199
- ...(issue.children ?? []).length === 0 ? ["- none"] : (issue.children ?? []).map((child) => `- ${child.key}: ${child.title} (${child.status})`)
26200
- ].join(`
26201
- `);
26028
+ async function resolveAskCommand(context) {
26029
+ const { args, client, actor, input } = context;
26030
+ const kind = stringArg(args, "kind");
26031
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
26032
+ const ask = await client.resolveAsk(id, {
26033
+ kind,
26034
+ reason: stringArg(args, "reason"),
26035
+ actor
26036
+ });
26037
+ if (ask.resolution === undefined)
26038
+ throw new Error("resolved ask is missing its resolution");
26039
+ return {
26040
+ text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
26041
+ details: await askOwnerDetails(client, ask)
26042
+ };
26202
26043
  }
26203
-
26204
- // ../envoy-client/src/dispatch-commands/issues.ts
26205
- function componentsChange(input, after) {
26206
- switch (input.mode) {
26207
- case "explicit":
26208
- return `components -> explicit [${(after.ids ?? []).join(", ")}]`;
26209
- case "none":
26210
- return `components -> none (${after.reason ?? input.reason ?? ""})`;
26211
- case "inherit":
26212
- return "components -> inherit";
26213
- default:
26214
- return `components -> ${input.mode}`;
26044
+ async function followCommand(context) {
26045
+ const { args, client, actor, input } = context;
26046
+ const sessionId = input.sessionId?.trim();
26047
+ if (!sessionId)
26048
+ throw new Error("host session id is required for dispatch follow");
26049
+ const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
26050
+ const action = stringArg(args, "action");
26051
+ if (action === "unfollow") {
26052
+ await client.unfollowAsk(ask, sessionId, actor);
26053
+ return { text: `Unfollowed ask ${ask}.`, details: { ask } };
26215
26054
  }
26055
+ const read = refRead ?? await client.getAsk(ask);
26056
+ await client.followAsk(ask, sessionId, actor);
26057
+ return {
26058
+ text: `Following ask ${ask}: its answer and replies reach this session directly.`,
26059
+ details: await followedAskDetails(client, read.ask)
26060
+ };
26216
26061
  }
26217
- 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.';
26218
- 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.";
26219
- async function architectureGuidance(client, project, components) {
26220
- if (components.mode === "none" || (components.ids ?? []).length > 0)
26221
- return;
26222
- try {
26223
- if ((await client.listArchitectureSources(project)).length === 0)
26224
- return;
26225
- return `Project ${project} has an architecture model, but this issue is not linked to any of its current components. ${architectureComponentsAction}`;
26226
- } catch (error) {
26227
- return `Could not check whether project ${project} has an architecture model: ${messageFor(error)}. ${architectureComponentsAction}`;
26062
+
26063
+ // ../envoy-client/src/dispatch-commands/conversation.ts
26064
+ async function resolveCommentCommand(context) {
26065
+ const { args, client, actor, input } = context;
26066
+ const reference = stringArg(args, "comment");
26067
+ const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
26068
+ let id = reference;
26069
+ let document;
26070
+ if (ref?.owner.kind === "issue") {
26071
+ const issueKey = ref.owner.issue;
26072
+ id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
26073
+ } else if (ref !== null) {
26074
+ const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
26075
+ document = artifact;
26076
+ id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
26228
26077
  }
26229
- }
26230
- function isDuplicateCandidate(value) {
26231
- if (typeof value !== "object" || value === null)
26232
- return false;
26233
- const candidate = value;
26234
- 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";
26235
- }
26236
- function duplicateCandidates(error) {
26237
- if (error.candidates === undefined || !error.candidates.every(isDuplicateCandidate))
26238
- throw error;
26239
- return error.candidates;
26240
- }
26241
- function refuseUnsavedRepository(verb, issue, repo) {
26242
- if (repo === undefined || issue.repo !== undefined)
26243
- return;
26244
- const lost = repo === "" ? "the repository was not cleared" : `${repo} was not saved`;
26245
- throw new Error(`Dispatch ${verb} ${issue.key} without its repository: this Dispatch server predates repository fields, so ${lost}; upgrade the server`);
26246
- }
26247
- function advancesRevisionToSend(issue, named) {
26248
- if (issue.advances_revision === undefined) {
26249
- throw new Error(`Dispatch read ${issue.key} without its advances: this Dispatch server predates priorities, so nothing was sent; upgrade the server`);
26078
+ if (ref !== null) {
26079
+ const read = await client.getComment(id);
26080
+ await refuseItemOffRef(input.tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
26250
26081
  }
26251
- return named ?? issue.advances_revision;
26082
+ const comment = await client.resolveComment(id, actor);
26083
+ const { label, details } = await commentOwnerResult(client, comment, document);
26084
+ return { text: `Resolved comment ${comment.id} on ${label}.`, details };
26252
26085
  }
26253
- async function issueCommand(context) {
26254
- const { args, client, actor, input, linkBase } = context;
26255
- const project = stringArg(args, "project");
26256
- const title = stringArg(args, "title");
26257
- const parent = optionalString(args, "parent");
26258
- const external = optionalString(args, "external");
26259
- const force = optionalBoolean(args, "force");
26260
- const spec = optionalString(args, "spec");
26261
- const priority = optionalPriority(args, "priority");
26262
- const assignee = optionalString(args, "assignee");
26263
- const components = optionalComponents(args, "components");
26264
- const repo = optionalString(args, "repo");
26265
- const labels = args.labels;
26266
- const blockedBy = args.blocked_by;
26267
- const advances = optionalStringArray(args, "advances");
26268
- try {
26269
- const created = await client.issue({
26270
- project,
26271
- title,
26272
- ...parent === undefined ? {} : { parent },
26273
- ...Array.isArray(blockedBy) ? { blocked_by: blockedBy } : {},
26274
- ...advances === undefined ? {} : { advances },
26275
- ...external === undefined ? {} : { external },
26276
- ...force === undefined ? {} : { force },
26277
- ...spec === undefined ? {} : { spec },
26278
- ...priority === undefined ? {} : { priority },
26279
- ...assignee === undefined ? {} : { assignee },
26280
- ...components === undefined ? {} : { components },
26281
- ...repo === undefined ? {} : { repo },
26282
- ...Array.isArray(labels) ? { labels } : {},
26283
- actor
26284
- });
26285
- refuseUnsavedRepository(created.created ? "created" : "already holds", created, repo);
26286
- const adviceLines = await otherAdviceLines(async () => {
26287
- const componentGuidance = await architectureGuidance(client, created.project, created.components);
26288
- return [
26289
- ...renderAdvice(input.tool, created.key, created.advice, {
26290
- isPrimarySpec: spec !== undefined
26291
- }),
26292
- ...componentGuidance === undefined ? [] : [componentGuidance]
26293
- ];
26294
- });
26295
- const href = linkFor(`/issues/${encodeURIComponent(created.key)}`, linkBase);
26296
- const assigned = created.assignee === undefined ? "" : created.assignee === null ? "; unassigned" : `; assigned to ${created.assignee}`;
26297
- const suffixes = `${assigned}${await notSubscribed(issueTopic(created.key), input.subscriptions)}`;
26086
+ async function commentCommand(context) {
26087
+ const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
26088
+ const artifactReference = optionalString(args, "artifact");
26089
+ const owner = documentOwner();
26090
+ const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
26091
+ const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
26092
+ const replyTo = itemReplyTo(args, "reply_to");
26093
+ const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
26094
+ const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
26095
+ const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
26096
+ const requestedTurn = optionalString(args, "turn");
26097
+ const body = await writePictures(resolved, stringArg(args, "body"));
26098
+ const commentInput = {
26099
+ body,
26100
+ ...anchored === undefined ? {} : { anchor: anchored },
26101
+ ...replyTo === undefined ? {} : { reply_to: replyTo.id },
26102
+ ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
26103
+ ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
26104
+ ...requestedTurn === undefined ? {} : { turn: requestedTurn },
26105
+ actor
26106
+ };
26107
+ const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
26108
+ const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
26109
+ const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
26110
+ const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
26111
+ isAskReply: replyToAsk !== undefined,
26112
+ replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
26113
+ });
26114
+ if (replyToAsk !== undefined) {
26115
+ const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
26116
+ const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
26298
26117
  return {
26299
26118
  text: [
26300
- created.created ? `Created ${created.key}: ${created.title} \u2192 ${href}${suffixes}` : `Dispatch already holds ${created.key}: ${created.title} \u2192 ${href}; nothing was created${suffixes}`,
26301
- ...created.created ? relatedCheckLines(created.advice?.suggestions, {
26302
- project: created.project,
26303
- text: title,
26304
- linkBase
26305
- }) : [],
26119
+ `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
26120
+ ...moved === undefined ? [] : [moved],
26306
26121
  ...adviceLines
26307
26122
  ].join(`
26308
26123
  `),
26309
26124
  details: {
26310
- issue: created.key,
26311
- ...created.advice === undefined ? {} : { advice: created.advice }
26125
+ ...commentDetails,
26126
+ ask: replyToAsk,
26127
+ follows: { ask: replyToAsk },
26128
+ ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
26129
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
26130
+ }
26131
+ };
26132
+ }
26133
+ return {
26134
+ text: [
26135
+ `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
26136
+ ...adviceLines
26137
+ ].join(`
26138
+ `),
26139
+ details: {
26140
+ ...commentDetails,
26141
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
26142
+ }
26143
+ };
26144
+ }
26145
+ async function suggestCommand(context) {
26146
+ const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
26147
+ const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
26148
+ const anchored = anchor(resolved.artifact, args);
26149
+ if (anchored === undefined)
26150
+ throw new Error("quote is required");
26151
+ const body = optionalString(args, "body");
26152
+ const suggestionInput = {
26153
+ ...body === undefined ? {} : { body },
26154
+ anchor: anchored,
26155
+ replace_with: stringArg(args, "replace_with"),
26156
+ actor
26157
+ };
26158
+ const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
26159
+ return {
26160
+ text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
26161
+ details: writeResultDetails(resolved, { comment: comment.id })
26162
+ };
26163
+ }
26164
+ function conversationReadBack(messageId) {
26165
+ return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
26166
+ }
26167
+ async function messageCommand(context) {
26168
+ const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
26169
+ const target = messageInReplyTo(args);
26170
+ const inReplyTo = target?.id;
26171
+ const written = stringArg(args, "body");
26172
+ if (owner === null && inReplyTo !== undefined) {
26173
+ let body = written;
26174
+ if (pictures.length > 0) {
26175
+ const sessionId = input.sessionId?.trim();
26176
+ if (!sessionId) {
26177
+ throw new Error("host session id is required to send pictures in a direct-message reply");
26312
26178
  }
26313
- };
26314
- } catch (error) {
26315
- if (!(error instanceof DispatchServiceError) || error.code !== "POSSIBLE_DUPLICATE") {
26316
- throw error;
26179
+ body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
26317
26180
  }
26318
- const candidates = duplicateCandidates(error);
26181
+ const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
26182
+ if (reply.duplicate === true && reply.body === body) {
26183
+ return {
26184
+ 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.",
26185
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
26186
+ };
26187
+ }
26188
+ if (reply.body !== body) {
26189
+ return {
26190
+ 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.",
26191
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
26192
+ };
26193
+ }
26194
+ const readBack = conversationReadBack(inReplyTo);
26195
+ const parent = reply.in_reply_to ?? undefined;
26196
+ const follows = parent === inReplyTo ? undefined : parent;
26319
26197
  return {
26320
- text: [
26321
- `Not created: "${title}" is a near copy of an open issue.`,
26322
- ...candidates.map((candidate) => {
26323
- const href = linkFor(candidate.href, linkBase);
26324
- return `${candidate.key} [${candidate.status}] ${candidate.title} \u2192 ${href}`;
26325
- }),
26326
- "Read each issue above. If one is the same work, fold this into it by the duplicate rule of skill://dispatch-first.",
26327
- "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."
26328
- ].join(`
26329
- `),
26330
- details: { duplicates: candidates },
26331
- refused: true
26198
+ 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}`,
26199
+ details: {
26200
+ message: reply.id,
26201
+ in_reply_to: inReplyTo,
26202
+ posted: true,
26203
+ ...follows === undefined ? {} : { follows }
26204
+ }
26332
26205
  };
26333
26206
  }
26334
- }
26335
- async function issueUpdateCommand(context) {
26336
- const { args, client, actor, input, issue } = context;
26337
26207
  const issueKey = issue();
26338
- const status = optionalString(args, "status");
26339
- const reason = optionalString(args, "reason");
26340
- const title = optionalString(args, "title");
26341
- const route = optionalString(args, "route");
26342
- const parent = optionalString(args, "parent");
26343
- const components = optionalComponents(args, "components");
26344
- const repo = optionalString(args, "repo");
26345
- const rankBefore = optionalString(args, "before");
26346
- const rankAfter = optionalString(args, "after");
26347
- const priority = optionalPriority(args, "priority");
26348
- const assignee = optionalNullableString(args, "assignee");
26349
- const labels = Array.isArray(args.labels) ? args.labels : undefined;
26350
- const blockedBy = Array.isArray(args.blocked_by) ? args.blocked_by : undefined;
26351
- const advances = optionalStringArray(args, "advances");
26352
- const advancesRevision = optionalNumber(args, "advances_revision");
26353
- const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
26354
- let before;
26355
- try {
26356
- before = await client.getIssue(issueKey);
26357
- } catch (error) {
26358
- throw refusalWithCode(error);
26208
+ const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
26209
+ const message = await client.message(issueKey, {
26210
+ body,
26211
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
26212
+ ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
26213
+ actor
26214
+ });
26215
+ const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
26216
+ const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
26217
+ return {
26218
+ text: [
26219
+ `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
26220
+ ...adviceLines
26221
+ ].join(`
26222
+ `),
26223
+ details: {
26224
+ issue: issueKey,
26225
+ message: message.id,
26226
+ ...message.advice === undefined ? {} : { advice: message.advice }
26227
+ }
26228
+ };
26229
+ }
26230
+ function arrivalText(attempt) {
26231
+ if (attempt === undefined)
26232
+ return "Dispatch recorded no delivery attempt for it";
26233
+ if (attempt.state === "failed") {
26234
+ return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
26359
26235
  }
26360
- const advancesWrite = advances === undefined ? undefined : { advances, advances_revision: advancesRevisionToSend(before, advancesRevision) };
26361
- if (status === "done" && typeof before.closed_at === "string") {
26362
- 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`);
26236
+ if (attempt.state === "pending")
26237
+ return "its delivery is still on its way";
26238
+ if (attempt.state === "queued") {
26239
+ return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
26363
26240
  }
26364
- let closingNote;
26365
- if (reason !== undefined) {
26366
- try {
26367
- const message = await client.message(issueKey, { body: reason, actor });
26368
- closingNote = {
26369
- id: message.id,
26370
- ref: dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id)
26241
+ return `it reached that session as ${attempt.delivery}`;
26242
+ }
26243
+ async function sendToAgentCommand(context) {
26244
+ const { args, client } = context;
26245
+ const session = stringArg(args, "session");
26246
+ const inReplyTo = optionalString(args, "in_reply_to");
26247
+ const message = await client.agentMessage(session, {
26248
+ body: stringArg(args, "body"),
26249
+ delivery: stringArg(args, "delivery"),
26250
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
26251
+ });
26252
+ const attempt = message.deliveries?.at(-1);
26253
+ const readBack = conversationReadBack(message.id);
26254
+ const arrival = arrivalText(attempt);
26255
+ return {
26256
+ text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
26257
+ details: {
26258
+ session,
26259
+ message: message.id,
26260
+ ...attempt === undefined ? {} : { delivery: attempt.state },
26261
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
26262
+ }
26263
+ };
26264
+ }
26265
+
26266
+ // ../envoy-client/src/dispatch-commands/documents.ts
26267
+ import { resolve as resolvePath2 } from "path";
26268
+
26269
+ // ../contracts/src/go-blank.ts
26270
+ var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
26271
+
26272
+ // ../envoy-client/src/dispatch-commands/documents.ts
26273
+ async function blockAsks(client, resolved, state) {
26274
+ const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
26275
+ return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
26276
+ }
26277
+ async function readUploadedFile(client, artifact, details, requested, owner, shown) {
26278
+ const versions = artifact.versions ?? [];
26279
+ const latest = Math.max(0, ...versions.map((version) => version.number));
26280
+ const number = requested ?? latest;
26281
+ const of = number === latest ? "" : ` of ${latest}`;
26282
+ const bytesRoute = `GET /api/v1/artifacts/${artifact.id}/versions/${number} serves its bytes.`;
26283
+ const tooLarge = (mime, bytes) => ({
26284
+ text: `${oversizePictureText(artifact.name, bytes)}, so dispatch doc-read cannot show this ` + `uploaded ${mime} picture (version ${number}${of}). ${bytesRoute}`,
26285
+ details
26286
+ });
26287
+ const stated = versions.find((version) => version.number === number);
26288
+ if (artifact.kind === "image" && stated?.size !== undefined && stated.size > PICTURE_SHOWN_MAX_BYTES) {
26289
+ return tooLarge(stated.mime ?? "image", stated.size);
26290
+ }
26291
+ const file = await client.fileVersion(artifact.id, number);
26292
+ const size = `${file.bytes.length.toLocaleString("en-US")} bytes`;
26293
+ if (artifact.kind === "image") {
26294
+ const image = toolImage(file.bytes);
26295
+ if (image !== undefined) {
26296
+ const address = `dispatch://${owner}/artifact/${artifact.slug}@v${number}`;
26297
+ shown?.add(address);
26298
+ return {
26299
+ text: `Picture ${artifact.name}: ${image.mimeType}, version ${number}${of}, ${size}.
26300
+ ` + shownPictureLine(1, address, artifact.name, image.mimeType, file.bytes.length),
26301
+ details,
26302
+ images: [image]
26371
26303
  };
26372
- } catch (error) {
26373
- if (error instanceof DispatchWriteLandedError) {
26374
- 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 });
26304
+ }
26305
+ if (sniffPictureType(file.bytes) !== undefined)
26306
+ return tooLarge(file.mime, file.bytes.length);
26307
+ }
26308
+ let text;
26309
+ try {
26310
+ text = new TextDecoder("utf-8", { fatal: true }).decode(file.bytes);
26311
+ } catch {
26312
+ return {
26313
+ 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}`,
26314
+ details
26315
+ };
26316
+ }
26317
+ return {
26318
+ text: `File ${artifact.name}: ${file.mime}, version ${number}${of}, ${size}.
26319
+
26320
+ ${text}`,
26321
+ details
26322
+ };
26323
+ }
26324
+ var BLOCK_OPENING_CHARS = 60;
26325
+ async function listDocumentBlocks(client, artifact) {
26326
+ const live = await liveBlocks(client, artifact);
26327
+ const { bytes, blocks } = live;
26328
+ const decoder = new TextDecoder;
26329
+ const lines = [
26330
+ `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.`
26331
+ ];
26332
+ const holders = [];
26333
+ for (const block of blocks) {
26334
+ while (holders.length > 0 && block.from >= (holders.at(-1)?.to ?? 0))
26335
+ holders.pop();
26336
+ const indent = " ".repeat(holders.length);
26337
+ const flat = decoder.decode(bytes.subarray(block.from, block.to)).replace(/\s+/g, " ").trim();
26338
+ const points = Array.from(flat);
26339
+ const opening = points.length > BLOCK_OPENING_CHARS ? `${points.slice(0, BLOCK_OPENING_CHARS).join("")}\u2026` : flat;
26340
+ const { comments, asks } = block.references;
26341
+ lines.push(`${indent}${block.id} ${block.type} (${block.token ?? "no token"}; ${comments} comment${comments === 1 ? "" : "s"}, ${asks} ask${asks === 1 ? "" : "s"}): ${opening}`);
26342
+ for (const attribute of block.attributes ?? []) {
26343
+ if (attribute.kind === "block[]" && attribute.value !== "") {
26344
+ lines.push(`${indent} ${attribute.name}: ${attribute.value}`);
26375
26345
  }
26376
- 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";
26377
- if (error instanceof DispatchServiceError)
26378
- throw refusalWithCode(error, told);
26379
- throw withAccount(error, told);
26380
26346
  }
26381
- }
26382
- const existingLinks = before.external_links ?? [];
26383
- const linked = existingLinks.map((link) => link.url);
26384
- const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
26385
- const sentLinks = requestedLinks === undefined ? undefined : requestedLinks.length === 0 ? [] : [...existingLinks, ...newLinks.map((url) => ({ url }))];
26386
- const rank = rankBefore === undefined && rankAfter === undefined ? undefined : {
26387
- ...rankBefore === undefined ? {} : { before: rankBefore },
26388
- ...rankAfter === undefined ? {} : { after: rankAfter }
26389
- };
26390
- let after;
26391
- try {
26392
- after = await client.updateIssue(issueKey, {
26393
- ...status === undefined ? {} : { status },
26394
- ...title === undefined ? {} : { title },
26395
- ...labels === undefined ? {} : { labels },
26396
- ...priority === undefined ? {} : { priority },
26397
- ...assignee === undefined ? {} : { assignee },
26398
- ...route === undefined ? {} : { route },
26399
- ...parent === undefined ? {} : { parent: parent === "" ? null : parent },
26400
- ...blockedBy === undefined ? {} : { blocked_by: blockedBy },
26401
- ...advancesWrite,
26402
- ...components === undefined ? {} : { components },
26403
- ...repo === undefined ? {} : { repo: repo === "" ? null : repo },
26404
- ...sentLinks === undefined ? {} : { external_links: sentLinks },
26405
- ...rank === undefined ? {} : { rank },
26406
- actor
26407
- });
26408
- } catch (error) {
26409
- if (error instanceof DispatchWriteLandedError)
26410
- throw error;
26411
- const answered = error instanceof DispatchWriteUnsettledError ? error.last : error;
26412
- 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)` : "";
26413
- if (closingNote === undefined) {
26414
- if (taken !== "" && !(error instanceof DispatchServiceError)) {
26415
- throw withAccount(error, taken);
26347
+ if (block.type === "table") {
26348
+ if (block.table === undefined) {
26349
+ lines.push(`${indent} This Dispatch does not report table rows yet, so no row or column index is listed.`);
26350
+ } else {
26351
+ for (const row of block.table.rows ?? []) {
26352
+ lines.push(`${indent} row ${row.index}, ${row.id === "" ? "no id yet" : `id ${row.id}`}`);
26353
+ for (const cell of row.cells ?? []) {
26354
+ const under = cell.header === "" ? "" : `, under ${JSON.stringify(cell.header)}`;
26355
+ lines.push(`${indent} row ${cell.row} column ${cell.column}, ${cell.id === "" ? "no id yet" : `id ${cell.id}`}${under}: ${cell.text === "" ? "(empty)" : cell.text}`);
26356
+ }
26357
+ }
26358
+ }
26359
+ }
26360
+ holders.push(block);
26361
+ }
26362
+ return { text: lines.join(`
26363
+ `), token: live.token, version: live.version };
26364
+ }
26365
+ async function refuseOpenDecisionBlocks(client, tool, resolved) {
26366
+ const artifact = resolved.artifact;
26367
+ const latest = artifact.approval?.latest_version;
26368
+ if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
26369
+ return;
26370
+ const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
26371
+ if (blocks.length === 0)
26372
+ return;
26373
+ const [documentAsks, version] = await Promise.all([
26374
+ blockAsks(client, resolved),
26375
+ client.docRead(artifact.id, latest)
26376
+ ]);
26377
+ const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
26378
+ const lines = version.markdown.split(`
26379
+ `);
26380
+ 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`;
26381
+ const open = blocks.flatMap((block) => {
26382
+ const ask = asks.get(block.id);
26383
+ const id = typedBlockIdAttribute(block.id);
26384
+ const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
26385
+ const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
26386
+ const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
26387
+ if (states.length === 0)
26388
+ return [`${named}, which version ${latest} does not hold yet`];
26389
+ if (!states.includes("open") && states.some((state) => state !== undefined))
26390
+ return [];
26391
+ if (ask !== undefined)
26392
+ return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
26393
+ const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
26394
+ const sourceId = attribute("copied_from");
26395
+ const document = attribute("copied_from_document");
26396
+ if (sourceId === undefined || document === undefined) {
26397
+ return [`${named}, whose ask Dispatch has not opened yet`];
26398
+ }
26399
+ const source = parseDispatchRef(document);
26400
+ const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
26401
+ const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
26402
+ return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
26403
+ });
26404
+ if (open.length === 0)
26405
+ return;
26406
+ const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
26407
+ throw new Error([
26408
+ `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.`,
26409
+ ...open.map((line) => `- ${line}`),
26410
+ "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."
26411
+ ].join(`
26412
+ `));
26413
+ }
26414
+ async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
26415
+ const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
26416
+ if (removing.length === 0)
26417
+ return;
26418
+ const artifact = resolved.artifact;
26419
+ const blocks = await client.artifactBlocks(artifact.id);
26420
+ const askBlocks = blocks.filter((block) => block.type === "ask");
26421
+ const removed = new Set;
26422
+ for (const operation of removing) {
26423
+ const target = blocks.find((block) => block.id === operation.block);
26424
+ if (target === undefined)
26425
+ continue;
26426
+ for (const block of askBlocks) {
26427
+ if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
26428
+ removed.add(block.id);
26416
26429
  }
26417
- throw refusalWithCode(error, taken);
26418
26430
  }
26419
- const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
26420
- const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
26421
- 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}`;
26422
- if (error instanceof DispatchServiceError)
26423
- throw refusalWithCode(error, taken, landed);
26424
- throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
26425
26431
  }
26426
- refuseUnsavedRepository("updated", after, repo);
26427
- const links = after.external_links ?? [];
26428
- const linkCount = `(${links.length} ${links.length === 1 ? "link" : "links"})`;
26429
- const stated = (after.advances ?? []).filter((advance) => !advance.inherited).map((advance) => advance.id);
26430
- const changes = [
26431
- ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
26432
- ...status === undefined ? [] : [`status ${before.status} -> ${after.status}`],
26433
- ...title === undefined ? [] : [`title "${after.title}"`],
26434
- ...labels === undefined ? [] : [
26435
- (after.labels ?? []).length === 0 ? "labels cleared" : `labels ${(after.labels ?? []).join(", ")}`
26436
- ],
26437
- ...priority === undefined ? [] : [after.priority === null ? "priority cleared" : `priority -> P${after.priority}`],
26438
- ...assignee === undefined ? [] : [after.assignee === null ? "assignee cleared" : `assignee -> ${after.assignee}`],
26439
- ...rank === undefined ? [] : [
26440
- `rank -> ${[
26441
- ...rankAfter === undefined ? [] : [`after ${rankAfter}`],
26442
- ...rankBefore === undefined ? [] : [`before ${rankBefore}`]
26443
- ].join(", ")}`
26444
- ],
26445
- ...requestedLinks === undefined ? [] : [
26446
- requestedLinks.length === 0 ? "external links cleared" : newLinks.length === 0 ? `already linked ${requestedLinks.join(", ")} ${linkCount}` : `linked ${newLinks.join(", ")} ${linkCount}`
26447
- ],
26448
- ...route === undefined ? [] : [after.route === null ? "route cleared" : `route ${after.route}`],
26449
- ...parent === undefined ? [] : [after.parent === null ? "parent cleared" : `parent -> ${after.parent}`],
26450
- ...blockedBy === undefined ? [] : [
26451
- (after.blocked_by ?? []).length === 0 ? "blocked_by cleared" : `blocked by ${(after.blocked_by ?? []).join(", ")}`
26452
- ],
26453
- ...advances === undefined ? [] : [stated.length === 0 ? "advances cleared" : `advances ${stated.join(", ")}`],
26454
- ...components === undefined ? [] : [componentsChange(components, after.components)],
26455
- ...repo === undefined ? [] : [
26456
- after.repo === null ? `repo cleared (resolves to ${after.resolved_repo ?? "none"})` : `repo -> ${after.repo}`
26457
- ]
26458
- ];
26459
- const adviceLines = renderAdvice(input.tool, after.key, after.advice, {
26460
- setsStatus: status !== undefined
26432
+ if (removed.size === 0)
26433
+ return;
26434
+ const asks = await blockAsks(client, resolved, "open");
26435
+ const open = asks.filter((ask) => removed.has(ask.block_id));
26436
+ if (open.length === 0)
26437
+ return;
26438
+ const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
26439
+ throw new Error([
26440
+ `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
26441
+ ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
26442
+ "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."
26443
+ ].join(`
26444
+ `));
26445
+ }
26446
+ async function docEditCommand(context) {
26447
+ const { args, client, actor, input, linkBase, documentOwner, resolveDocument } = context;
26448
+ const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
26449
+ const ops = args.ops;
26450
+ const summary = optionalString(args, "summary");
26451
+ const { precondition: rawPrecondition } = args;
26452
+ const precondition = rawPrecondition;
26453
+ await refuseRemovingOpenDecisionBlocks(client, input.tool, resolved, ops);
26454
+ const edited = await client.docEdit(resolved.artifact.id, {
26455
+ ops,
26456
+ ...summary === undefined ? {} : { summary },
26457
+ ...precondition === undefined ? {} : { precondition },
26458
+ actor
26459
+ });
26460
+ const retyped = ops.filter((operation) => operation.op === "retype").length;
26461
+ const versionText = edited.version === null ? "no new version" : `version ${edited.version.number}`;
26462
+ const retypedText = retyped === 0 ? "" : `; retyped ${retyped} block${retyped === 1 ? "" : "s"}`;
26463
+ const nothingChanged = edited.changed === false;
26464
+ const head = nothingChanged ? `Applied ${edited.applied} ops${retypedText}; nothing changed (${versionText})` : `Applied ${edited.applied} ops${retypedText} (${versionText})`;
26465
+ const unchangedOps = edited.unchanged_ops ?? [];
26466
+ const unchangedText = unchangedOps.length === 0 ? "" : `; ${unchangedOps.length === 1 ? "operation" : "operations"} ${unchangedOps.join(", ")} changed nothing`;
26467
+ const lostOps = edited.lost_ops;
26468
+ 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`;
26469
+ const applied = `${head}${unchangedText}${lostText}`;
26470
+ const editAskText = ops.map((operation) => /^:{3,}ask\{.*\n([\s\S]*)/mu.exec(operation.markdown ?? operation.with ?? "")?.[1]).find((text) => text !== undefined) ?? resolved.issue?.title ?? "";
26471
+ const checkLines = decisionBlockLines(edited.advice, {
26472
+ project: resolved.artifact.project,
26473
+ text: editAskText,
26474
+ linkBase
26461
26475
  });
26476
+ const declinedLines = resolved.issue === undefined ? [] : declinedAskLines(edited.advice, resolved.issue.key, linkBase);
26477
+ const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, resolvedTopic(resolved).label, edited.advice, {
26478
+ isPlan: documentPlaysPlan(resolved.artifact)
26479
+ }));
26480
+ const written = edited.written;
26481
+ const writtenLines = written === undefined || written === "" ? [] : [written];
26482
+ const tokenTrailer = edited.token === undefined ? [] : [`Document token: ${edited.token}`];
26462
26483
  return {
26463
26484
  text: [
26464
- `${after.key}: ${changes.join("; ")}${await notSubscribed(issueTopic(after.key), input.subscriptions)}`,
26485
+ `${applied}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
26486
+ ...checkLines,
26487
+ ...declinedLines,
26488
+ ...writtenLines,
26489
+ ...tokenTrailer,
26465
26490
  ...adviceLines
26466
26491
  ].join(`
26467
26492
  `),
26468
- details: {
26469
- issue: after.key,
26470
- status: after.status,
26471
- external_links: (after.external_links ?? []).map((link) => link.url),
26472
- ...closingNote === undefined ? {} : { message: closingNote.id },
26473
- ...after.advice === undefined ? {} : { advice: after.advice }
26474
- }
26493
+ details: writeResultDetails(resolved, {
26494
+ applied: edited.applied,
26495
+ ...edited.version === null ? {} : { version: edited.version.number },
26496
+ ...nothingChanged ? { changed: false } : {},
26497
+ ...lostOps === undefined ? {} : { lost_ops: lostOps },
26498
+ ...edited.token === undefined ? {} : { token: edited.token },
26499
+ ...edited.advice === undefined ? {} : { advice: edited.advice }
26500
+ })
26475
26501
  };
26476
26502
  }
26477
- async function claimCommand(context) {
26478
- const { args, client, actor, input, issue } = context;
26479
- const issueKey = issue();
26480
- const release = optionalBoolean(args, "release") ?? false;
26481
- let after;
26482
- try {
26483
- after = release ? await client.releaseIssueClaim(issueKey, { actor }) : await client.claimIssue(issueKey, { actor });
26484
- } catch (error) {
26485
- throw refusalWithCode(error);
26486
- }
26487
- const held = after.claim;
26488
- const legionManaged = after.legion_managed_status === true;
26489
- let text;
26490
- if (release) {
26491
- const released = `${issueKey}: claim released; nobody is working it now. Its status is still ${after.status}`;
26492
- text = legionManaged ? `${released}; ${LEGION_OWNS_STATUS}` : `${released} \u2014 move it yourself if that is no longer where the work is.`;
26493
- } else {
26494
- if (held === null) {
26495
- throw new Error(`Dispatch claimed ${issueKey} but answered with no claim`);
26503
+ async function docReadCommand(context) {
26504
+ const { args, client, ownerArguments, shown, documentOwner, resolveDocument } = context;
26505
+ const { agentArtifact } = ownerArguments;
26506
+ if (agentArtifact !== undefined) {
26507
+ const artifact = await client.getAgentArtifact(agentArtifact.session, agentArtifact.slug);
26508
+ if (optionalBoolean(args, "blocks") === true) {
26509
+ 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.`);
26496
26510
  }
26497
- const claimed = `${issueKey}: claimed by you since ${held.at}. Its status is ${after.status}`;
26498
- const reaches = `A person's answers, comments and messages on ${issueKey} now reach you directly.`;
26499
- 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}`;
26511
+ return readUploadedFile(client, artifact, { session: agentArtifact.session, artifact: artifact.slug }, optionalNumber(args, "version") ?? agentArtifact.version, `agent/${agentArtifact.session}`, shown);
26500
26512
  }
26513
+ const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
26514
+ const resolved = await resolveDocument(documentOwner(), artifactReference);
26515
+ const version = optionalNumber(args, "version") ?? ownerArguments.ref?.version;
26516
+ if (optionalBoolean(args, "blocks") === true) {
26517
+ if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
26518
+ 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.`);
26519
+ }
26520
+ const listed = await listDocumentBlocks(client, resolved.artifact);
26521
+ const trailer = [
26522
+ ...listed.token === undefined ? [] : [`Document token: ${listed.token}`],
26523
+ `Document version: ${listed.version === null ? "none yet" : listed.version}`
26524
+ ];
26525
+ return {
26526
+ text: `${listed.text}
26527
+
26528
+ ${trailer.join(`
26529
+ `)}`,
26530
+ details: resolved.owner.kind === "project" ? {
26531
+ project: resolved.artifact.project,
26532
+ document: documentLabel(resolved.artifact.project, resolved.artifact.slug)
26533
+ } : { issue: resolved.issue?.key }
26534
+ };
26535
+ }
26536
+ if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
26537
+ const { artifact } = resolved;
26538
+ return readUploadedFile(client, artifact, resolved.owner.kind === "project" ? {
26539
+ project: artifact.project,
26540
+ document: documentLabel(artifact.project, artifact.slug)
26541
+ } : { issue: resolved.issue?.key }, version, resolved.owner.kind === "project" ? resolved.owner.project : resolved.owner.issue, shown);
26542
+ }
26543
+ const documentPromise = client.docRead(resolved.artifact.id, version);
26544
+ const threadsPromise = openAnchoredThreads(client, resolved);
26545
+ const threadsResultPromise = threadsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
26546
+ const document = await documentPromise;
26547
+ const threadsResult = await threadsResultPromise;
26548
+ if (threadsResult.status === "rejected")
26549
+ throw threadsResult.reason;
26550
+ const threads = threadsResult.value;
26551
+ const approval = approvalLine(resolved.artifact, typeof resolved.issue?.closed_at === "string");
26552
+ const trailer = [
26553
+ ..."token" in document && document.token !== undefined ? [`Document token: ${document.token}`] : [],
26554
+ ..."sha256" in document && document.sha256 !== undefined ? [`Content: sha256:${document.sha256}`] : [],
26555
+ ...approval === undefined ? [] : [approval]
26556
+ ];
26501
26557
  return {
26502
- text: `${text}${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
26503
- details: { issue: issueKey, status: after.status, claim: held }
26504
- };
26505
- }
26506
- async function searchCommand(context) {
26507
- const { args, client, linkBase } = context;
26508
- const query = stringArg(args, "query");
26509
- const project = optionalString(args, "project");
26510
- const limit = optionalNumber(args, "limit");
26511
- const offset = optionalNumber(args, "offset");
26512
- const search = await client.search(query, {
26513
- ...project === undefined ? {} : { project },
26514
- ...limit === undefined ? {} : { limit },
26515
- ...offset === undefined ? {} : { offset }
26516
- });
26517
- return searchAnswer(search, query, offset, linkBase);
26518
- }
26519
- async function relatedCommand(context) {
26520
- const { args, client, linkBase } = context;
26521
- const project = stringArg(args, "project");
26522
- const title = optionalString(args, "title");
26523
- const text = optionalString(args, "text");
26524
- const excludeIssues = optionalStringArray(args, "exclude_issues");
26525
- const keywordsOnly = optionalBoolean(args, "keywords_only");
26526
- const suggestions = await client.related(project, {
26527
- ...title === undefined ? {} : { title },
26528
- ...text === undefined ? {} : { text },
26529
- ...excludeIssues === undefined ? {} : { exclude_issues: excludeIssues },
26530
- ...keywordsOnly === undefined ? {} : { keywords_only: keywordsOnly }
26531
- });
26532
- return {
26533
- text: relatedCheckLines(suggestions, {
26534
- project,
26535
- text: [title, text].filter((part) => part !== undefined).join(`
26536
- `),
26537
- linkBase
26538
- }).join(`
26558
+ text: [
26559
+ document.markdown,
26560
+ ...trailer.length === 0 ? [] : [trailer.join(`
26561
+ `)],
26562
+ ...threads.length === 0 ? [] : ["Open anchored threads:", ...threads]
26563
+ ].join(`
26564
+
26539
26565
  `),
26540
- details: { project, suggestions }
26566
+ details: resolved.owner.kind === "project" ? {
26567
+ project: resolved.artifact.project,
26568
+ document: `${resolved.artifact.project}/${resolved.artifact.slug}`
26569
+ } : { issue: resolved.issue?.key }
26541
26570
  };
26542
26571
  }
26543
- async function issuesCommand(context) {
26544
- const { args, client } = context;
26545
- const project = stringArg(args, "project");
26546
- const status = optionalString(args, "status");
26547
- const parent = optionalString(args, "parent");
26548
- const label = optionalString(args, "label");
26549
- const priority = optionalPriorityFilter(args, "priority");
26550
- const updatedSince = optionalString(args, "updated_since");
26551
- const routeStatus = optionalString(args, "route_status");
26552
- const filters = {
26553
- project,
26554
- ...status === undefined ? {} : { status },
26555
- ...parent === undefined ? {} : { parent },
26556
- ...label === undefined ? {} : { label },
26557
- ...priority === undefined ? {} : { priority },
26558
- ...updatedSince === undefined ? {} : { updated_since: updatedSince },
26559
- ...routeStatus === undefined ? {} : { route_status: routeStatus }
26560
- };
26561
- const page = optionalBoolean(args, "all") === true ? await client.listAllIssues(filters).then((issues) => ({
26562
- issues,
26563
- total: issues.length,
26564
- limit: issues.length,
26565
- offset: 0
26566
- })) : await client.listIssuePage(filters, {
26567
- limit: optionalNumber(args, "limit") ?? DEFAULT_ISSUE_PAGE_LIMIT,
26568
- offset: optionalNumber(args, "offset") ?? 0
26572
+ async function requestApprovalCommand(context) {
26573
+ const { args, client, actor, input, ownerArguments, documentOwner, resolveDocument } = context;
26574
+ const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
26575
+ const resolved = await resolveDocument(documentOwner(), artifactReference);
26576
+ await refuseOpenDecisionBlocks(client, input.tool, resolved);
26577
+ const includeVerification = optionalBoolean(args, "include_verification") === true;
26578
+ const result = await client.requestApproval(resolved.artifact.id, {
26579
+ actor,
26580
+ summary: stringArg(args, "summary"),
26581
+ ...includeVerification ? { include_verification: true } : {}
26569
26582
  });
26570
- const { total, limit, offset } = page;
26571
- const rows = (page.issues ?? []).map((row) => ({
26572
- key: row.key,
26573
- title: row.title,
26574
- status: row.status,
26575
- priority: row.priority,
26576
- parent: row.parent,
26577
- labels: row.labels ?? [],
26578
- open_asks: row.open_asks,
26579
- claim: row.claim ?? null,
26580
- route: row.route ?? null,
26581
- route_status: row.route_status ?? null,
26582
- route_holder: row.route_holder ?? null,
26583
- route_status_reason: row.route_status_reason ?? null,
26584
- updated_at: row.updated_at,
26585
- progress: row.progress
26586
- }));
26587
- const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
26588
- const isPartial = offset !== 0 || rows.length !== total;
26589
- const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
26583
+ const gaps = result.coverage ?? [];
26584
+ const coverageLines = result.coverage_unread ? [
26585
+ `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.`
26586
+ ] : gaps.length === 0 ? [] : [
26587
+ `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.`
26588
+ ];
26589
+ if (result.ask === null) {
26590
+ return {
26591
+ text: [
26592
+ `${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.`,
26593
+ ...coverageLines
26594
+ ].join(`
26595
+ `),
26596
+ details: {
26597
+ ...resolved.owner.kind === "project" ? documentResultDetails(resolved.artifact) : { issue: resolved.issue?.key },
26598
+ artifact: resolved.artifact.id,
26599
+ version: result.version
26600
+ }
26601
+ };
26602
+ }
26603
+ const details = await followedAskDetails(client, result.ask, resolved.artifact);
26604
+ 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.`;
26605
+ const waitsOn = waitsOnPerson(result.ask);
26590
26606
  return {
26591
- text: rows.length === 0 ? `No issues in ${project}.${isPartial ? ` (${showing})` : ""}` : [
26592
- `${rows.length} ${rows.length === 1 ? "issue" : "issues"} in ${project}` + (isPartial ? ` (${showing})` : ""),
26593
- ...rows.map((row) => {
26594
- const progress = progressText(row.progress, " \xB7 ");
26595
- 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)}`);
26596
- })
26607
+ text: [
26608
+ `${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.`,
26609
+ ...coverageLines
26597
26610
  ].join(`
26598
26611
  `),
26599
- details: { issues: rows, total, offset, limit }
26612
+ details: { ...details, artifact: resolved.artifact.id, version: result.version }
26600
26613
  };
26601
26614
  }
26602
- var BRIEF_READING_CHARACTERS = 200;
26603
- var COMPARISON_REASONS = {
26604
- no_pull_request_or_branch: "the issue has no pull request and no branch to compare with",
26605
- repository_unreadable: "Dispatch cannot read the repository",
26606
- read_failed: "a read Dispatch made did not answer"
26607
- };
26608
- function learnedText(learned) {
26609
- if (learned.kind === "read_at")
26610
- return `Dispatch read it ${learned.at}`;
26611
- return `GitHub updated it ${learned.at}`;
26612
- }
26613
- function basisText(basis) {
26614
- const learned = basis.learned_at === undefined ? "" : ` (${learnedText(basis.learned_at)})`;
26615
- if (basis.kind === "pull_request") {
26616
- const number = basis.pull_request === undefined ? "" : `#${basis.pull_request} `;
26617
- return `the head of pull request ${number}at ${basis.commit ?? "an unnamed commit"}${learned}`;
26618
- }
26619
- if (basis.kind === "branch")
26620
- return `branch ${basis.branch ?? "unnamed"}${learned}`;
26621
- return `the commit you named, ${basis.commit ?? ""}${learned}`;
26622
- }
26623
- function basisPlace(basis) {
26624
- if (basis.kind === "pull_request") {
26625
- return basis.pull_request === undefined ? "the head of a pull request" : `the head of pull request #${basis.pull_request}`;
26626
- }
26627
- if (basis.kind === "branch")
26628
- return `on branch ${basis.branch ?? "unnamed"}`;
26629
- return "the commit you named";
26615
+ async function planApproveCommand(context) {
26616
+ const { args, client, actor, documentOwner, resolveDocument } = context;
26617
+ const planOwner = documentOwner();
26618
+ const named = optionalString(args, "artifact");
26619
+ const byRole = named === undefined && planOwner.kind === "issue" ? (await client.getIssue(planOwner.issue)).plan_artifact_id ?? "" : "";
26620
+ const resolved = await resolveDocument(planOwner, named ?? (byRole || "plan.md"));
26621
+ const version = numberArg(args, "version");
26622
+ const review = await client.planApprove(resolved.artifact.id, { actor, version });
26623
+ return {
26624
+ 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.`,
26625
+ details: {
26626
+ issue: resolved.issue?.key,
26627
+ artifact: resolved.artifact.id,
26628
+ version: review.version
26629
+ }
26630
+ };
26630
26631
  }
26631
- function commitStandsText(stands) {
26632
- if (stands === undefined) {
26633
- return "Where that commit stands is not known: this Dispatch server does not say";
26634
- }
26635
- if (stands.answer === "at_basis") {
26636
- return stands.basis === undefined ? "That commit is one of the compared commits" : `That commit is ${basisPlace(stands.basis)}`;
26637
- }
26638
- if (stands.answer === "other_commit")
26639
- return "That commit is none of the compared commits";
26640
- return stands.reason === undefined ? "Where that commit stands is not known" : `Where that commit stands is not known: ${COMPARISON_REASONS[stands.reason]}`;
26632
+ function artifactUnderName(artifacts, name) {
26633
+ const written = name.trim();
26634
+ return artifacts.find((held) => held.slug === written) ?? artifacts.find((held) => held.name === written);
26641
26635
  }
26642
- function checkWordsText(check, result) {
26643
- const versions = `result version ${result.check_version}, check version ${check.version}`;
26644
- if (result.check_words_moved === undefined) {
26645
- return `Whether the check's words moved is not known (${versions})`;
26636
+ function artifactNameExistsProblem(held, owner) {
26637
+ const versions = held.versions ?? [];
26638
+ const newest = versions[versions.length - 1];
26639
+ if (newest === undefined) {
26640
+ 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}`;
26646
26641
  }
26647
- 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})`;
26642
+ const authors = (newest.authors ?? []).map(actorText);
26643
+ const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
26644
+ return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${ARTIFACT_NAME_EXISTS_RULE}`;
26648
26645
  }
26649
- function passStandsText(pass) {
26650
- if (pass === undefined)
26651
- return "Whether a pass stands is not known: this Dispatch server does not say";
26652
- if (pass.answer === "yes") {
26653
- const roles = pass.roles ?? [];
26654
- return roles.length === 0 ? "A pass stands: yes" : `A pass stands: yes, from ${roles.join(", ")}`;
26655
- }
26656
- if (pass.answer === "no")
26657
- return "A pass stands: no";
26658
- return "A pass stands: not known";
26646
+ var STORED_LINE_QUOTED = 200;
26647
+ function quotedStoredLine(line) {
26648
+ if (line.length <= STORED_LINE_QUOTED)
26649
+ return JSON.stringify(line);
26650
+ const head = JSON.stringify(line.slice(0, STORED_LINE_QUOTED));
26651
+ return `${head} (cut after ${STORED_LINE_QUOTED} of its ${line.length} characters)`;
26659
26652
  }
26660
- function readingLines(result, brief, indent = " ") {
26661
- const observed = result.observed;
26662
- if (observed === "")
26663
- return [`${indent}The role recorded no reading.`];
26664
- const cut = brief && result.commit_stands?.answer !== "at_basis";
26665
- if (cut && observed.length > BRIEF_READING_CHARACTERS) {
26666
- return [
26667
- `${indent}Reading: ${observed.slice(0, BRIEF_READING_CHARACTERS)}\u2026 (result ${result.id})`
26668
- ];
26653
+ function firstStoredDifference(given, stored) {
26654
+ const written = given.split(`
26655
+ `);
26656
+ const holds = stored.split(`
26657
+ `);
26658
+ for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
26659
+ const wrote = written[line];
26660
+ const held = holds[line];
26661
+ if (wrote === held)
26662
+ continue;
26663
+ if (wrote === undefined && held !== undefined) {
26664
+ return `the store writes a line ${line + 1}, ${quotedStoredLine(held)}`;
26665
+ }
26666
+ if (held === undefined && wrote !== undefined) {
26667
+ return `the store drops line ${line + 1}, ${quotedStoredLine(wrote)}`;
26668
+ }
26669
+ if (wrote !== undefined && held !== undefined) {
26670
+ return `line ${line + 1} reads ${quotedStoredLine(wrote)} and is stored as ${quotedStoredLine(held)}`;
26671
+ }
26669
26672
  }
26670
- return [`${indent}Reading: ${observed}`];
26673
+ return "the stored text differs from the text given";
26671
26674
  }
26672
- function resultLines(check, result, brief) {
26673
- const lines = [
26674
- ` - ${result.verdict} by ${result.role} at ${result.commit_sha}. ${commitStandsText(result.commit_stands)}. ${checkWordsText(check, result)}. Recorded ${result.created_at}. Result ${result.id}.`
26675
- ];
26676
- const retracted = result.retracted;
26677
- if (retracted !== undefined) {
26678
- lines.push(` Retracted by ${actorText(retracted.actor)} at ${retracted.created_at}. The reason: ${retracted.reason}`);
26679
- }
26680
- return [...lines, ...readingLines(result, brief)];
26675
+ var STORED_TEXT_PRINTED = 2000;
26676
+ function storedTextPrinted(stored) {
26677
+ if (stored.length <= STORED_TEXT_PRINTED)
26678
+ return { text: stored, cut: "" };
26679
+ const head = stored.slice(0, STORED_TEXT_PRINTED);
26680
+ const lastLineFeed = head.lastIndexOf(`
26681
+ `);
26682
+ const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
26683
+ return {
26684
+ text,
26685
+ cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
26686
+ };
26681
26687
  }
26682
- function ciCheckLines(check, ci, brief) {
26683
- const passStandsLine = ` ${passStandsText(check.pass_stands)}.`;
26684
- const pullRequestLine = ` Pull request line: ${ci.line}`;
26685
- const derived = check.results?.[0];
26686
- if (derived === undefined) {
26687
- return [
26688
- `- ${check.block_id} (${check.when}): no result: ${ci.detail} ${check.text}`,
26689
- passStandsLine,
26690
- pullRequestLine
26691
- ];
26692
- }
26693
- const stands = commitStandsText(derived.commit_stands);
26688
+ function storedTextProblem(given, stored, name) {
26689
+ const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
26690
+ const printed = storedTextPrinted(stored);
26694
26691
  return [
26695
- `- ${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}`,
26696
- passStandsLine,
26697
- pullRequestLine,
26698
- ...readingLines(derived, brief, " ")
26699
- ];
26692
+ `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
26693
+ ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
26694
+ `${printed.cut}
26695
+ --- the text Dispatch stores ---
26696
+ ${printed.text}`,
26697
+ "--- end of the text Dispatch stores ---"
26698
+ ].join("");
26700
26699
  }
26701
- function checkLines(check, brief) {
26702
- if (check.ci !== undefined)
26703
- return ciCheckLines(check, check.ci, brief);
26704
- const bases = check.compared_with ?? [];
26705
- const reason = check.compared_nothing;
26706
- 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]}`;
26707
- const results = check.results ?? [];
26708
- return [
26709
- `- ${check.block_id} (${check.when}). ${compared}. ${passStandsText(check.pass_stands)}.`,
26710
- ` The check's words: ${check.text}`,
26711
- ...results.length === 0 ? [" No result is recorded for this check."] : results.flatMap((result) => resultLines(check, result, brief))
26712
- ];
26700
+ function storedTextCheckFailed(error, name) {
26701
+ 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)}.`;
26702
+ if (!dispatchAnswered(error, 413)) {
26703
+ return `${failure} Send the upload again once that call is answered.`;
26704
+ }
26705
+ const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
26706
+ 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}`;
26713
26707
  }
26714
- function formatCheckResults(results, brief = false) {
26715
- if (results.verification_artifact_id === "") {
26716
- 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.`;
26708
+ function roundTripRouteAbsent(error) {
26709
+ return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
26710
+ }
26711
+ function withoutFinalLineFeed(text) {
26712
+ return text.endsWith(`
26713
+ `) ? text.slice(0, -1) : text;
26714
+ }
26715
+ async function artifactCommand(context) {
26716
+ const { args, client, actor, input, documentOwner, issue } = context;
26717
+ const summary = optionalString(args, "summary");
26718
+ const name = stringArg(args, "name");
26719
+ const content = optionalString(args, "content");
26720
+ const path = optionalString(args, "path");
26721
+ const options = { name, ...summary === undefined ? {} : { summary }, actor };
26722
+ const artifactOwner = documentOwner();
26723
+ const blank = content === undefined || goBlankPattern.test(content);
26724
+ if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
26725
+ const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
26726
+ if (held !== undefined) {
26727
+ throw new ToolInputError(input.tool, [
26728
+ artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`)
26729
+ ]);
26730
+ }
26717
26731
  }
26718
- const checks = results.checks ?? [];
26719
- if (checks.length === 0) {
26720
- return `${results.issue}'s Verification document holds no check blocks.`;
26732
+ if (!blank) {
26733
+ let stored;
26734
+ try {
26735
+ stored = await client.markdownRoundTrip(content);
26736
+ } catch (error) {
26737
+ if (!roundTripRouteAbsent(error)) {
26738
+ throw new Error(storedTextCheckFailed(error, name), { cause: error });
26739
+ }
26740
+ }
26741
+ if (stored !== undefined && withoutFinalLineFeed(stored) !== withoutFinalLineFeed(content)) {
26742
+ throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
26743
+ }
26721
26744
  }
26722
- const blocks = checks.map((check) => checkLines(check, brief).join(`
26723
- `));
26724
- return [`Checks of ${results.issue}:`, ...blocks].join(`
26725
-
26726
- `);
26745
+ const artifactInput = path !== undefined ? {
26746
+ ...options,
26747
+ file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
26748
+ type: Bun.file(resolvePath2(input.cwd, path)).type
26749
+ })
26750
+ } : content !== undefined ? { ...options, content } : options;
26751
+ const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
26752
+ const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
26753
+ const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
26754
+ const adviceLines = renderAdvice(input.tool, uploadOwner.label, result.advice, {
26755
+ isPrimarySpec: result.artifact.primary || result.artifact.name === "spec.md",
26756
+ isPlan: documentPlaysPlan(result.artifact)
26757
+ });
26758
+ return {
26759
+ text: [
26760
+ 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)}`,
26761
+ ...adviceLines
26762
+ ].join(`
26763
+ `),
26764
+ details: artifactOwner.kind === "project" ? {
26765
+ ...documentResultDetails(result.artifact),
26766
+ version: result.version.number,
26767
+ ...result.advice === undefined ? {} : { advice: result.advice }
26768
+ } : {
26769
+ issue: issue(),
26770
+ artifact: result.artifact.id,
26771
+ version: result.version.number,
26772
+ ...result.advice === undefined ? {} : { advice: result.advice }
26773
+ }
26774
+ };
26727
26775
  }
26728
- async function resultCommand(context) {
26729
- const { args, client, actor } = context;
26730
- const retract = optionalString(args, "retract");
26731
- if (retract !== undefined) {
26732
- const retraction = await client.retractResult(retract, {
26733
- actor,
26734
- reason: stringArg(args, "reason")
26735
- });
26736
- return {
26737
- text: `Retracted result ${retraction.result_id}. ${actorText(retraction.actor)} retracted it at ${retraction.created_at}. The reason: ${retraction.reason}
26738
26776
 
26739
- The result stays readable, and it proves nothing from now on. Record a new result where the check still needs one.`,
26740
- details: {
26741
- result: retraction.result_id,
26742
- reason: retraction.reason,
26743
- created_at: retraction.created_at
26744
- }
26745
- };
26777
+ // ../envoy-client/src/dispatch-commands/handoffs.ts
26778
+ async function handoffWriteCommand(context) {
26779
+ const { args, client, actor, input, issue } = context;
26780
+ if (!input.sessionId?.trim()) {
26781
+ throw new Error("host session id is required for dispatch handoff-write");
26746
26782
  }
26747
- const issue = stringArg(args, "issue");
26748
- const optional = {
26749
- ...defined("surface", optionalString(args, "surface")),
26750
- ...defined("run", optionalString(args, "run")),
26751
- ...defined("observed", optionalString(args, "observed")),
26752
- ...defined("negative_control", optionalString(args, "negative_control")),
26753
- ...defined("failed", optionalNumber(args, "failed")),
26754
- ...defined("skipped", optionalNumber(args, "skipped")),
26755
- ...defined("excluded", optionalNumber(args, "excluded")),
26756
- ...defined("screenshots", optionalStringArray(args, "screenshots"))
26757
- };
26758
26783
  let recorded;
26759
26784
  try {
26760
- recorded = await client.recordResult(issue, {
26785
+ recorded = await client.writeHandoff(issue(), stringArg(args, "phase"), {
26761
26786
  actor,
26762
- check: stringArg(args, "check"),
26763
- role: stringArg(args, "role"),
26764
- verdict: stringArg(args, "verdict"),
26765
- commit: stringArg(args, "commit"),
26766
- ...optional
26787
+ body: stringArg(args, "body")
26767
26788
  });
26768
26789
  } catch (error) {
26769
- if (dispatchAnswered(error, 409) && error.code === "CHECK_CONTENDED") {
26770
- throw refusalWithCode(error, "the check moved twice while this result was being written, and nothing was recorded: run the same dispatch result command again");
26771
- }
26772
- throw error;
26790
+ throw refusalWithCode(error);
26773
26791
  }
26774
26792
  return {
26775
- 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}.
26776
-
26777
- Pull request body line:
26778
- ${recorded.line}`,
26793
+ text: `Recorded the ${recorded.phase} handoff of ${recorded.issue_key}, version ${recorded.version} (id ${recorded.id})`,
26779
26794
  details: {
26780
- issue,
26781
- result: recorded.result.id,
26782
- check: recorded.result.check_block_id,
26783
- verdict: recorded.result.verdict,
26784
- line: recorded.line
26795
+ issue: recorded.issue_key,
26796
+ phase: recorded.phase,
26797
+ version: recorded.version,
26798
+ handoff: recorded.id
26785
26799
  }
26786
26800
  };
26787
26801
  }
26788
- async function resultsCommand(context) {
26789
- const { args, client } = context;
26790
- const issue = stringArg(args, "issue");
26791
- const at = optionalString(args, "at");
26792
- const brief = optionalBoolean(args, "brief") === true;
26793
- const results = await client.issueResults(issue, at);
26794
- const checks = results.checks ?? [];
26802
+ async function handoffReadCommand(context) {
26803
+ const { args, client, issue } = context;
26804
+ const issueKey = issue();
26805
+ const phase = stringArg(args, "phase");
26806
+ const version = optionalNumber(args, "version");
26807
+ let handoff;
26808
+ try {
26809
+ if (version === undefined) {
26810
+ handoff = await client.latestHandoff(issueKey, phase);
26811
+ } else {
26812
+ const listed = await client.listHandoffs(issueKey);
26813
+ const ofPhase = listed.filter((summary) => summary.phase === phase);
26814
+ const match = ofPhase.find((summary) => summary.version === version);
26815
+ if (match === undefined) {
26816
+ const newest = Math.max(0, ...ofPhase.map((summary) => summary.version));
26817
+ 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}`}`);
26818
+ }
26819
+ handoff = await client.handoff(match.id);
26820
+ }
26821
+ } catch (error) {
26822
+ throw refusalWithCode(error);
26823
+ }
26795
26824
  return {
26796
- text: formatCheckResults(results, brief),
26825
+ text: `${handoff.issue_key} ${handoff.phase} handoff, version ${handoff.version} (id ${handoff.id}), written by ${actorText(handoff.author)} at ${handoff.created_at}
26826
+ ${handoff.body}`,
26797
26827
  details: {
26798
- issue,
26799
- checks: checks.length,
26800
- results: checks.reduce((total, check) => total + (check.results ?? []).length, 0)
26828
+ issue: handoff.issue_key,
26829
+ phase: handoff.phase,
26830
+ version: handoff.version,
26831
+ handoff: handoff.id
26801
26832
  }
26802
26833
  };
26803
26834
  }
@@ -27839,6 +27870,9 @@ async function executeDispatchTool(input) {
27839
27870
  });
27840
27871
  if (checked.problems.length > 0)
27841
27872
  throw new ToolInputError(input.tool, checked.problems);
27873
+ if (input.dryRun === true && !dryRunAsksDispatch(input.tool, checked.args)) {
27874
+ throw new Error(`dispatch ${input.tool}'s dry run asks Dispatch nothing`);
27875
+ }
27842
27876
  const command = dispatchCommands[input.tool];
27843
27877
  if (command === undefined)
27844
27878
  throw new Error(`Unknown Dispatch tool: ${input.tool}`);
@@ -31817,7 +31851,7 @@ async function runDispatchCli(argv, rawEnv, io) {
31817
31851
  return refuse(messageFor(error), USAGE, parsed.tool);
31818
31852
  }
31819
31853
  const file = (env.DISPATCH_HOST === undefined ? null : handedConfigFile(env)) ?? sessionConfigFile(host, env);
31820
- if (parsed.dryRun) {
31854
+ if (parsed.dryRun && !dryRunAsksDispatch(parsed.tool, parsed.args)) {
31821
31855
  const settings = file.path === null ? null : sessionDispatchSettings(file, env, { cwd: io.cwd, session: sessionId }).dispatch;
31822
31856
  const { problems } = await checkDispatchCall({
31823
31857
  tool: parsed.tool,
@@ -31845,6 +31879,28 @@ async function runDispatchCli(argv, rawEnv, io) {
31845
31879
  return refuse(resolution.error === null ? `dispatch: ${resolution.notice}` : `dispatch: dispatch config: ${resolution.error}`, USAGE, parsed.tool);
31846
31880
  }
31847
31881
  const config = resolution;
31882
+ if (parsed.dryRun) {
31883
+ try {
31884
+ const result = await executeDispatchTool({
31885
+ tool: parsed.tool,
31886
+ args: parsed.args,
31887
+ cwd: io.cwd,
31888
+ host,
31889
+ sessionId,
31890
+ sessionTitle: env.DISPATCH_SESSION_TITLE ?? readSessionTitle(dir),
31891
+ config,
31892
+ env,
31893
+ ...io.fetchImpl === undefined ? {} : { fetchImpl: io.fetchImpl },
31894
+ dryRun: true
31895
+ });
31896
+ print(`${JSON.stringify(parsed.args, null, 2)}
31897
+
31898
+ ${result.text}`);
31899
+ return OK;
31900
+ } catch (error) {
31901
+ return refuse(messageFor(error), error instanceof ToolInputError ? USAGE : REFUSED, parsed.tool);
31902
+ }
31903
+ }
31848
31904
  let uploadBytes;
31849
31905
  if (gatedWrite(parsed.tool, parsed.args)) {
31850
31906
  const notCalled = `dispatch ${commandName(parsed.tool)} was not called:`;