- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/issues.ts?version=261&format=json
961 linespinch 50% · First import 40% · devops 4% · review 3% · infra-split 2% · speed 1% · Last change groups in version 256, 21 versions changed it
You're reading version 261. The newest is 318, and 1 version since then changed this file.
1// Issues (#54): abso issues, abso issue, abso ask, abso waiting and avcs
2// answer. The Issues Worker keeps them (avcs-issues beside avcs, or
3// ABSO_ISSUES_SERVER), and takes the same token. Statuses come from the work: a start note naming
4// an issue (abso start --issue N) puts it In progress, an open ask Blocked or
5// In review, and publish --done closes it. Other agents' and people's words
6// are quoted as JSON, so none can print as another line (#30).
8import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
9import { basename, join, resolve } from "node:path";
10import {
11 type Api,
12 ApiError,
13 type Ask,
14 type Attachment,
15 type CopyAnswer,
16 type CopyBody,
17 type Draft,
18 type DraftBody,
19 type IssuePage,
20 type IssueRow,
21 type IssueSearchHit,
22} from "./api.ts";
23import { bool, type Parsed, str, UsageError } from "./args.ts";
24import { type Env, type Output, open, plural } from "./commands.ts";
25import { type Config, readMachineServers, trustedServers } from "./config.ts";
26import { issuesServerFor, tokenGoesToIssues } from "./core.ts";
27import { fromEnv } from "./env-names.ts";
28import { ignoredHere } from "./fetch.ts";
29import { loadIgnore, relativeTo } from "./folder.ts";
30import type { AskReply } from "./issues-wire.ts";
31import { queuedLines, standing } from "./queue.ts";
32import { seenText, shortWhen } from "./times.ts";
34const q = (s: string): string => JSON.stringify(s);
36/** The folder, with its Api pointed at the Issues Worker: the token goes only where tokenGoesTo allows, as for the avcs server. */
37export function openIssues(env: Env): { root: string; config: Config; api: Api } {
38 const { root, config, api } = open(env);
39 // An explicit --server goes to that server's own Issues Worker: ABSO_ISSUES_SERVER doesn't redirect it.
40 const server =
41 (env.server === undefined ? fromEnv(env.env, "ISSUES_SERVER") : undefined) ||
42 issuesServerFor(config.server, readMachineServers(env.env));
43 if (server === undefined)
44 throw new UsageError(
45 `${config.server} has no Issues Worker beside it that abso knows; ~/.abso/servers.json or ABSO_ISSUES_SERVER names one`,
46 );
47 if (config.token !== undefined && !tokenGoesToIssues(server, trustedServers(env.env))) {
48 throw new UsageError(
49 `the Issues Worker is ${server}, and abso sends your token only to its own servers and this machine. If ${server} is yours, name it in ~/.abso/servers.json or ABSO_TRUSTED_SERVERS.`,
50 );
51 }
52 api.issuesServer = server;
53 return { root, config, api };
54}
56function issueNumber(word: string | undefined, what = "an issue number"): number {
57 if (word === undefined || !/^#?\d+$/.test(word)) throw new UsageError(`${what} is a number, like 12`);
58 return Number(word.replace("#", ""));
59}
61/** One issue as a line. */
62export function issueLine(i: IssueRow): string {
63 const detail = [
64 i.agent !== null && !i.agents.includes(i.agent) ? `for ${i.agent}` : "",
65 i.agents.length > 0 ? i.agents.join(", ") : "",
66 i.blockedBy.length > 0 ? `blocked by ${i.blockedBy.join(", ")}` : "",
67 (i.labels ?? []).length > 0 ? `labels ${i.labels.join(", ")}` : "",
68 i.versions.length > 0 ? `${i.versions.length === 1 ? "version" : "versions"} ${i.versions.join(", ")}` : "",
69 i.waitingOn.length > 0 ? `waiting on ${i.waitingOn.join(", ")}` : "",
70 i.parent !== null ? `under ${i.parent}` : "",
71 i.children > 0 ? plural(i.children, "sub-issue") : "",
72 `updated ${shortWhen(i.updated)}`,
73 ].filter((d) => d !== "");
74 return ` ${String(i.id).padStart(3)} ${i.status.padEnd(11)} ${q(i.title)}${detail.length > 0 ? ` (${detail.join("; ")})` : ""}`;
75}
77/** The first line of a reply, for lists; abso ask <N> shows it whole. */
78const firstLine = (text: string): string => {
79 const line = text.split("\n")[0]!;
80 return line.length < text.length ? `${line} ...` : line;
81};
83/** One reply in an ask's thread. */
84function replyLine(r: AskReply, indent: string, whole: boolean): string {
85 return `${indent}${r.by}, ${shortWhen(r.at)}${r.question ? ", a question" : ""}: ${q(whole ? r.text : firstLine(r.text))}`;
86}
88/**
89 * An ask: its head line, its files and options, then, in a list, its newest reply, or with `thread`, every
90 * reply, oldest first; then its answer. Older servers send no thread, only the one asked's acknowledgement.
91 */
92function askLine(a: Ask & { title?: string | null }, api?: Pick<Api, "attachmentUrl">, thread = false): string {
93 const what = a.review ? "a review" : a.kind === "task" ? "a task" : "a question";
94 const where = a.issue === null ? "" : ` on issue ${a.issue}${a.title ? ` (${q(a.title)})` : ""}`;
95 const replies = a.replies;
96 const extra = [
97 // Who answered, and when, on the ask's own line, so a handled ask can't pass for an open one.
98 a.answer
99 ? `${a.outcome === "withdrawn" ? "withdrawn" : "answered"} by ${a.answer.by}, ${shortWhen(a.answer.at)}`
100 : "",
101 !a.answer && a.ack && replies === undefined ? `acknowledged ${shortWhen(a.ack.at)}, not answered yet` : "",
102 !a.answer && !a.ack && a.seen !== undefined ? seenText(a.seen) : "",
103 replies && replies.length > 0 ? (replies.length === 1 ? "1 reply" : `${replies.length} replies`) : "",
104 // Whose turn it is, when it isn't the one asked's: they asked something back.
105 !a.answer && a.waitingOn && a.waitingOn !== a.of ? `waiting on ${a.waitingOn}` : "",
106 a.due ? `due ${a.due}` : "",
107 a.blocks.length > 0 ? `blocks ${a.blocks.join(", ")}` : "",
108 ].filter((x) => x !== "");
109 const head = ` ask ${a.id}: ${a.by}, ${shortWhen(a.at)}, asks ${a.of} ${what}${where}${extra.length > 0 ? ` (${extra.join("; ")})` : ""}: ${q(a.question)}`;
110 const lines = [head, ...attachmentLines(api, a.attachments, " ")];
111 if (a.options.length > 0) lines.push(` options: ${a.options.map((o, i) => `${i + 1}. ${q(o)}`).join(", ")}`);
112 if (a.recommendation) lines.push(` ${a.recommendation.by} recommends: ${q(a.recommendation.text)}`);
113 if (replies === undefined) {
114 if (!a.answer && a.ack && a.ack.note !== "") lines.push(` ${a.of} acknowledged: ${q(a.ack.note)}`);
115 } else if (thread) lines.push(...replies.map((r) => replyLine(r, " ", true)));
116 else if (replies.length > 0) lines.push(replyLine(replies[replies.length - 1]!, " last: ", false));
117 if (a.answer && a.outcome === "withdrawn") {
118 if (a.answer.words !== "") lines.push(` why: ${q(a.answer.words)}`);
119 } else if (a.answer)
120 lines.push(` answer: ${q(a.answer.words)}`, ...attachmentLines(api, a.answer.attachments, " "));
121 return lines.join("\n");
122}
124/** One edit in an issue's activity: what changed, and who was told. */
125function editLine(e: IssuePage["edits"][number]): string {
126 const c = e.changes;
127 const said = [
128 c.title ? `title ${q(String(c.title.from))} to ${q(String(c.title.to))}` : "",
129 c.description ? "the description" : "",
130 c.parent ? (c.parent.to === null ? "no parent" : `parent issue ${String(c.parent.to)}`) : "",
131 c.agent ? (c.agent.to === null ? "no Agent" : `Agent ${String(c.agent.to)}`) : "",
132 c.blockedBy
133 ? (c.blockedBy.to as number[]).length === 0
134 ? "blocked by nothing"
135 : `blocked by ${(c.blockedBy.to as number[]).join(", ")}`
136 : "",
137 c.labels
138 ? (c.labels.to as string[]).length === 0
139 ? "no labels"
140 : `labels ${(c.labels.to as string[]).join(", ")}`
141 : "",
142 ].filter((x) => x !== "");
143 return ` ${e.by}, ${shortWhen(e.at)}: ${said.join("; ")} (${e.notified.length > 0 ? `told ${e.notified.join(", ")}` : "told nobody"})`;
144}
146/** Labels as typed, lower-cased, since the Worker refuses upper case: --label Friction means friction. */
147function labelList(value: string): string[] {
148 return listOf(value).map((l) => l.toLowerCase());
149}
151/** A comma-separated list of names or issue numbers; "none" is the empty list. */
152function listOf(value: string): string[] {
153 return value.trim() === "none"
154 ? []
155 : value
156 .split(",")
157 .map((v) => v.trim())
158 .filter((v) => v !== "");
159}
161/** " with 2 attachments (a…, a…)" after a write that carried some; nothing otherwise. */
162function withFiles(ids: readonly string[]): string {
163 return ids.length > 0 ? ` with ${plural(ids.length, "attachment")} (${ids.join(", ")})` : "";
164}
166/**
167 * What to say when a write sent files the server didn't keep: an Issues server from before asks carried
168 * attachments takes the words and leaves the files out. Nothing to say when it kept them, or none were sent.
169 */
170function notKept(sent: readonly string[], kept: readonly string[] | undefined, what: string): string | undefined {
171 if (sent.length === 0 || (kept !== undefined && sent.every((id) => kept.includes(id)))) return undefined;
172 return `The Issues server didn't keep the ${sent.length === 1 ? "file" : "files"} on ${what}: it is older than this client. The words went; the ${sent.length === 1 ? "file goes" : "files go"} on a comment instead (abso issue <N> --comment "..." --attach ...).`;
173}
175/** The most one attachment may be: the Issues Worker's cap, checked here before sending (abso issue 171). */
176const ATTACH_MAX = 10 * 1024 * 1024;
178/** Uploads each file --attach names (comma-separated), in order, and answers their ids. Nothing is sent if a file is missing or too big. */
179async function uploadAttachments(api: Api, cwd: string, value: string | undefined): Promise<string[]> {
180 if (value === undefined) return [];
181 const paths = listOf(value);
182 if (paths.length === 0) throw new UsageError("--attach names files, comma-separated: --attach shot.png,after.png");
183 const files = paths.map((p) => {
184 const full = resolve(cwd, p);
185 let size: number;
186 try {
187 size = statSync(full).size;
188 } catch {
189 throw new UsageError(`--attach ${p}: no such file`);
190 }
191 if (size > ATTACH_MAX)
192 throw new UsageError(`--attach ${p} is ${sizeText(size)}; one attachment is at most ${sizeText(ATTACH_MAX)}`);
193 return { full, name: basename(full) };
194 });
195 const ids: string[] = [];
196 for (const f of files) ids.push((await api.attachmentUpload(readFileSync(f.full), f.name)).id);
197 return ids;
198}
200function sizeText(n: number): string {
201 return n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`;
202}
204/** Attachments as lines under what carries them: name, size and where it's served. */
205function attachmentLines(
206 api: Pick<Api, "attachmentUrl"> | undefined,
207 files: readonly Attachment[] | undefined,
208 indent: string,
209): string[] {
210 return (files ?? []).flatMap((a) => [
211 `${indent}attached ${a.id}: ${q(a.name)}, ${sizeText(a.size)}${api ? `, ${api.attachmentUrl(a.id)}` : ""}`,
212 // An SVG is shown as the PNG drawn from it; its own file is a download beside it.
213 ...(a.source
214 ? [
215 `${indent} drawn from ${q(a.source.name)}, ${sizeText(a.source.size)}${api ? `, ${api.attachmentUrl(a.id)}/source` : ""}`,
216 ]
217 : []),
218 ]);
219}
221/** A saved attachment's file name: its id, then its own name with anything but letters, digits, . - _ made _. */
222export function savedName(id: string, name: string): string {
223 const own = (name.split(/[\\/]/).pop() ?? "")
224 .replace(/[^A-Za-z0-9._-]/g, "_")
225 .replace(/^\.+/, "_")
226 .slice(0, 100);
227 return `${id}-${own || "file"}`;
228}
230/**
231 * abso issue N --save-attachments <folder>: every attachment on the issue, its
232 * comments and its asks and answers, written to that folder as <id>-<name>; an svg's own file
233 * beside the png drawn from it. Not into the abso folder unless abso leaves
234 * that place out, or the images would be recorded as edits.
235 */
236async function saveAttachments(api: Api, root: string, cwd: string, dir: string, page: IssuePage): Promise<Output> {
237 const target = resolve(cwd, dir);
238 const inside = target === resolve(root) ? "" : relativeTo(root, target);
239 if (inside !== undefined && (inside === "" || !ignoredHere(loadIgnore(root), inside, true)))
240 throw new UsageError(
241 `${dir} is inside this abso folder, so abso would record the images as your edits. Save them outside the folder, or into a folder .absoignore leaves out`,
242 );
243 const seen = new Set<string>();
244 const all = [
245 ...(page.issue.attachments ?? []),
246 ...page.comments.flatMap((c) => c.attachments ?? []),
247 ...page.asks.flatMap((a) => [...(a.attachments ?? []), ...(a.answer?.attachments ?? [])]),
248 ].filter((a) => !seen.has(a.id) && seen.add(a.id));
249 if (all.length === 0)
250 return {
251 text: `Issue ${page.issue.id} has no attachments.`,
252 json: { issue: page.issue.id, folder: target, files: [] },
253 };
254 mkdirSync(target, { recursive: true });
255 const files: { id: string; path: string; size: number }[] = [];
256 for (const a of all) {
257 const wanted = [{ name: a.name, source: false }, ...(a.source ? [{ name: a.source.name, source: true }] : [])];
258 for (const w of wanted) {
259 const bytes = await api.attachmentBytes(a.id, w.source, ATTACH_MAX);
260 const path = join(target, savedName(a.id, w.name));
261 writeFileSync(path, bytes);
262 files.push({ id: a.id, path, size: bytes.length });
263 }
264 }
265 return {
266 text: [
267 `Saved ${plural(files.length, "file")} from issue ${page.issue.id} to ${target}:`,
268 ...files.map((f) => ` ${basename(f.path)}, ${sizeText(f.size)}`),
269 ].join("\n"),
270 json: { issue: page.issue.id, folder: target, files },
271 };
272}
274/** An issue's page, as text. */
275export function issuePage(p: IssuePage, api?: Pick<Api, "attachmentUrl">): string[] {
276 const i = p.issue;
277 const facts = [
278 i.parent !== null ? `Under issue ${i.parent}.` : "",
279 `Opened by ${i.opened.by}, ${shortWhen(i.opened.at)}.`,
280 i.agent !== null ? `Agent: ${i.agent}.` : "",
281 i.agents.length > 0 ? `Working on it: ${i.agents.join(", ")}.` : "",
282 i.blockedBy.length > 0 ? `Blocked by: issue${i.blockedBy.length === 1 ? "" : "s"} ${i.blockedBy.join(", ")}.` : "",
283 (i.labels ?? []).length > 0 ? `Labels: ${i.labels.join(", ")}.` : "",
284 i.versions.length > 0 ? `Versions: ${i.versions.join(", ")}.` : "",
285 i.waitingOn.length > 0 ? `Waiting on: ${i.waitingOn.join(", ")}.` : "",
286 i.closed
287 ? `${i.closed.how === "done" ? "Done" : "Dropped"} by ${i.closed.by}${i.closed.version !== null ? ` in version ${i.closed.version}` : ""}, ${shortWhen(i.closed.at)}.`
288 : "",
289 ].filter((f) => f !== "");
290 // The links below open for people signed in on the website; an agent's fetch of one is refused. Say the way in
291 // before the first link, so an agent reads the files instead of hunting for them.
292 const files =
293 (i.attachments ?? []).length +
294 p.comments.reduce((n, c) => n + (c.attachments ?? []).length, 0) +
295 p.asks.reduce((n, a) => n + (a.attachments ?? []).length + (a.answer?.attachments ?? []).length, 0);
296 return [
297 `Issue ${i.id}: ${q(i.title)} [${i.status}]`,
298 facts.join(" "),
299 ...(files > 0
300 ? [
301 `${files === 1 ? "1 file is" : `${files} files are`} attached below. To read ${files === 1 ? "it" : "them"}: abso issue ${i.id} --save-attachments <folder> saves ${files === 1 ? "it" : "every one"} there, then open the files. The links are for people signed in on the website.`,
302 ]
303 : []),
304 ...(i.lines ? [`From ${i.lines.file} lines ${i.lines.from}-${i.lines.to} at version ${i.lines.version}.`] : []),
305 ...(i.description !== "" ? ["", ...i.description.split("\n").map((l) => ` ${l}`)] : []),
306 ...attachmentLines(api, i.attachments, " "),
307 ...(p.asks.length > 0 ? ["", "Asks:", ...p.asks.map((a) => askLine(a, api))] : []),
308 ...(p.comments.length > 0
309 ? [
310 "",
311 "Comments:",
312 ...p.comments.flatMap((c) => [
313 ` ${c.by}${c.kind === "objection" ? " objects" : ""}, ${shortWhen(c.at)}: ${q(c.text)}`,
314 ...attachmentLines(api, c.attachments, " "),
315 ]),
316 ]
317 : []),
318 ...((p.edits ?? []).length > 0 ? ["", "Edits:", ...p.edits.map(editLine)] : []),
319 ...(p.children.length > 0 ? ["", "Sub-issues:", ...p.children.map(issueLine)] : []),
320 ...((i.watchers ?? []).length > 0 ? ["", `Watchers: ${i.watchers.join(", ")}.`] : []),
321 "",
322 `abso start "..." --issue ${i.id} starts on it; abso issue ${i.id} --comment "..." comments; abso ask <who> "..." --issue ${i.id} asks.`,
323 ];
324}
326export async function runIssues(args: Parsed, env: Env): Promise<Output> {
327 if (args.positionals.length > 0)
328 throw new UsageError(
329 "issues takes no words: abso issues [--open] [--status <s>] [--agent <a>] [--parent <N>] [--label <l,l>] | abso issues --labels; abso issue <N> shows one",
330 );
331 const { api } = openIssues(env);
332 if (bool(args, "drafts")) {
333 const { drafts } = await api.drafts();
334 return {
335 text:
336 drafts.length === 0
337 ? 'No drafts. abso issue draft "<title>" saves one: only you see it, and nobody hears of it.'
338 : [
339 `${plural(drafts.length, "draft")}, newest first (only you see them):`,
340 ...drafts.map(draftLine),
341 "abso issue draft <D> --open opens one as an issue; --delete deletes it.",
342 ].join("\n"),
343 json: { drafts },
344 };
345 }
346 if (bool(args, "labels")) {
347 const { labels } = await api.issueLabels();
348 return {
349 text:
350 labels.length === 0
351 ? 'No labels yet. abso issue new "<title>" --label friction labels a new issue; abso issue <N> --label <l> labels one.'
352 : [
353 `${plural(labels.length, "label")} in use:`,
354 ...labels.map((l) => ` ${l.label}: ${l.open} open of ${l.total}`),
355 "abso issues --label <label> lists a label's issues.",
356 ].join("\n"),
357 json: { labels },
358 };
359 }
360 const parent = str(args, "parent");
361 const filter = {
362 ...(str(args, "status") ? { status: str(args, "status")! } : {}),
363 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
364 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
365 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
366 open: bool(args, "open"),
367 };
368 const { issues } = await api.issues(filter);
369 const scope = [
370 filter.open ? "open " : "",
371 filter.status ? `${filter.status} ` : "",
372 filter.labels ? `${filter.labels.join(", ")} ` : "",
373 ].join("");
374 return {
375 text:
376 issues.length === 0
377 ? `No ${scope}issues${filter.agent ? ` for ${filter.agent}` : ""}${parent !== undefined ? ` under ${parent}` : ""}. abso issue new "<title>" opens one.`
378 : [
379 `${plural(issues.length, `${scope}issue`)}, most recently updated first:`,
380 ...issues.map(issueLine),
381 "abso issue <N> shows one.",
382 ].join("\n"),
383 json: { issues },
384 };
385}
387/** A new issue's fields from the command line, as open and drafts take them; `title` only when words were given. */
388function openFields(args: Parsed, title: string): DraftBody {
389 const lines = str(args, "lines");
390 const at = lines === undefined ? undefined : /^(.+):(\d+)(?:-(\d+))?@(\d+)$/.exec(lines);
391 if (lines !== undefined && !at)
392 throw new UsageError("--lines is <file>:<from>-<to>@<version>, like src/a.ts:10-14@140");
393 const parent = str(args, "parent");
394 return {
395 ...(title !== "" ? { title } : {}),
396 ...(str(args, "description") ? { description: str(args, "description")! } : {}),
397 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
398 ...(at ? { lines: { file: at[1]!, from: Number(at[2]), to: Number(at[3] ?? at[2]), version: Number(at[4]) } } : {}),
399 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
400 ...(str(args, "blocked-by") !== undefined
401 ? { blockedBy: listOf(str(args, "blocked-by")!).map((b) => issueNumber(b, "--blocked-by")) }
402 : {}),
403 ...(str(args, "notify") !== undefined ? { notify: listOf(str(args, "notify")!) } : {}),
404 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
405 };
406}
408/** One draft as a line: its number, title, and what else it holds. */
409function draftLine(d: Draft): string {
410 const b = d.body;
411 const more = [
412 b.agent ? `for ${b.agent}` : "",
413 b.parent ? `under ${b.parent}` : "",
414 (b.labels ?? []).length > 0 ? `labels ${b.labels!.join(", ")}` : "",
415 b.description ? "a description" : "",
416 ].filter((m) => m !== "");
417 return ` draft ${d.id}: ${b.title ? q(b.title) : "(no title yet)"}${more.length > 0 ? ` (${more.join("; ")})` : ""}, saved ${shortWhen(d.saved)}`;
418}
420/**
421 * Drafts (abso issue 3): an issue not opened yet, this agent's alone, with no
422 * number and no news. `abso issue draft "<title>" [fields]` saves a new one;
423 * `abso issue draft <D> [fields]` changes one; --open opens it as an issue;
424 * --delete deletes it. `abso issues --drafts` lists them.
425 */
426async function runDraft(api: Api, args: Parsed, words: string[]): Promise<Output> {
427 const [d, ...more] = words;
428 if (d !== undefined && /^\d+$/.test(d) && more.length === 0) {
429 const id = Number(d);
430 if (bool(args, "delete") && bool(args, "open")) throw new UsageError("--open or --delete, not both");
431 if (bool(args, "delete")) {
432 await api.deleteDraft(id);
433 return { text: `Deleted draft ${id}.`, json: { draft: id, deleted: true } };
434 }
435 if (bool(args, "open")) {
436 const r = await api.openDraft(id, openFields(args, ""));
437 return {
438 text: `Opened draft ${id} as issue ${r.id}. abso start "..." --issue ${r.id} starts on it.`,
439 json: { draft: id, id: r.id },
440 };
441 }
442 // Saving replaces the draft's body, so the fields given go over what it holds.
443 const found = (await api.drafts()).drafts.find((x) => x.id === id);
444 if (!found) throw new UsageError(`you have no draft ${id}; abso issues --drafts lists yours`);
445 await api.saveDraft({ ...found.body, ...openFields(args, ""), id });
446 return { text: `Saved draft ${id}.`, json: { draft: id } };
447 }
448 if (bool(args, "open") || bool(args, "delete"))
449 throw new UsageError("--open and --delete take a draft's number: abso issue draft <D> --open");
450 const r = await api.saveDraft(openFields(args, words.join(" ")));
451 return {
452 text: `Saved draft ${r.id}. Only you see it, and nobody hears of it. abso issue draft ${r.id} --open opens it as an issue.`,
453 json: { draft: r.id },
454 };
455}
457/** The flags --copy-to goes with: anything else on the same command is refused, so a copy is never half an edit. */
458const COPY_FLAGS = new Set(["copy-to", "clean", "dry-run"]);
460/** abso issue <N> --copy-to <project>: the server reads the issue and writes the copy. */
461async function runCopy(api: Api, id: number, to: string, args: Parsed, env: Env): Promise<Output> {
462 const other = [...args.flags.keys()].filter((f) => !COPY_FLAGS.has(f) && f !== "json");
463 if (other.length > 0)
464 throw new UsageError(`--copy-to goes alone (with --clean and --dry-run), not with --${other[0]}`);
465 if (to === api.config.project)
466 throw new UsageError(`issue ${id} is already in ${to}; --copy-to names another project`);
467 const clean = str(args, "clean");
468 const texts = clean === undefined ? {} : readClean(resolve(env.cwd, clean), clean);
469 const dryRun = bool(args, "dry-run");
470 const from = api.config.project;
471 let answer: CopyAnswer;
472 try {
473 answer = await api.issueCopy(to, { ...texts, from, issue: id, ...(dryRun ? { dryRun: true } : {}) });
474 } catch (e) {
475 if (e instanceof ApiError && e.status === 403 && !dryRun)
476 throw new ApiError(`${e.message}. --dry-run still shows what would go.`, e.status);
477 throw e;
478 }
479 if ("dryRun" in answer) {
480 const p = answer.plan;
481 const edited = (list: { edited: boolean }[]) => list.filter((x) => x.edited).length;
482 const lines = [
483 `A dry run: nothing was written. Copying ${from} issue ${id} into ${to} would make:`,
484 ` ${q(p.title)}${p.closed ? `, ${p.closed.how}` : ""}${p.edited.length > 0 ? ` (${p.edited.join(" and ")} edited when copied)` : ""}`,
485 ` ${plural(p.comments.length, "comment")}${edited(p.comments) > 0 ? ` (${edited(p.comments)} edited)` : ""}, ${plural(p.asks.length, "answered ask")}${edited(p.asks) > 0 ? ` (${edited(p.asks)} edited)` : ""}${p.labels.length > 0 ? `, labelled ${p.labels.join(", ")}` : ""}`,
486 ...skippedLines(p.skipped),
487 `Run it again without --dry-run to copy it.`,
488 ];
489 return { text: lines.join("\n"), json: answer };
490 }
491 return {
492 text: [
493 `Copied ${from} issue ${id} to ${to} issue ${answer.id}. Its comments and asks keep their authors and times, and issue ${id} has a comment saying where it went.`,
494 ...skippedLines(answer.skipped),
495 ].join("\n"),
496 json: answer,
497 };
498}
500function skippedLines(skipped: { comments: number[]; asks: number[] }): string[] {
501 const parts = [
502 ...(skipped.comments.length > 0 ? [`comments ${skipped.comments.join(", ")}`] : []),
503 ...(skipped.asks.length > 0 ? [`asks ${skipped.asks.join(", ")}`] : []),
504 ];
505 return parts.length > 0 ? [` not copied: ${parts.join("; ")} (open asks, and what --clean left out)`] : [];
506}
508/** --clean's file: cleaned texts by source id. The server checks each id against the issue it reads. */
509function readClean(path: string, given: string): Omit<CopyBody, "from" | "issue"> {
510 let raw: unknown;
511 try {
512 raw = JSON.parse(readFileSync(path, "utf8"));
513 } catch (e) {
514 throw new UsageError(
515 `--clean ${given}: ${(e as NodeJS.ErrnoException).code === "ENOENT" ? "no such file" : "not JSON"}`,
516 );
517 }
518 if (typeof raw !== "object" || raw === null || Array.isArray(raw))
519 throw new UsageError(`--clean ${given}: a JSON object with title, description, comments or asks`);
520 const known = new Set(["title", "description", "comments", "asks"]);
521 const unknown = Object.keys(raw).filter((k) => !known.has(k));
522 if (unknown.length > 0)
523 throw new UsageError(`--clean ${given}: ${unknown[0]} isn't one of title, description, comments, asks`);
524 return raw as Omit<CopyBody, "from" | "issue">;
525}
527export async function runIssue(args: Parsed, env: Env): Promise<Output> {
528 const [first, ...rest] = args.positionals;
529 const { root, api } = openIssues(env);
530 const saveTo = str(args, "save-attachments");
531 if (saveTo !== undefined) {
532 const other = [...args.flags.keys()].filter((f) => f !== "save-attachments" && f !== "json");
533 if (other.length > 0 || first === "new" || first === "draft")
534 throw new UsageError(
535 `--save-attachments goes alone with an issue number: abso issue <N> --save-attachments <folder>${other.length > 0 ? `, not with --${other[0]}` : ""}`,
536 );
537 }
538 if (first === "draft") return runDraft(api, args, rest);
539 if (first === "new") {
540 if (rest.length === 0)
541 throw new UsageError(
542 'abso issue new "<title>" [--description "..."] [--parent <N>] [--lines <file>:<from>-<to>@<version>] [--agent <agent>] [--blocked-by <N,N>] [--notify <who,who>] [--label <l,l>]',
543 );
544 const fields = { ...openFields(args, rest.join(" ")), title: rest.join(" ") };
545 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
546 const r = await api.issueOpen({ ...fields, ...(attachments.length > 0 ? { attachments } : {}) });
547 return {
548 text: `Opened issue ${r.id}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. abso start "..." --issue ${r.id} starts on it.`,
549 json: { id: r.id, ...(attachments.length > 0 ? { attachments } : {}) },
550 };
551 }
552 if (first === undefined || rest.length > 0)
553 throw new UsageError(
554 'abso issue <N> [--comment "..." | --object "..." | --drop | --reopen | --done [--done-by <version>] | an edit], or abso issue new "<title>"',
555 );
556 const id = issueNumber(first);
557 const copyTo = str(args, "copy-to");
558 if (copyTo !== undefined) return runCopy(api, id, copyTo, args, env);
559 if (str(args, "clean") !== undefined || bool(args, "dry-run"))
560 throw new UsageError("--clean and --dry-run go with --copy-to <project>");
561 const comment = str(args, "comment");
562 const object = str(args, "object");
563 const doneBy = str(args, "done-by");
564 const markingDone = bool(args, "done") || doneBy !== undefined;
565 const edits = ["title", "description", "parent", "agent", "blocked-by", "label", "unlabel"].filter(
566 (f) => str(args, f) !== undefined,
567 );
568 if (
569 [
570 comment !== undefined,
571 object !== undefined,
572 bool(args, "drop"),
573 bool(args, "reopen"),
574 markingDone,
575 edits.length > 0,
576 ].filter(Boolean).length > 1
577 )
578 throw new UsageError("one of --comment, --object, --drop, --reopen, --done or an edit at a time");
579 if (edits.length > 0) {
580 const parent = str(args, "parent");
581 const agent = str(args, "agent");
582 const blockedBy = str(args, "blocked-by");
583 const r = await api.issueEdit(id, {
584 ...(str(args, "title") !== undefined ? { title: str(args, "title")! } : {}),
585 ...(str(args, "description") !== undefined ? { description: str(args, "description")! } : {}),
586 ...(parent !== undefined ? { parent: parent === "none" ? null : issueNumber(parent, "--parent") } : {}),
587 ...(agent !== undefined ? { agent: agent === "none" ? null : agent } : {}),
588 ...(blockedBy !== undefined ? { blockedBy: listOf(blockedBy).map((b) => issueNumber(b, "--blocked-by")) } : {}),
589 ...(bool(args, "quiet") ? { notify: false } : {}),
590 ...(str(args, "notify") !== undefined ? { also: listOf(str(args, "notify")!) } : {}),
591 ...(str(args, "label") !== undefined ? { addLabels: labelList(str(args, "label")!) } : {}),
592 ...(str(args, "unlabel") !== undefined ? { removeLabels: labelList(str(args, "unlabel")!) } : {}),
593 // A labels-only edit tells nobody unless --notify names people.
594 ...(edits.every((f) => f === "label" || f === "unlabel") && str(args, "notify") !== undefined
595 ? { notify: true }
596 : {}),
597 });
598 return {
599 text: `Edited issue ${id}. ${r.notified.length > 0 ? `Told ${r.notified.join(", ")}.` : "Told nobody."}`,
600 json: { issue: id, edit: r.edit, notified: r.notified },
601 };
602 }
603 if (bool(args, "quiet") || str(args, "notify") !== undefined)
604 throw new UsageError(
605 "--quiet and --notify go with an edit (--title, --description, --parent, --agent, --blocked-by, --label or --unlabel)",
606 );
607 if (str(args, "attach") !== undefined && comment === undefined && object === undefined)
608 throw new UsageError("--attach goes with abso issue new or --comment (or --object)");
609 if (comment !== undefined || object !== undefined) {
610 // Refused before anything goes up: an objection is one comment, and a part of one would read as a whole.
611 if (object !== undefined && object.length > COMMENT_MAX)
612 throw new UsageError(
613 `an objection holds up to ${COMMENT_MAX} characters, and this one has ${object.length}: say it shorter, and put the rest in a --comment`,
614 );
615 const parts = object !== undefined ? [object] : commentParts(comment!);
616 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
617 const ids: number[] = [];
618 for (const [i, part] of parts.entries()) {
619 // The attachments go on the first part, which the rest follow.
620 ids.push((await api.issueComment(id, part, object !== undefined, i === 0 ? attachments : [])).id);
621 }
622 const inParts = parts.length > 1 ? ` in ${parts.length} parts (comments ${ids.join(", ")})` : "";
623 return {
624 text: `${object !== undefined ? "Objected" : "Commented"} on issue ${id}${inParts}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. Its agents hear it.`,
625 json: {
626 id: ids[0],
627 issue: id,
628 ...(parts.length > 1 ? { parts: ids } : {}),
629 ...(attachments.length > 0 ? { attachments } : {}),
630 },
631 };
632 }
633 if (bool(args, "drop")) {
634 await api.issueDrop(id);
635 return { text: `Dropped issue ${id}.`, json: { issue: id, dropped: true } };
636 }
637 if (bool(args, "reopen")) {
638 await api.issueReopen(id);
639 return { text: `Reopened issue ${id}.`, json: { issue: id, reopened: true } };
640 }
641 if (markingDone) {
642 let version: number | null = null;
643 if (doneBy !== undefined) {
644 version = issueNumber(doneBy, "--done-by");
645 if (version < 1) throw new UsageError("--done-by is a pushed version, 1 or more");
646 try {
647 await api.show(version, { draft: null });
648 } catch {
649 throw new UsageError(`no version ${version}`);
650 }
651 }
652 await api.issueDone(id, version);
653 return {
654 text: version === null ? `Marked issue ${id} done.` : `Marked issue ${id} done in version ${version}.`,
655 json: { issue: id, done: true, ...(version !== null ? { version } : {}) },
656 };
657 }
658 const page = await api.issue(id);
659 if (saveTo !== undefined) return saveAttachments(api, root, env.cwd, saveTo, page);
660 return { text: issuePage(page, api).join("\n"), json: { ...page } };
661}
663export async function runAsk(args: Parsed, env: Env): Promise<Output> {
664 const withdraw = str(args, "withdraw");
665 if (withdraw !== undefined) return withdrawAsk(args, env, withdraw);
666 if (str(args, "note") !== undefined)
667 throw new UsageError('--note goes with --withdraw: abso ask --withdraw <ask> --note "why"');
668 const [of, ...words] = args.positionals;
669 if (of !== undefined && words.length === 0 && /^\d+$/.test(of)) return showAsk(args, env, of);
670 if (of === undefined || words.length === 0)
671 throw new UsageError(
672 'abso ask <who> "<question>" [--issue <N>] [--review | --task] [--due <YYYY-MM-DD>] [--blocks <N,N>] [--options "A|B|C"]; who is an agent, or person:<id>',
673 );
674 const { api } = openIssues(env);
675 if (bool(args, "review") && bool(args, "task")) throw new UsageError("an ask is a review or a task, not both");
676 const issue = str(args, "issue");
677 const blocks = str(args, "blocks");
678 const options = str(args, "options");
679 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
680 const r = await api.ask({
681 of,
682 question: words.join(" "),
683 ...(issue !== undefined ? { issue: issueNumber(issue, "--issue") } : {}),
684 ...(bool(args, "review") ? { review: true } : {}),
685 ...(bool(args, "task") ? { kind: "task" as const } : {}),
686 ...(str(args, "due") ? { due: str(args, "due")! } : {}),
687 ...(blocks !== undefined ? { blocks: blocks.split(",").map((b) => issueNumber(b.trim(), "--blocks")) } : {}),
688 ...(options !== undefined
689 ? {
690 options: options
691 .split("|")
692 .map((o) => o.trim())
693 .filter((o) => o !== ""),
694 }
695 : {}),
696 ...(attachments.length > 0 ? { attachments } : {}),
697 });
698 const lost = notKept(attachments, r.attachments, `ask ${r.id}`);
699 return {
700 text: `Asked ${of} (ask ${r.id})${withFiles(attachments)}. They hear it; abso waiting shows what's open.${lost ? ` ${lost}` : ""}`,
701 json: { id: r.id, ...(attachments.length > 0 ? { attachments } : {}), ...(lost ? { notKept: lost } : {}) },
702 };
703}
705/** abso ask <N>: one ask, open or closed, with its whole thread, its answer and whose turn it is. */
706async function showAsk(args: Parsed, env: Env, word: string): Promise<Output> {
707 const others = ["issue", "due", "blocks", "options", "attach"].filter((f) => str(args, f) !== undefined);
708 if (others.length > 0 || bool(args, "review") || bool(args, "task"))
709 throw new UsageError('abso ask <N> shows ask N; to ask, say who and what: abso ask <who> "<question>"');
710 const id = issueNumber(word, "the ask number");
711 const { api, config } = openIssues(env);
712 const { ask } = await api.askThread(id);
713 const side = ask.of === config.agent || ask.by === config.agent;
714 const turn = ask.waitingOn === config.agent ? "you" : ask.waitingOn;
715 const steps = !side
716 ? ""
717 : ask.answer
718 ? `abso reply ${id} "..." still adds to it.`
719 : ask.of === config.agent
720 ? `abso reply ${id} "..." adds to it; abso answer ${id} "..." answers and closes it.`
721 : `abso reply ${id} "..." adds to it.`;
722 const next = [!ask.answer && turn ? `It waits on ${turn}.` : "", steps].join(" ");
723 return {
724 text: [askLine(ask, api, true), next.trim()].filter((l) => l !== "").join("\n"),
725 json: { ask },
726 };
727}
729/** abso reply <ask> "<words>" [--question]: add to an ask's thread, as its asker or the one asked. */
730export async function runReply(args: Parsed, env: Env): Promise<Output> {
731 const [first, ...words] = args.positionals;
732 const id = issueNumber(first, "the ask number");
733 if (words.length === 0)
734 throw new UsageError(
735 `abso reply <ask> "<words>" [--question]: adds to an ask's thread, as its asker or the one asked`,
736 );
737 const { api, config } = openIssues(env);
738 const question = bool(args, "question");
739 const r = await api.reply(id, { text: words.join(" "), ...(question ? { question: true } : {}) });
740 const other = r.ask.by === config.agent ? r.ask.of : r.ask.by;
741 const turn =
742 !r.ask.answer && r.ask.waitingOn
743 ? ` It waits on ${r.ask.waitingOn === config.agent ? "you" : r.ask.waitingOn}.`
744 : "";
745 return { text: `Replied on ask ${id}. ${other} hears it.${turn}`, json: { ask: r.ask } };
746}
748/** abso ask --withdraw <ask> [--note "why"]: the asker takes an ask back. It closes like an answer, and the one asked hears it. */
749async function withdrawAsk(args: Parsed, env: Env, word: string): Promise<Output> {
750 const others = ["issue", "due", "blocks", "options", "attach"].filter((f) => str(args, f) !== undefined);
751 if (args.positionals.length > 0 || others.length > 0 || bool(args, "review") || bool(args, "task"))
752 throw new UsageError('abso ask --withdraw <ask> [--note "why"] takes nothing else: it takes back an ask you made');
753 const id = issueNumber(word, "the ask number");
754 const { api } = openIssues(env);
755 const note = str(args, "note");
756 const r = await api.withdraw(id, note !== undefined ? { note } : {});
757 return { text: `Withdrew ask ${id}. ${r.ask.of} hears it, and it no longer waits on them.`, json: { ask: r.ask } };
758}
760/** One search hit as two lines: the issue, then where it matched and the words around it. */
761export function searchLines(h: IssueSearchHit): string[] {
762 const where = h.meaning ? "by meaning" : h.where === "comment" ? `in comment ${h.comment}` : `in the ${h.where}`;
763 const words = h.snippet
764 .replace(/[\u0001\u0002]/g, "")
765 .replace(/\s+/g, " ")
766 .trim();
767 return [
768 ` ${String(h.issue.id).padStart(3)} ${h.issue.status.padEnd(11)} ${q(h.issue.title)}`,
769 ` ${where}${words && words !== h.issue.title ? `: ${q(words)}` : ""}`,
770 ];
771}
773export async function runSearch(args: Parsed, env: Env): Promise<Output> {
774 const words = args.positionals.join(" ").trim();
775 if (words === "") throw new UsageError('search needs words: abso search "<words>" [--limit <N>]');
776 const limitWord = str(args, "limit");
777 const limit = limitWord === undefined ? undefined : Number(limitWord);
778 if (limit !== undefined && !(Number.isInteger(limit) && limit >= 1 && limit <= 50))
779 throw new UsageError("--limit is a number from 1 to 50");
780 const { api } = openIssues(env);
781 const { hits } = await api.issueSearch(words, limit);
782 return {
783 text:
784 hits.length === 0
785 ? `Nothing matches ${q(words)}.`
786 : [
787 `${plural(hits.length, "issue")} for ${q(words)}, best first:`,
788 ...hits.flatMap(searchLines),
789 "abso issue <N> shows one.",
790 ].join("\n"),
791 json: { hits },
792 };
793}
795export async function runWaiting(args: Parsed, env: Env): Promise<Output> {
796 if (args.positionals.length > 0)
797 throw new UsageError("waiting takes no words: abso waiting [--of <agent or person:id>] [--mine] [--asked]");
798 if (bool(args, "asked")) return askedOf(args, env);
799 const { api, config } = openIssues(env);
800 const mine = bool(args, "mine") || str(args, "of") === config.agent;
801 const of = mine ? config.agent : str(args, "of");
802 // With --mine, your own publishes still in the merge queue are open work too. A server without a queue,
803 // or one that can't be read now, leaves them out rather than failing the asks.
804 const [{ asks }, queue] = await Promise.all([
805 mine ? api.waitingMine() : api.waiting(of),
806 mine ? api.queueState().catch(() => undefined) : undefined,
807 ]);
808 const queued = queuedLines(queue, config.agent);
809 const yours = (queue?.items ?? []).filter((q) => q.agent === config.agent);
810 return {
811 text: [
812 ...queued,
813 ...(asks.length === 0
814 ? [queued.length > 0 ? `No open asks of ${of}.` : `Nothing is waiting${of ? ` on ${of}` : ""}.`]
815 : [
816 `${plural(asks.length, "open ask")}${of ? ` of ${of}` : ""}, soonest due first:`,
817 ...asks.map((a) => askLine(a, api)),
818 'abso ask <N> shows one with its thread; abso reply <N> "..." adds to it; abso answer <N> "..." answers one asked of you.',
819 ]),
820 ].join("\n"),
821 json: {
822 asks,
823 ...(yours.length > 0
824 ? { queued: yours.map((q) => ({ id: q.id, message: q.message, standing: standing(queue!.items, q.id) })) }
825 : {}),
826 },
827 };
828}
830/** abso waiting --asked: the asks you sent, open ones first, then the latest answered, each with its newest reply. */
831async function askedOf(args: Parsed, env: Env): Promise<Output> {
832 if (bool(args, "mine") || str(args, "of") !== undefined)
833 throw new UsageError("--asked lists the asks you sent; it takes no --mine or --of");
834 const { api, config } = openIssues(env);
835 const { asks } = await api.asked();
836 const open = asks.filter((a) => !a.answer);
837 const closed = asks.filter((a) => a.answer);
838 return {
839 text: [
840 ...(asks.length === 0
841 ? [`${config.agent} hasn't asked anything yet.`]
842 : [
843 ...(open.length > 0
844 ? [`${plural(open.length, "open ask")} you sent:`, ...open.map((a) => askLine(a, api))]
845 : []),
846 ...(closed.length > 0
847 ? [
848 `${closed.length === 1 ? "The latest answered" : `The latest ${closed.length} answered`}:`,
849 ...closed.map((a) => askLine(a, api)),
850 ]
851 : []),
852 "abso ask <N> shows one with its whole thread.",
853 ]),
854 ].join("\n"),
855 json: { asks },
856 };
857}
859/** abso ack <ask> ["note"]: tell the asker you have it, and answer later. The ask stays open until abso answer. */
860export async function runAck(args: Parsed, env: Env): Promise<Output> {
861 const [first, ...words] = args.positionals;
862 const id = issueNumber(first, "the ask number");
863 const { api } = openIssues(env);
864 const note = words.join(" ");
865 const r = await api.ack(id, note !== "" ? { note } : {});
866 return {
867 text: `Acknowledged ask ${id}. ${r.ask.by} hears it; abso reply ${id} "..." adds more as you go, and the ask stays open until abso answer ${id} "...".`,
868 json: { ask: r.ask },
869 };
870}
872export async function runAnswer(args: Parsed, env: Env): Promise<Output> {
873 const [first, ...words] = args.positionals;
874 const id = issueNumber(first, "the ask number");
875 const option = str(args, "option");
876 const done = bool(args, "done");
877 if (words.length === 0 && option === undefined && !done)
878 throw new UsageError('abso answer <ask> "<words>" | --option <N> [--note "..."] | --done [--note "..."]');
879 const { api } = openIssues(env);
880 const note = str(args, "note");
881 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
882 const r = await api.answer(id, {
883 ...(words.length > 0 ? { words: words.join(" ") } : {}),
884 ...(option !== undefined ? { option: /^\d+$/.test(option) ? Number(option) - 1 : option } : {}),
885 ...(done ? { done: true } : {}),
886 ...(note !== undefined ? { note } : {}),
887 ...(attachments.length > 0 ? { attachments } : {}),
888 });
889 const lost = notKept(
890 attachments,
891 r.ask.answer?.attachments?.map((a) => a.id),
892 `your answer to ask ${id}`,
893 );
894 return {
895 text: `Answered ask ${id}${withFiles(attachments)}. ${r.ask.by} hears it.${lost ? ` ${lost}` : ""}`,
896 json: { ask: r.ask, ...(lost ? { notKept: lost } : {}) },
897 };
898}
900/** What the Issues Worker takes in one comment (its LIMITS.text). */
901export const COMMENT_MAX = 4000;
903/** Room a part keeps for its "(i/n)" line and blank line, and for closing a code block it ends inside. */
904const PART_MARK = 12;
905const FENCE_CLOSE = 5;
907/**
908 * A comment too long for one, as parts that each fit, each starting with "(i/n)". A part ends at the last
909 * paragraph break that fits, else the last line break, else the last space, else at the limit. A part that
910 * would end inside a fenced code block closes it, and the next part opens it again with the same fence line.
911 */
912export function commentParts(text: string, max = COMMENT_MAX): string[] {
913 if (text.length <= max) return [text];
914 const bodies: string[] = [];
915 let rest = text;
916 let reopen = "";
917 while (rest !== "") {
918 const room = max - PART_MARK - FENCE_CLOSE - reopen.length;
919 let body: string;
920 if (reopen.length + rest.length <= max - PART_MARK) {
921 body = rest;
922 rest = "";
923 } else {
924 const cut = cutAt(rest, room);
925 body = rest.slice(0, cut).trimEnd();
926 // A space cut at goes with neither part; the line breaks between paragraphs go too.
927 rest = rest.slice(rest[cut] === " " ? cut + 1 : cut).replace(/^\n+/, "");
928 if (rest.trim() === "") rest = "";
929 }
930 let part = reopen + body;
931 const fence = openFence(part);
932 if (fence && rest !== "") {
933 part += `\n${fence.marker}`;
934 reopen = `${fence.line}\n`;
935 } else reopen = "";
936 bodies.push(part);
937 }
938 return bodies.map((b, i) => `(${i + 1}/${bodies.length})\n\n${b}`);
939}
941/** Where to end a part of at most `room` characters of `text`: a paragraph break, a line break, a space, or the limit. */
942function cutAt(text: string, room: number): number {
943 const head = text.slice(0, room);
944 const floor = room / 4;
945 for (const at of [head.lastIndexOf("\n\n"), head.lastIndexOf("\n"), head.lastIndexOf(" ")]) if (at > floor) return at;
946 // Not between the two halves of a character outside the Basic Multilingual Plane.
947 const code = text.charCodeAt(room - 1);
948 return code >= 0xd800 && code <= 0xdbff ? room - 1 : room;
949}
951/** The fence line of a code block still open at the end of `text`, and the marker that closes it, or undefined. */
952function openFence(text: string): { line: string; marker: string } | undefined {
953 let open: { line: string; marker: string } | undefined;
954 for (const line of text.split("\n")) {
955 const m = /^\s*(`{3,}|~{3,})/.exec(line);
956 if (!m) continue;
957 if (!open) open = { line, marker: m[1]! };
958 else if (m[1]!.startsWith(open.marker) && line.trim() === m[1]) open = undefined;
959 }
960 return open;
961}