Skip to content

abso-core

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