@vercel/board 0.45.1 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/{access-3udXjJAg.mjs → access-Crbvd2Dm.mjs} +2 -2
  2. package/dist/access.d.mts +2 -2
  3. package/dist/access.mjs +5 -5
  4. package/dist/{actors-DasGZnfb.mjs → actors-BBphaJ_G.mjs} +3 -3
  5. package/dist/{auth-aiOVE82-.mjs → auth-C-pFnJBA.mjs} +2 -2
  6. package/dist/{auth-BG_whr9_.d.mts → auth-CkNXnQno.d.mts} +1 -1
  7. package/dist/{backend-D6yTo8Un.d.mts → backend-D3p8gjba.d.mts} +126 -4
  8. package/dist/backend-local.d.mts +1 -1
  9. package/dist/backend-local.mjs +1 -1
  10. package/dist/{chat-provider-BvNqOQFL.mjs → chat-provider-1zpY6Qo_.mjs} +2 -2
  11. package/dist/{chat-provider-V2jnjVLq.d.mts → chat-provider-Bn33acHd.d.mts} +2 -2
  12. package/dist/cli-commands.d.mts +1 -1
  13. package/dist/cli-commands.mjs +1 -1
  14. package/dist/cli-embedded.d.mts +2 -2
  15. package/dist/cli-embedded.mjs +3 -2
  16. package/dist/cli.mjs +6 -6
  17. package/dist/{commands-DewS14_P.d.mts → commands-CSZPQ38I.d.mts} +54 -0
  18. package/dist/{commands-CqdnjUkm.mjs → commands-D0lyo8O8.mjs} +319 -0
  19. package/dist/{conformance-BInS4_6b.mjs → conformance-Blzd4CXG.mjs} +972 -6
  20. package/dist/conformance.d.mts +6 -5
  21. package/dist/conformance.mjs +1 -1
  22. package/dist/{engine-XVBt02Bl.mjs → engine-C_SlBihU.mjs} +15 -7
  23. package/dist/{errors-ZazTZh-s.mjs → errors-DZ1tbwSM.mjs} +151 -3
  24. package/dist/{events-D17RndlV.mjs → events-mGuhF4i5.mjs} +2 -2
  25. package/dist/{exports-DCxecX15.mjs → exports-DQauuHrc.mjs} +1226 -42
  26. package/dist/exports-DUX_Yzo7.d.mts +44 -0
  27. package/dist/{external-DfhN7lKK.mjs → external-BVr1Sq0y.mjs} +1 -1
  28. package/dist/{index-Djmr4GzQ.d.mts → index-BHXg4Xdo.d.mts} +2 -2
  29. package/dist/index.d.mts +6 -6
  30. package/dist/index.mjs +5 -5
  31. package/dist/index.node.d.mts +7 -6
  32. package/dist/index.node.mjs +5 -4
  33. package/dist/inspect/app.js +215 -115
  34. package/dist/inspect/engine.js +5 -5
  35. package/dist/{inspect-CHsgnf_5.mjs → inspect-2OIjv2lW.mjs} +242 -20
  36. package/dist/inspect-F-b4GPXX.mjs +2 -0
  37. package/dist/{local-DE9vmanM.mjs → local-11FMUJrU.mjs} +1593 -60
  38. package/dist/{main-CF1Me3jg.mjs → main-BYmbTDgo.mjs} +1167 -24
  39. package/dist/{memory-DyEL0fvN.mjs → memory-CZBdVNn8.mjs} +2 -2
  40. package/dist/{middleware-BHHKHA9q.mjs → middleware-BKsTcMAv.mjs} +2 -2
  41. package/dist/{provider-BC9mPYVh.d.mts → provider-D3bfHRHA.d.mts} +119 -3
  42. package/dist/{routes-CkUetTO2.mjs → routes-B2HHHD_C.mjs} +246 -6
  43. package/dist/{routes-zm4TXKCC.d.mts → routes-NEc6w3QC.d.mts} +540 -6
  44. package/dist/{schemas-BhZaystC.mjs → schemas-7VFdomFB.mjs} +34 -1
  45. package/dist/{serve-CEMvl0EH.mjs → serve-DS2T2iWI.mjs} +4 -4
  46. package/dist/{server-Bmz0zqYM.mjs → server-Ch3tuK2k.mjs} +10 -10
  47. package/dist/{serving-BLVRrJ7P.mjs → serving-9riPNrHk.mjs} +1 -1
  48. package/dist/{sql-CyVcjw8x.mjs → sql-Bml29DpM.mjs} +174 -9
  49. package/dist/{sqlite-Con-8duk.mjs → sqlite-4C5u7-ag.mjs} +2 -2
  50. package/dist/{sqlite-db-BdzxtUOV.mjs → sqlite-db-eVb9v3zc.mjs} +1 -1
  51. package/dist/sync-chat-sdk.d.mts +2 -2
  52. package/dist/sync-chat-sdk.mjs +2 -2
  53. package/dist/sync-github.d.mts +2 -2
  54. package/dist/sync-github.mjs +2 -2
  55. package/dist/sync-linear.d.mts +3 -3
  56. package/dist/sync-linear.mjs +2 -2
  57. package/dist/sync-slack.d.mts +3 -3
  58. package/dist/sync-slack.mjs +4 -4
  59. package/dist/sync.d.mts +2 -2
  60. package/dist/sync.mjs +2 -2
  61. package/dist/{origin-BbwhnKrg.mjs → task-batch-BJcLiYe1.mjs} +83 -8
  62. package/dist/{tokens-BErYXuHZ.mjs → tokens-DPKF_cb5.mjs} +2 -2
  63. package/docs/01-board/01-mounting.md +1 -1
  64. package/docs/01-board/08-middleware.md +7 -0
  65. package/docs/01-board/11-tasks.md +348 -0
  66. package/docs/03-guides/02-inspector.md +66 -9
  67. package/docs/03-guides/06-sandboxed-agents.md +5 -3
  68. package/docs/03-guides/07-build-a-ui.md +210 -0
  69. package/docs/04-reference/01-cli.md +216 -8
  70. package/docs/04-reference/02-board.md +277 -2
  71. package/docs/04-reference/03-http.md +184 -10
  72. package/docs/04-reference/05-conformance.md +10 -7
  73. package/package.json +1 -1
  74. package/dist/exports-Gspe1eEq.d.mts +0 -4
  75. package/dist/inspect-C8U3A4jQ.mjs +0 -2
@@ -1,19 +1,20 @@
1
- import { d as BoardError, v as DIRECT_UPLOAD_BYTES_MAX, x as fileSize } from "./errors-ZazTZh-s.mjs";
2
- import { p as MESSAGE_TEXT_MAX, r as AttachmentId } from "./schemas-BhZaystC.mjs";
1
+ import { C as fileSize, b as DIRECT_UPLOAD_BYTES_MAX, f as BoardError } from "./errors-DZ1tbwSM.mjs";
2
+ import { m as MESSAGE_TEXT_MAX, r as AttachmentId } from "./schemas-7VFdomFB.mjs";
3
3
  import { n as displayEmoji, r as normalizeEmoji } from "./emoji-CTLpvH-A.mjs";
4
- import { l as shownName } from "./middleware-BHHKHA9q.mjs";
4
+ import { l as shownName } from "./middleware-BKsTcMAv.mjs";
5
5
  import { d as parseSchemaId, r as findBlocks, t as block } from "./blocks-CVoBC7ur.mjs";
6
- import { h as VERSION, s as withMentions } from "./origin-BbwhnKrg.mjs";
7
- import { r as PERMISSIONS } from "./access-3udXjJAg.mjs";
8
- import { a as isApiMessageId, n as isBoardName } from "./exports-DCxecX15.mjs";
9
- import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-CqdnjUkm.mjs";
10
- import { a as vercel, c as connect, i as handTeam, l as handFetch, n as credentialSource, o as http, p as vercelProjectFile, r as credentialed, s as boardUrl, t as board, u as handLogin } from "./server-Bmz0zqYM.mjs";
11
- import { t as conformance } from "./conformance-BInS4_6b.mjs";
6
+ import { c as withMentions, g as VERSION } from "./task-batch-BJcLiYe1.mjs";
7
+ import { r as PERMISSIONS } from "./access-Crbvd2Dm.mjs";
8
+ import { i as isBoardName, n as createTasksInChunks, s as isApiMessageId, t as TasksInChunksError } from "./exports-DQauuHrc.mjs";
9
+ import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-D0lyo8O8.mjs";
10
+ import { a as vercel, c as configDir, d as handFetch, f as handLogin, h as vercelProjectFile, i as handTeam, l as connect, n as credentialSource, o as http, r as credentialed, s as boardUrl, t as board, u as environmentProfile } from "./server-Ch3tuK2k.mjs";
11
+ import { t as conformance } from "./conformance-Blzd4CXG.mjs";
12
12
  import { n as displayText } from "./bots-CLKKMgYf.mjs";
13
13
  import { spawn } from "node:child_process";
14
- import { readFile, stat, writeFile } from "node:fs/promises";
14
+ import { createHash, randomUUID } from "node:crypto";
15
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
15
16
  import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
16
- import { homedir } from "node:os";
17
+ import { constants, homedir } from "node:os";
17
18
  import { basename, dirname, join } from "node:path";
18
19
  import { parseArgs } from "node:util";
19
20
  //#region src/cli/grants.ts
@@ -351,6 +352,7 @@ function formatMessage(message, options = {}) {
351
352
  const pad = options.reply ? " " : " ";
352
353
  const head = `${options.reply ? " ↳ " : ""}#${message.id} ${authorName(message)} · ${ago(message.createdAt)}${message.editedAt ? " (edited)" : ""}${message.schedule ? ` · scheduled ${message.schedule.id}` : ""}${labels(message)}`;
353
354
  const body = message.deleted ? `${pad}(message removed)` : indent(shownText(message), pad);
355
+ const task = message.task ? [`${pad}task ${taskState(message, message.task, options.names ?? /* @__PURE__ */ new Map(), options.now ?? Date.now())}`] : [];
354
356
  const files = (message.attachments ?? []).map((a) => `${pad}file ${a.name} · ${a.type} · ${fileSize(a.size)} · ${a.id}`);
355
357
  const links = message.deleted ? [] : (message.links ?? []).flatMap((link) => embed(link, pad));
356
358
  const reacted = reactions(message, options.names ?? /* @__PURE__ */ new Map());
@@ -358,12 +360,78 @@ function formatMessage(message, options = {}) {
358
360
  return [
359
361
  head,
360
362
  body,
363
+ ...task,
361
364
  ...files,
362
365
  ...links,
363
366
  ...reacted ? [`${pad}${reacted}`] : [],
364
367
  ...undelivered
365
368
  ].join("\n");
366
369
  }
370
+ /** The first line of what a task came to, or of why it's held or ended: the rest is in its thread. */
371
+ const noteLine = (text, max = 60) => {
372
+ const [line = ""] = text.trim().split(/\r?\n/);
373
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
374
+ };
375
+ /** The profile an actor ID names (`vercel:user:u_abc+fixer` is `fixer`), or the ID itself when it names none. */
376
+ const profileOf = (actor) => actor.includes("+") ? actor.slice(actor.lastIndexOf("+") + 1) : actor;
377
+ /** How long a lease has left, as a duration flag would say it, to the minute from a minute up: `15m`, `45s`. */
378
+ function leaseLeft(until, now = Date.now()) {
379
+ const ms = Date.parse(until) - now;
380
+ if (ms <= 0) return "0s";
381
+ return span(ms < 6e4 ? Math.ceil(ms / 1e3) * 1e3 : Math.round(ms / 6e4) * 6e4);
382
+ }
383
+ /**
384
+ * A task's state as `read` says it under its root: who holds it and for how long, what it's held
385
+ * for or how it ended, then what it waits for, whom it's for, and whose it is when that isn't its
386
+ * root's author. `names` are the display names the reader knows, by actor ID.
387
+ */
388
+ function taskState(message, task, names, now) {
389
+ const named = (id) => names.get(id) ?? id;
390
+ const parts = [];
391
+ if (task.state === "claimed" && task.claim) {
392
+ const left = Date.parse(task.claim.until) - now;
393
+ parts.push(`claimed by ${named(task.claim.actor)}`, left > 0 ? `${leaseLeft(task.claim.until, now)} left` : "its lease ran out");
394
+ } else if (task.state === "blocked" && task.blocked) parts.push("blocked", ...task.blocked.kind ? [task.blocked.kind] : [], noteLine(task.blocked.reason));
395
+ else if (task.state === "completed") parts.push("completed", ...task.result ? [noteLine(task.result)] : []);
396
+ else if (task.state === "failed" || task.state === "canceled") parts.push(task.state, ...task.reason ? [noteLine(task.reason)] : []);
397
+ else parts.push(task.state);
398
+ if (task.needs.length) parts.push(`needs ${task.needs.map((id) => `#${id}`).join(" ")}`);
399
+ if (task.for !== null) parts.push(`for ${profileOf(task.for)}`);
400
+ if (task.owner !== message.by.principal) parts.push(`owner ${named(task.owner)}`);
401
+ return parts.join(" · ");
402
+ }
403
+ /** A claim as the CLI says it: the task, how long it's yours, and what it is. */
404
+ const claimLine = (task, until, now = Date.now()) => `#${task.id} yours for ${leaseLeft(until, now)} ${firstLine(task, 52)}`;
405
+ /**
406
+ * What a task's row says after its text: how it ended or what it's held for, in the `room` the row
407
+ * has left, or its own labels, whole, and what it waits for.
408
+ */
409
+ function taskNote(message, task, room) {
410
+ if (task.state === "completed" && task.result) return noteLine(task.result, room);
411
+ if ((task.state === "failed" || task.state === "canceled") && task.reason) return noteLine(task.reason, room);
412
+ if (task.state === "blocked" && task.blocked) return noteLine(task.blocked.reason, room);
413
+ return [Object.entries(message.labels).filter(([key]) => !key.startsWith("board.")).map(([key, value]) => `${key}=${value}`).join(" "), task.state === "waiting" && task.needs.length ? `needs ${task.needs.map((id) => `#${id}`).join(" ")}` : ""].filter(Boolean).join(" ");
414
+ }
415
+ /** The widest a task's state is (`completed`), and how wide its first line's column is at least and at most. */
416
+ const STATE_WIDTH = 9;
417
+ const TASK_TEXT_MIN = 30;
418
+ const TASK_TEXT_MAX = 40;
419
+ /** The least a row leaves for how a task ended, however long its ID. */
420
+ const TASK_NOTE_MIN = 20;
421
+ /**
422
+ * Tasks, one a row: its ID, its state, its first line, and what's notable about it. The state's
423
+ * column is as wide as any state, and the text's at least 30, so one list lines up with the next.
424
+ * What a person wrote about how it ended is cut to fit 80 columns: the rest is in its thread.
425
+ */
426
+ function formatTasks(tasks) {
427
+ const rows = tasks.map(({ message }) => [
428
+ `#${message.id}`,
429
+ (message.task?.state ?? "").padEnd(STATE_WIDTH),
430
+ firstLine(message, TASK_TEXT_MAX).padEnd(TASK_TEXT_MIN)
431
+ ]);
432
+ const room = Math.max(TASK_NOTE_MIN, 80 - rows.reduce((widest, row) => Math.max(widest, row.join(" ").length), 0) - 2);
433
+ return table(rows.map((row, at) => [...row, tasks[at].message.task ? taskNote(tasks[at].message, tasks[at].message.task, room) : ""]));
434
+ }
367
435
  /** Threads in order, each root followed by its replies. */
368
436
  function formatThreads(messages, known = /* @__PURE__ */ new Map()) {
369
437
  const names = new Map([...known, ...messages.map((m) => [m.by.actor, authorName(m)])]);
@@ -384,15 +452,15 @@ function formatThreads(messages, known = /* @__PURE__ */ new Map()) {
384
452
  })}`);
385
453
  return blocks.join("\n\n");
386
454
  }
387
- /** A root's first line, cut to fit 80 columns under its header. */
388
- function firstLine(message) {
455
+ /** A root's first line, cut to `max` characters: 74 fits 80 columns under its header. */
456
+ function firstLine(message, max = 74) {
389
457
  if (message.deleted) return "(message removed)";
390
458
  const text = shownText(message).trim();
391
459
  const files = message.attachments?.length ?? 0;
392
460
  if (!text) return files ? `(${files} ${files === 1 ? "file" : "files"})` : "(no text)";
393
461
  const [line = "", ...rest] = text.split(/\r?\n/);
394
462
  const shown = rest.length ? `${line.trimEnd()} …` : line;
395
- return shown.length > 74 ? `${line.slice(0, 73)}…` : shown;
463
+ return shown.length > max ? `${line.slice(0, max - 1)}…` : shown;
396
464
  }
397
465
  /**
398
466
  * One block per thread, for `read <channel>`: the root's header and first line,
@@ -533,9 +601,40 @@ function formatEvent(event) {
533
601
  return `#${message.id} ${where} labels ${[...set, ...unset].join(" ")}${event.actor ? ` by ${event.actor.name}` : ""}`;
534
602
  }
535
603
  case "message.sync_failed": return `#${message.id} ${where} ✗ didn't reach ${event.payload.target}: ${event.payload.error}`;
604
+ case "task.created":
605
+ case "task.assigned":
606
+ case "task.needs_changed":
607
+ case "task.ready":
608
+ case "task.claimed":
609
+ case "task.renewed":
610
+ case "task.released":
611
+ case "task.expired":
612
+ case "task.completed":
613
+ case "task.failed":
614
+ case "task.blocked":
615
+ case "task.unblocked":
616
+ case "task.canceled":
617
+ case "task.reopened": return `#${message.id} ${where} task ${taskEvent(event)}`;
536
618
  default: return `#${event.cursor} ${event.type}`;
537
619
  }
538
620
  }
621
+ /** What happened to a task, after `task`: `claimed by claude via ada`, `completed by claude via ada · tests pass`. */
622
+ function taskEvent(event) {
623
+ const by = event.actor ? ` by ${actorName(event.actor)}` : "";
624
+ const more = (...parts) => parts.filter((part) => !!part).map((part) => ` · ${part}`).join("");
625
+ switch (event.type) {
626
+ case "task.created": return `created${by}${more(event.payload.needs.length ? `needs ${event.payload.needs.map((id) => `#${id}`).join(" ")}` : null, event.payload.for !== null ? `for ${profileOf(event.payload.for)}` : null)}`;
627
+ case "task.assigned": return event.payload.for !== null ? `assigned to ${profileOf(event.payload.for)}${by}` : `unassigned${by}`;
628
+ case "task.needs_changed": return `needs ${event.payload.needs.length ? event.payload.needs.map((id) => `#${id}`).join(" ") : "nothing"}${by}`;
629
+ case "task.ready": return "ready";
630
+ case "task.expired": return "lease ran out";
631
+ case "task.completed": return `completed${by}${more(event.payload.result === null ? null : noteLine(event.payload.result))}`;
632
+ case "task.failed": return `failed${by}${more(noteLine(event.payload.reason))}`;
633
+ case "task.blocked": return `blocked${by}${more(event.payload.kind, noteLine(event.payload.reason))}`;
634
+ case "task.canceled": return `canceled${by}${more(noteLine(event.payload.reason))}`;
635
+ default: return `${event.type.slice(5)}${by}`;
636
+ }
637
+ }
539
638
  /**
540
639
  * Where a thread is synced, for `vb sync <id>`: a row a target, its sync key and where it is, then
541
640
  * the link to the message's copy there, or why it didn't reach it.
@@ -624,6 +723,169 @@ function formatSchema(schema) {
624
723
  return `${[schema.id, schema.description].filter(Boolean).join(" ")}\n\n${definition}`;
625
724
  }
626
725
  //#endregion
726
+ //#region src/cli/claims.ts
727
+ /** A claim whose lease ended this long ago is no one's to settle: its file goes when another is written. */
728
+ const DEAD_MS = 864e5;
729
+ /** The claims directory: `~/.config/board/claims`, or under `XDG_CONFIG_HOME`, as the CLI's tokens are. */
730
+ const claimsDir = () => join(configDir(), "claims");
731
+ /**
732
+ * The file one claim lives in: named for its board, task, and profile together, hashed, so a name
733
+ * says nothing of any of them, and never holds a token.
734
+ */
735
+ const fileOf = (board, task, profile) => join(claimsDir(), `${createHash("sha256").update(JSON.stringify([
736
+ board,
737
+ task,
738
+ profile
739
+ ])).digest("hex").slice(0, 32)}.json`);
740
+ async function read(file) {
741
+ try {
742
+ const stored = JSON.parse(await readFile(file, "utf8"));
743
+ if (typeof stored.epoch !== "number" || typeof stored.token !== "string" || typeof stored.until !== "string") return null;
744
+ return stored;
745
+ } catch {
746
+ return null;
747
+ }
748
+ }
749
+ /** Removes the claims whose leases ended long ago: a process that was killed leaves its file behind. */
750
+ async function prune(now) {
751
+ for (const name of await readdir(claimsDir()).catch(() => [])) {
752
+ if (!name.endsWith(".json")) {
753
+ const file = join(claimsDir(), name);
754
+ const info = await stat(file).catch(() => null);
755
+ if (info && now - info.mtimeMs > DEAD_MS) await unlink(file).catch(() => {});
756
+ continue;
757
+ }
758
+ const file = join(claimsDir(), name);
759
+ const stored = await read(file);
760
+ if (stored && now - Date.parse(stored.until) > DEAD_MS) await unlink(file).catch(() => {});
761
+ }
762
+ }
763
+ /**
764
+ * Claims in files, one per board, task, and profile: only this user reads them (the directory is
765
+ * 0700, each file 0600), and each is written whole or not at all. `board` is the board's own URL,
766
+ * asked for only when a claim is read or written; `profile` is the profile this run writes as, as
767
+ * an actor's ID has it, or null as yourself. A claim is its actor's: a run as another profile is
768
+ * another actor, and holds none of it.
769
+ */
770
+ function fileClaims(board, profile) {
771
+ let key = null;
772
+ const at = async (task) => fileOf(await (key ??= board()), task, profile);
773
+ return {
774
+ async get(task) {
775
+ const stored = await read(await at(task));
776
+ if (!stored || stored.board !== await key || stored.task !== task || stored.profile !== profile) return null;
777
+ return {
778
+ epoch: stored.epoch,
779
+ token: stored.token,
780
+ until: stored.until
781
+ };
782
+ },
783
+ async put(task, claim) {
784
+ const file = await at(task);
785
+ await mkdir(claimsDir(), {
786
+ recursive: true,
787
+ mode: 448
788
+ });
789
+ const stored = {
790
+ board: await key,
791
+ task,
792
+ profile,
793
+ ...claim
794
+ };
795
+ const partial = `${file}.${process.pid}.${randomUUID()}.tmp`;
796
+ await writeFile(partial, JSON.stringify(stored), { mode: 384 });
797
+ await rename(partial, file).catch(async (error) => {
798
+ await unlink(partial).catch(() => {});
799
+ throw error;
800
+ });
801
+ await prune(Date.now()).catch(() => {});
802
+ },
803
+ async drop(task) {
804
+ await unlink(await at(task)).catch(() => {});
805
+ }
806
+ };
807
+ }
808
+ /** A handle's claims, kept in this process: what `vb()` holds, where the board is a handle and no file is the caller's. */
809
+ const held = /* @__PURE__ */ new WeakMap();
810
+ /** Claims kept in memory, for as long as the process and the handle last: one per task and profile, as the files are. */
811
+ function memoryClaims(board, profile) {
812
+ const claims = held.get(board) ?? held.set(board, /* @__PURE__ */ new Map()).get(board);
813
+ const at = (task) => JSON.stringify([task, profile]);
814
+ return {
815
+ get: async (task) => claims.get(at(task)) ?? null,
816
+ put: async (task, claim) => void claims.set(at(task), claim),
817
+ drop: async (task) => void claims.delete(at(task))
818
+ };
819
+ }
820
+ //#endregion
821
+ //#region src/cli/run.ts
822
+ /** A claim is never renewed more often than this, however short its lease. */
823
+ const RENEW_MIN_MS = 1e4;
824
+ /**
825
+ * Runs `command` with this process's terminal, and calls `renew` every `every` milliseconds (at
826
+ * least 10 seconds apart) while it runs. With `stdout: 'stderr'`, what the command prints on its
827
+ * stdout goes to this process's stderr, for a caller whose own stdout is one document. `renew` answers whether the claim still holds: once it
828
+ * doesn't, the command is stopped. Ctrl-C stops it too. It answers once the command has ended and
829
+ * no renewal is still on its way.
830
+ */
831
+ function runCommand(command, options) {
832
+ return new Promise((resolve) => {
833
+ const child = spawn(command[0], command.slice(1), {
834
+ stdio: [
835
+ "inherit",
836
+ options.stdout === "stderr" ? 2 : "inherit",
837
+ "inherit"
838
+ ],
839
+ env: options.env
840
+ });
841
+ let interrupted = null;
842
+ let lost = false;
843
+ let ended = false;
844
+ let renewing = null;
845
+ const interrupt = () => {
846
+ interrupted = "SIGINT";
847
+ if (!process.stdin.isTTY) child.kill("SIGINT");
848
+ };
849
+ const terminate = () => {
850
+ interrupted = "SIGTERM";
851
+ child.kill("SIGTERM");
852
+ };
853
+ process.on("SIGINT", interrupt);
854
+ process.on("SIGTERM", terminate);
855
+ const timer = setInterval(() => {
856
+ if (renewing || lost) return;
857
+ renewing = options.renew().then((held) => {
858
+ if (held) return;
859
+ lost = true;
860
+ child.kill("SIGTERM");
861
+ }).finally(() => {
862
+ renewing = null;
863
+ });
864
+ }, Math.max(RENEW_MIN_MS, options.every));
865
+ const end = async (ran) => {
866
+ if (ended) return;
867
+ ended = true;
868
+ clearInterval(timer);
869
+ process.off("SIGINT", interrupt);
870
+ process.off("SIGTERM", terminate);
871
+ await renewing;
872
+ resolve(ran.how === "unstarted" ? ran : lost ? { how: "lost" } : interrupted ? {
873
+ how: "interrupted",
874
+ code: 128 + constants.signals[interrupted]
875
+ } : ran);
876
+ };
877
+ child.once("error", (error) => void end({
878
+ how: "unstarted",
879
+ why: error.code === "ENOENT" ? "there's no such command" : error.message
880
+ }));
881
+ child.once("exit", (code, signal) => void end({
882
+ how: "exited",
883
+ code: code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0),
884
+ signal
885
+ }));
886
+ });
887
+ }
888
+ //#endregion
627
889
  //#region src/cli/hooks.ts
628
890
  /**
629
891
  * Where each agent keeps hooks, and which of its events run ours. Claude Code
@@ -1072,11 +1334,24 @@ function commandWord(argv) {
1072
1334
  });
1073
1335
  return canonical(positionals[0]);
1074
1336
  }
1075
- const parseAll = (args) => parseArgs({
1076
- args,
1077
- allowPositionals: true,
1078
- options: OPTIONS
1079
- });
1337
+ /**
1338
+ * What the parser accepts for `word`'s command: every option, with the command's own definition
1339
+ * where it has one. `--claim` takes a value on `grants` and none on `tasks`, and each command's
1340
+ * data says which. The command is found before this applies, so one that's its command's own way
1341
+ * goes after the command's name.
1342
+ */
1343
+ function optionsFor(word) {
1344
+ const command = [...commands, ...Object.values(app.commands).map((own) => own.spec)].find((known) => known.name === word);
1345
+ if (!command) return OPTIONS;
1346
+ const own = [command, ...command.subcommands ?? []].flatMap((c) => c.options);
1347
+ const table = { ...OPTIONS };
1348
+ for (const { name, type, short, multiple } of own) table[name] = {
1349
+ type,
1350
+ ...short ? { short } : {},
1351
+ ...multiple ? { multiple } : {}
1352
+ };
1353
+ return table;
1354
+ }
1080
1355
  let app = {
1081
1356
  name: "board",
1082
1357
  commands: {}
@@ -1127,11 +1402,16 @@ function parse(argv) {
1127
1402
  const removed = removedCommand(word ?? "");
1128
1403
  if (removed) throw removed;
1129
1404
  try {
1130
- const parsed = parseAll(markAttachmentId(args));
1405
+ const table = optionsFor(word);
1406
+ const parsed = parseArgs({
1407
+ args: markAttachmentId(args),
1408
+ allowPositionals: true,
1409
+ options: table
1410
+ });
1131
1411
  ordered = parseArgs({
1132
1412
  args: markAttachmentId(args),
1133
1413
  allowPositionals: true,
1134
- options: OPTIONS,
1414
+ options: table,
1135
1415
  tokens: true
1136
1416
  }).tokens.flatMap((token) => token.kind === "option" ? [{
1137
1417
  name: token.name,
@@ -1145,6 +1425,7 @@ function parse(argv) {
1145
1425
  const known = specOf(word) && new Set(optionsOf(word));
1146
1426
  const foreign = known && ordered.find((option) => !known.has(option.name));
1147
1427
  if (foreign) throw foreignOption(foreign.name, word);
1428
+ if (canonical(positionals[0]) !== word) throw misplaced(args, word);
1148
1429
  }
1149
1430
  /** An option `word` doesn't take: what to do instead, where there's something better to say than that. */
1150
1431
  function foreignOption(name, word) {
@@ -1176,6 +1457,13 @@ function foreignOption(name, word) {
1176
1457
  }]
1177
1458
  });
1178
1459
  }
1460
+ /** An option `word`'s command reads its own way, written before the command: it goes after it. */
1461
+ function misplaced(args, word) {
1462
+ const at = args.indexOf(word ?? "");
1463
+ const before = (at === -1 ? args : args.slice(0, at)).filter((arg) => arg.startsWith("-"));
1464
+ const own = optionsFor(word);
1465
+ return usage(`Put ${before.map((arg) => arg.replace(/=.*$/, "")).find((arg) => arg.startsWith("--") && own[arg.slice(2)] !== OPTIONS[arg.slice(2)]) ?? "its options"} after ${word}.`, { reason: "misplaced_option" });
1466
+ }
1179
1467
  /** What the parser rejected, as misuse: an unknown option (with the likeliest one meant), or an option without its value. */
1180
1468
  function parseFailure(error, argv, word) {
1181
1469
  const option = error.message.match(/--[a-z][\w-]*/)?.[0] ?? /'(-[^' ,]+)/.exec(error.message)?.[1];
@@ -1544,6 +1832,16 @@ function doing() {
1544
1832
  case "channels": return a === "create" ? `create ${b ?? "the channel"}` : "list channels";
1545
1833
  case "schedules":
1546
1834
  case "actors": return `list ${command}`;
1835
+ case "tasks": {
1836
+ if (a === void 0 || !TASK_VERBS.has(a)) return a === void 0 ? "list tasks" : `list tasks in ${a}`;
1837
+ const one = b === void 0 ? "a task" : `task ${ref(b)}`;
1838
+ if (a === "claim" || a === "run") return flags.ready ? `claim a task in ${b ?? "a channel"}` : `claim ${one}`;
1839
+ if (a === "create" && flags["tasks-file"] !== void 0) return `create tasks in ${b ?? "a channel"}`;
1840
+ if (a === "create") return b !== void 0 && isMessageRef(b) ? `make ${ref(b)} a task` : `create a task in ${b ?? "a channel"}`;
1841
+ if (a === "renew") return `renew the claim on ${one}`;
1842
+ if (a === "needs") return `change what ${one} needs`;
1843
+ return `${a} ${one}`;
1844
+ }
1547
1845
  case "grants": return a === "create" ? "create the grant" : a === "update" ? `update grant ${b}` : a === "explain" ? `explain ${b ?? "the channel"}` : a === "revoke" ? `revoke grant ${b}` : "list grants";
1548
1846
  case "schemas": return a === "create" ? `register schema ${b ?? ""}`.trimEnd() : a === "inspect" ? `read schema ${b ?? ""}`.trimEnd() : "list schemas";
1549
1847
  case "sources": return b === void 0 ? "list sources" : `${b} ${c ?? "it"} on ${a}`;
@@ -1579,6 +1877,7 @@ function missing() {
1579
1877
  "schedule"
1580
1878
  ].includes(command) && isMessageRef(a)) return `message ${ref(a)}`;
1581
1879
  if (command === "schedule" && a === "cancel" && b !== void 0) return `schedule ${b}`;
1880
+ if (command === "tasks" && TASK_VERBS.has(a) && b !== void 0 && isMessageRef(b)) return `message ${ref(b)}`;
1582
1881
  if (command === "grants" && (a === "revoke" || a === "update") && b !== void 0) return `grant ${b}`;
1583
1882
  if (command === "schemas" && a === "inspect" && b !== void 0) return `schema ${b}`;
1584
1883
  if (command === "download") return `attachment ${a}`;
@@ -1686,6 +1985,11 @@ function failureOf(error) {
1686
1985
  data: said
1687
1986
  });
1688
1987
  const specific = (fallback) => /^[a-z]+(_[a-z]+)+$/.test(code) && code !== "invalid_request" && code !== "remote_error" ? code : fallback;
1988
+ const about = taskFailure(code, status);
1989
+ if (about) return {
1990
+ ...theirs(about.class, code, about.message, about.next),
1991
+ ...about.whole ? { details: [] } : {}
1992
+ };
1689
1993
  if (status === 400 && code === "invalid_block" && flags.schema !== void 0 && parseSchemaId(flags.schema)) return theirs("usage", code, `Can't ${doing()}.`, [{
1690
1994
  instruction: `See what ${flags.schema} holds`,
1691
1995
  argv: [
@@ -1700,7 +2004,7 @@ function failureOf(error) {
1700
2004
  argv: [...cli(), "schemas"]
1701
2005
  }]);
1702
2006
  if (status === 400 && (code === "text_too_long" || code === "invalid_message" && sentLength > 1e4)) return {
1703
- ...theirs("limit", "payload_too_large", `Can't ${doing()}. A message's text is at most ${MESSAGE_TEXT_MAX.toLocaleString("en-US")} characters.`, [{ instruction: current.command === "edit" ? "Keep the edit short, and reply with the long part in a file with --attach" : "Put the long part in a file and --attach it, with a short summary as the text" }]),
2007
+ ...theirs("limit", "payload_too_large", `Can't ${doing()}. A message's text is at most ${MESSAGE_TEXT_MAX.toLocaleString("en-US")} characters.`, [{ instruction: current.command === "edit" ? "Keep the edit short, and reply with the long part in a file with --attach" : current.command === "tasks" ? "Keep it short, and reply to the task with the long part in a file with --attach" : "Put the long part in a file and --attach it, with a short summary as the text" }]),
1704
2008
  details: []
1705
2009
  };
1706
2010
  if (status === 400) return theirs("usage", specific("invalid_arguments"), `Can't ${doing()}.`);
@@ -2084,7 +2388,9 @@ async function run(command, args) {
2084
2388
  replies
2085
2389
  }), 0;
2086
2390
  const authors = new Set([thread.message, ...replies].map((m) => m.by.actor));
2087
- const unnamed = reactionNames([thread.message, ...replies]).filter((id) => !authors.has(id));
2391
+ const { task } = thread.message;
2392
+ const working = task ? [...task.claim ? [task.claim.actor] : [], ...task.owner !== thread.message.by.principal ? [task.owner] : []] : [];
2393
+ const unnamed = [.../* @__PURE__ */ new Set([...reactionNames([thread.message, ...replies]), ...working])].filter((id) => !authors.has(id));
2088
2394
  const known = unnamed.length ? new Map((await board.actors().catch(() => [])).filter((a) => unnamed.includes(a.id)).map((a) => [a.id, actorName(a)])) : /* @__PURE__ */ new Map();
2089
2395
  out(formatThreads([thread.message, ...replies], known));
2090
2396
  if (!narrowed) for (const schedule of thread.schedules ?? []) out(formatSchedule(schedule, { pad: " " }));
@@ -2587,6 +2893,7 @@ async function run(command, args) {
2587
2893
  }
2588
2894
  return 0;
2589
2895
  }
2896
+ case "tasks": return tasks(args);
2590
2897
  default: {
2591
2898
  const own = app.commands[command];
2592
2899
  if (own) return own.run(args, context());
@@ -2605,6 +2912,842 @@ async function run(command, args) {
2605
2912
  }
2606
2913
  }
2607
2914
  }
2915
+ /** What `tasks` does to a task, by the word after it: any other word is a channel to list. */
2916
+ const TASK_VERBS = /* @__PURE__ */ new Set([
2917
+ "create",
2918
+ "claim",
2919
+ "run",
2920
+ "renew",
2921
+ "release",
2922
+ "complete",
2923
+ "fail",
2924
+ "block",
2925
+ "unblock",
2926
+ "reopen",
2927
+ "assign",
2928
+ "needs",
2929
+ "cancel"
2930
+ ]);
2931
+ const TASK_STATES = [
2932
+ "waiting",
2933
+ "ready",
2934
+ "claimed",
2935
+ "blocked",
2936
+ "completed",
2937
+ "failed",
2938
+ "canceled"
2939
+ ];
2940
+ /** A task's ID as you'd write it: `#812` or `812`. */
2941
+ const taskId = (value) => messageId(value, "task ID");
2942
+ /** `--wait` or `--lease` in seconds: a number and a unit, as `schedule` takes a duration. A lease is 30s to 1h. */
2943
+ function seconds(flag) {
2944
+ const value = flags[flag];
2945
+ if (value === void 0) return void 0;
2946
+ const found = /^(\d+(?:\.\d+)?)(s|m|h|d)$/.exec(value);
2947
+ if (!found) throw usage(`--${flag} takes a duration like 30s or 10m, and ${value} isn't one.`);
2948
+ const total = Number(found[1]) * {
2949
+ s: 1,
2950
+ m: 60,
2951
+ h: 3600,
2952
+ d: 86400
2953
+ }[found[2]];
2954
+ if (flag === "lease" && (total < 30 || total > 3600)) throw usage(`--lease takes 30s to 1h, and ${value} isn't in it.`);
2955
+ return total;
2956
+ }
2957
+ /**
2958
+ * `tasks create <channel> --tasks-file <path>`: the tasks a JSON file holds, as `tasks.createMany`
2959
+ * takes them, made in as many writes as the board needs. It prints each as the list shows one.
2960
+ * The whole plan goes under one key, `--idempotency-key`'s or this run's own, so one that stops
2961
+ * midway says what was made and is finished by the same command.
2962
+ */
2963
+ async function createPlan(target, text, path) {
2964
+ if (isMessageRef(target)) throw usage(`--tasks-file starts threads in a channel, and ${ref(target)} is a thread.`);
2965
+ const own = text !== void 0 ? "text" : [
2966
+ "text-file",
2967
+ "label",
2968
+ "needs",
2969
+ "for",
2970
+ "claim",
2971
+ "lease",
2972
+ "no-sync"
2973
+ ].find((name) => flags[name] !== void 0 && flags[name] !== false);
2974
+ if (own !== void 0) throw usage(`${own === "text" ? "Text" : `--${own}`} is one task's: with --tasks-file, each task in the file has its own.`);
2975
+ const board = client();
2976
+ const tasks = await planFrom(path, board);
2977
+ sentLength = Math.max(0, ...tasks.map((task) => typeof task.text === "string" ? task.text.length : 0));
2978
+ const key = flags["idempotency-key"] ?? crypto.randomUUID();
2979
+ let made;
2980
+ try {
2981
+ made = await createTasksInChunks(board, target, tasks, { id: key });
2982
+ } catch (error) {
2983
+ if (!(error instanceof TasksInChunksError)) throw error;
2984
+ const there = error.created.filter((task) => task !== void 0);
2985
+ const failed = failureOf(error);
2986
+ if (error.code === "duplicate_id") throw new Failed({
2987
+ ...failed,
2988
+ message: `${failed.message} That key made another plan.`,
2989
+ next: [{ instruction: "Leave what the key made as it was, or make new tasks under another key" }]
2990
+ });
2991
+ if (there.length === 0) throw new Failed(failed);
2992
+ throw new Failed({
2993
+ ...failed,
2994
+ details: [...failed.details ?? [], `made ${there.length} of ${tasks.length}: ${ref(there[0].id)} to ${ref(there.at(-1).id)}`],
2995
+ next: [{
2996
+ instruction: "Make the rest, under the same key: what was made stays as it is",
2997
+ argv: rerunWithout(["--idempotency-key"], "--idempotency-key", key)
2998
+ }],
2999
+ data: {
3000
+ ...failed.data,
3001
+ created: there.map((task) => task.id),
3002
+ total: tasks.length
3003
+ }
3004
+ });
3005
+ }
3006
+ if (flags.json) result({ tasks: made });
3007
+ else out(formatTasks(made.map((message) => ({
3008
+ message,
3009
+ replies: 0,
3010
+ last: null
3011
+ }))));
3012
+ return 0;
3013
+ }
3014
+ /** What a task of a `--tasks-file` takes, as `tasks.createMany` does. */
3015
+ const PLAN_KEYS = [
3016
+ "key",
3017
+ "text",
3018
+ "labels",
3019
+ "needs",
3020
+ "for",
3021
+ "noSync",
3022
+ "attachments"
3023
+ ];
3024
+ /** The help page that says what a plan holds. */
3025
+ const planHelp = () => ({
3026
+ instruction: "See what a plan takes",
3027
+ argv: [
3028
+ ...cli(),
3029
+ "tasks",
3030
+ "create",
3031
+ "--help"
3032
+ ]
3033
+ });
3034
+ /** One of a plan task's `needs`: a task that's there, by its ID as text or as a number, or `{ "key": … }` for one of the plan's own. */
3035
+ function isNeed(need) {
3036
+ if (typeof need === "string") return need.replace(/^#/, "").length > 0;
3037
+ if (typeof need === "number") return Number.isSafeInteger(need) && need >= 0;
3038
+ if (typeof need !== "object" || need === null) return false;
3039
+ const keys = Object.keys(need);
3040
+ return keys.length === 1 && keys[0] === "key" && typeof need.key === "string";
3041
+ }
3042
+ /**
3043
+ * Refuses a plan that says something a task doesn't take, before anything is sent. The board
3044
+ * drops a key it doesn't know, so a `need` for `needs` would make a task that waits for nothing,
3045
+ * without a word: here the file can say which task, and the key that was meant.
3046
+ */
3047
+ function checkPlan(plan, where) {
3048
+ for (const [at, task] of plan.entries()) {
3049
+ const unknown = Object.keys(task).find((name) => !PLAN_KEYS.includes(name));
3050
+ if (unknown !== void 0) {
3051
+ const meant = PLAN_KEYS.find((known) => known.toLowerCase() === unknown.toLowerCase()) ?? closest(unknown, PLAN_KEYS);
3052
+ throw new Failed({
3053
+ class: "usage",
3054
+ reason: "invalid_arguments",
3055
+ message: `Unknown key ${JSON.stringify(unknown)} on task ${at + 1} of ${where}.${meant ? ` Did you mean ${JSON.stringify(meant)}?` : ""}`,
3056
+ ...meant ? {} : { details: [`a task takes ${PLAN_KEYS.join(", ")}`] },
3057
+ next: [planHelp()]
3058
+ });
3059
+ }
3060
+ if (!("needs" in task)) continue;
3061
+ const needs = "[{\"key\": \"fix\"}, \"812\"]";
3062
+ if (!Array.isArray(task.needs)) throw usage(`Task ${at + 1} of ${where} has needs that aren't a list, such as ${needs}.`, { next: [planHelp()] });
3063
+ const odd = task.needs.find((need) => !isNeed(need));
3064
+ if (odd !== void 0) {
3065
+ const said = JSON.stringify(odd);
3066
+ throw usage(`Task ${at + 1} of ${where} needs ${said.length > 60 ? `${said.slice(0, 59)}…` : said}, which isn't a task's ID or {"key": "…"}.`, { next: [planHelp()] });
3067
+ }
3068
+ }
3069
+ }
3070
+ /** The tasks a `--tasks-file` holds: a JSON array, from the file or from stdin for `-`. An ID may be written `#812`, and `for` as a profile's name. */
3071
+ async function planFrom(path, board) {
3072
+ const where = path === "-" ? "stdin" : path;
3073
+ let source;
3074
+ if (path === "-") source = await io.stdin();
3075
+ else {
3076
+ const data = await io.readFile(path);
3077
+ if (!data) throw usage(`Can't read ${path}. There's no such file.`, {
3078
+ reason: "file_not_found",
3079
+ next: []
3080
+ });
3081
+ source = new TextDecoder().decode(data);
3082
+ }
3083
+ let parsed;
3084
+ try {
3085
+ parsed = JSON.parse(source);
3086
+ } catch {
3087
+ throw usage(`${where} isn't JSON.`, { next: [planHelp()] });
3088
+ }
3089
+ const shape = "A plan is a JSON array of tasks: [{\"key\": \"fix\", \"text\": \"…\"}, {\"text\": \"…\", \"needs\": [{\"key\": \"fix\"}]}].";
3090
+ if (!Array.isArray(parsed) || parsed.length === 0 || parsed.some((task) => typeof task !== "object" || task === null || Array.isArray(task))) throw usage(`${where} holds no tasks. ${shape}`, { next: [planHelp()] });
3091
+ const plan = parsed;
3092
+ checkPlan(plan, where);
3093
+ const principal = plan.some((task) => typeof task.for === "string" && !task.for.includes(":")) ? (await board.me()).principal : "";
3094
+ return plan.map((task) => ({
3095
+ ...task,
3096
+ ...Array.isArray(task.needs) ? { needs: task.needs.map((need) => typeof need === "string" ? need.replace(/^#/, "") : typeof need === "number" ? String(need) : need) } : {},
3097
+ ...typeof task.for === "string" && !task.for.includes(":") ? { for: profileActor(principal, task.for) } : {}
3098
+ }));
3099
+ }
3100
+ /** `--claim`, on `tasks create`: a flag there (`optionsFor`), where a grant's takes a value. */
3101
+ const claimFlag = () => flags.claim === true;
3102
+ /**
3103
+ * The profile this run writes as, as an actor's ID has it: `--as`'s, or the environment's
3104
+ * (`BOARD_PROFILE`), or null as yourself. `vb()`'s board is a handle that already is someone, so
3105
+ * only `--as` names one there.
3106
+ */
3107
+ function writesAs() {
3108
+ const profile = profileFlag() ?? (io.board ? null : environmentProfile());
3109
+ const name = typeof profile === "string" ? profile : profile?.name ?? null;
3110
+ return name === null ? null : name.toLowerCase();
3111
+ }
3112
+ /** `--as` as this run typed it, for a way out that claims: the claim it takes is then the one the next command, typed the same way, finds. */
3113
+ const asTyped = () => flags.as ? ["--as", flags.as] : [];
3114
+ /**
3115
+ * This run's board, and the claims it holds there as whoever it writes as. A claim's token is the
3116
+ * CLI's to keep: in a file under its config directory, by the board's URL, the task, and the
3117
+ * profile this run writes as; or for `vb()`, whose board is a handle, in memory for as long as the
3118
+ * handle lasts.
3119
+ */
3120
+ function tasksOn() {
3121
+ const profile = writesAs();
3122
+ if (io.board) return {
3123
+ board: client(),
3124
+ claims: memoryClaims(io.claimsOf ?? io.board, profile)
3125
+ };
3126
+ const { board, url } = connection();
3127
+ return {
3128
+ board,
3129
+ claims: fileClaims(async () => url ?? (await board.discovery()).url, profile)
3130
+ };
3131
+ }
3132
+ /** The actor `profile` names under `principal`: a task is assigned to one of its owner's profiles. */
3133
+ const profileActor = (principal, profile) => `${principal}+${profile.toLowerCase()}`;
3134
+ /** A write to a task that answers its root: with `--json`, the task and what happened to it. */
3135
+ function printTask(task, outcome, more = {}) {
3136
+ if (flags.json) result({
3137
+ task,
3138
+ outcome,
3139
+ ...more
3140
+ });
3141
+ else out(`${outcome} ${messageRef(task.id)}`);
3142
+ }
3143
+ /** A claim: the task, how long it's yours, and what it is. With `--json`, the task and the claim, without its token, which the CLI keeps. */
3144
+ function printClaim(task, claim, more = {}) {
3145
+ if (flags.json) result({
3146
+ task,
3147
+ claim: {
3148
+ epoch: claim.epoch,
3149
+ until: claim.until
3150
+ },
3151
+ ...more
3152
+ });
3153
+ else out(claimLine(task, claim.until));
3154
+ }
3155
+ /**
3156
+ * This run's claim on task `id`, as the board's handle acts on it, or the failure that says it
3157
+ * holds none as whoever it writes as: a claim taken as one profile isn't another's, or yours.
3158
+ */
3159
+ async function heldBy(board, claims, id) {
3160
+ const stored = await claims.get(id);
3161
+ if (!stored) throw new Failed({
3162
+ class: "conflict",
3163
+ reason: "claim_not_held",
3164
+ message: `You hold no claim on task ${ref(id)} as ${writesAs() ?? "yourself"}.`,
3165
+ next: [{
3166
+ instruction: "Claim it",
3167
+ argv: [
3168
+ ...cli(),
3169
+ "tasks",
3170
+ "claim",
3171
+ id,
3172
+ ...asTyped()
3173
+ ]
3174
+ }]
3175
+ });
3176
+ return board.tasks.held(id, stored);
3177
+ }
3178
+ /** A write a claim makes. One the board answers `claim_lost` is over: the CLI forgets it, and the failure says how to claim again. */
3179
+ async function withClaim(claims, id, write) {
3180
+ try {
3181
+ return await write();
3182
+ } catch (error) {
3183
+ if (error instanceof BoardError && error.code === "claim_lost") await claims.drop(id);
3184
+ throw error;
3185
+ }
3186
+ }
3187
+ /**
3188
+ * Claims a task for this run, by its ID or with `--ready` the oldest ready one in `target`, and
3189
+ * keeps the claim. With nothing ready it fails: `nothing_ready`, or `timeout` once `--wait` ran
3190
+ * out, as `wait` does. Stopped while it waits, it answers the exit code instead.
3191
+ */
3192
+ async function claimFor(board, claims, target) {
3193
+ const lease = seconds("lease");
3194
+ if (!flags.ready) {
3195
+ for (const given of [
3196
+ "label",
3197
+ "from",
3198
+ "wait"
3199
+ ]) if (flags[given] !== void 0) throw usage(`--${given} goes with --ready, which claims the next ready task in a channel.`);
3200
+ const claim = await board.tasks.claim(taskId(target), lease !== void 0 ? { lease } : {});
3201
+ await claims.put(claim.task.id, {
3202
+ epoch: claim.epoch,
3203
+ token: claim.token,
3204
+ until: claim.until
3205
+ });
3206
+ return claim;
3207
+ }
3208
+ if (target === void 0) throw usage("Missing the channel to claim a task in: work, or work/ for all under it.", { reason: "missing_arguments" });
3209
+ const wait = seconds("wait");
3210
+ if (io.board && !io.signal && wait !== void 0) throw usage("--wait holds every later call, as vb() runs one at a time: pass a signal.", {
3211
+ reason: "not_available",
3212
+ next: []
3213
+ });
3214
+ const controller = new AbortController();
3215
+ const stop = stopOn(controller);
3216
+ let claim;
3217
+ try {
3218
+ claim = await board.tasks.claim({
3219
+ channel: target,
3220
+ ...flags.label?.length ? { label: labelPairs(flags.label) } : {},
3221
+ ...flags.from?.length ? { from: flags.from } : {},
3222
+ ...wait !== void 0 ? { wait } : {},
3223
+ ...lease !== void 0 ? { lease } : {}
3224
+ }, { signal: controller.signal });
3225
+ } catch (error) {
3226
+ if (controller.signal.aborted) return stop.interrupted() ? 130 : 0;
3227
+ throw error;
3228
+ } finally {
3229
+ stop.release();
3230
+ }
3231
+ if (claim) {
3232
+ await claims.put(claim.task.id, {
3233
+ epoch: claim.epoch,
3234
+ token: claim.token,
3235
+ until: claim.until
3236
+ });
3237
+ return claim;
3238
+ }
3239
+ if (controller.signal.aborted) return stop.interrupted() ? 130 : 0;
3240
+ if (wait !== void 0) throw new Failed({
3241
+ class: "timeout",
3242
+ reason: "timeout",
3243
+ message: `Nothing was ready in ${target} within ${flags.wait}.`
3244
+ });
3245
+ throw new Failed({
3246
+ class: "not_found",
3247
+ reason: "nothing_ready",
3248
+ message: `Nothing is ready in ${target}.`,
3249
+ next: [{
3250
+ instruction: "Wait for one",
3251
+ argv: rerun("--wait", "10m")
3252
+ }, {
3253
+ instruction: "Or see what's there",
3254
+ argv: [
3255
+ ...cli(),
3256
+ "tasks",
3257
+ target
3258
+ ]
3259
+ }]
3260
+ });
3261
+ }
3262
+ /** `tasks`: the list, or what the word after it does to a task. */
3263
+ async function tasks(args) {
3264
+ const [verb, ...rest] = args;
3265
+ if (verb === void 0 || !TASK_VERBS.has(verb)) {
3266
+ if (rest.length > 0) {
3267
+ const guess = closest(verb, TASK_VERBS);
3268
+ throw usage(`Unknown command ${verb} for ${named()} tasks.${guess ? ` Did you mean ${guess}?` : ""}`, { reason: "unknown_command" });
3269
+ }
3270
+ const state = flags.state;
3271
+ if (state !== void 0 && state !== "open" && state !== "all" && !TASK_STATES.includes(state)) throw usage(`--state takes a task's state, open, or all, and ${state} isn't one.`);
3272
+ const board = client();
3273
+ const limit = flags.limit ? Number(flags.limit) : 50;
3274
+ const page = await board.tasks.list({
3275
+ ...verb ? { channel: verb } : {},
3276
+ ...state ? { state } : {},
3277
+ ...flags.label?.length ? { label: flags.label } : {},
3278
+ ...flags.by ? { by: flags.by.replace(/^@/, "") } : {},
3279
+ ...flags.for ? { for: profileActor((await board.me()).principal, flags.for) } : {},
3280
+ ...flags.after !== void 0 ? { after: flags.after.replace(/^#/, "") } : {},
3281
+ limit
3282
+ });
3283
+ if (page.tasks.length === 0 && verb && flags.after === void 0) {
3284
+ const channels = (await board.channels()).map((c) => c.path);
3285
+ const name = verb.replace(/\/$/, "");
3286
+ if (!channels.some((path) => path === name || path.startsWith(`${name}/`))) {
3287
+ const meant = closest(verb, TASK_VERBS);
3288
+ if (meant) throw usage(`Unknown command ${verb} for ${named()} tasks. Did you mean ${meant}?`, { reason: "unknown_command" });
3289
+ const guess = closest(verb, channels);
3290
+ throw new Failed({
3291
+ class: "not_found",
3292
+ reason: "channel_not_found",
3293
+ message: `Couldn't find channel ${verb}.${guess ? ` Did you mean ${guess}?` : ""}`,
3294
+ next: [{
3295
+ instruction: "See its channels",
3296
+ argv: [...cli(), "channels"]
3297
+ }]
3298
+ });
3299
+ }
3300
+ }
3301
+ if (flags.json) return result(page), 0;
3302
+ if (page.tasks.length === 0) {
3303
+ const which = state === void 0 || state === "open" ? "open " : state === "all" ? "" : `${state} `;
3304
+ return out(`no ${which}tasks${verb ? ` in ${verb}` : ""}`), 0;
3305
+ }
3306
+ out(formatTasks(page.tasks));
3307
+ if (page.tasks.length === limit) out(`(more not shown: ${commandLine(rerunWithout(["--after"], "--after", page.cursor))})`);
3308
+ return 0;
3309
+ }
3310
+ if (verb === "create") {
3311
+ const [target, body, extra] = rest;
3312
+ if (!target) throw usage("Missing a channel to start a task in, or a thread's ID to make one of.", { reason: "missing_arguments" });
3313
+ if (extra !== void 0) throw usage(`tasks create takes a channel and quoted text: ${extra} is one too many.`);
3314
+ if (flags["tasks-file"] !== void 0) return createPlan(target, body, flags["tasks-file"]);
3315
+ const lease = seconds("lease");
3316
+ if (lease !== void 0 && !claimFlag()) throw usage("--lease is how long a claim holds the task: pass --claim too.");
3317
+ const { board, claims } = tasksOn();
3318
+ const about = {
3319
+ ...flags.needs?.length ? { needs: flags.needs.map((id) => taskId(id)) } : {},
3320
+ ...flags.for ? { for: profileActor((await board.me()).principal, flags.for) } : {},
3321
+ ...claimFlag() ? { claim: true } : {},
3322
+ ...lease !== void 0 ? { lease } : {}
3323
+ };
3324
+ let made;
3325
+ if (isMessageRef(target)) {
3326
+ const own = body !== void 0 ? "text" : [
3327
+ "text-file",
3328
+ "label",
3329
+ "no-sync",
3330
+ "idempotency-key"
3331
+ ].find((name) => flags[name] !== void 0 && flags[name] !== false);
3332
+ if (own !== void 0) throw usage(`${ref(target)} becomes a task as it is: ${own === "text" ? "text" : `--${own}`} is for a new thread.`, { next: [{
3333
+ instruction: "Make it a task as it is",
3334
+ argv: [
3335
+ ...cli(),
3336
+ "tasks",
3337
+ "create",
3338
+ messageId(target)
3339
+ ]
3340
+ }] });
3341
+ made = await board.tasks.create({ re: messageId(target) }, about);
3342
+ } else {
3343
+ const said = await text(body);
3344
+ sentLength = said.length;
3345
+ made = await board.tasks.create(target, {
3346
+ text: said,
3347
+ ...flags.label?.length ? { labels: labelPairs(flags.label) } : {},
3348
+ ...flags["no-sync"] ? { noSync: true } : {},
3349
+ ...flags["idempotency-key"] ? { id: flags["idempotency-key"] } : {},
3350
+ ...about
3351
+ });
3352
+ }
3353
+ if (made.claim) {
3354
+ await claims.put(made.task.id, {
3355
+ epoch: made.claim.epoch,
3356
+ token: made.claim.token,
3357
+ until: made.claim.until
3358
+ });
3359
+ printClaim(made.task, made.claim, { outcome: "created" });
3360
+ } else if (flags.json) result({
3361
+ task: made.task,
3362
+ outcome: "created"
3363
+ });
3364
+ else out(messageRef(made.task.id));
3365
+ return 0;
3366
+ }
3367
+ if (verb === "claim") {
3368
+ if (rest.length > 1) throw usage(`tasks claim takes one ${flags.ready ? "channel" : "task"}: ${rest[1]} is one too many.`);
3369
+ if (!flags.ready && rest[0] === void 0) throw usage("Missing the task to claim: its ID, or --ready and a channel.", { reason: "missing_arguments" });
3370
+ const { board, claims } = tasksOn();
3371
+ const claim = await claimFor(board, claims, rest[0]);
3372
+ if (typeof claim === "number") return claim;
3373
+ printClaim(claim.task, claim);
3374
+ return 0;
3375
+ }
3376
+ if (verb === "run") {
3377
+ const dash = typed.indexOf("--");
3378
+ const command = dash === -1 ? [] : typed.slice(dash + 1);
3379
+ if (command.length === 0) throw usage("Missing the command to run: put it after --.", {
3380
+ reason: "missing_arguments",
3381
+ next: [{
3382
+ instruction: "Run a command on a task",
3383
+ argv: [
3384
+ ...cli(),
3385
+ "tasks",
3386
+ "run",
3387
+ "<ID>",
3388
+ "--",
3389
+ "<COMMAND>"
3390
+ ]
3391
+ }]
3392
+ });
3393
+ const before = rest.slice(0, rest.length - command.length);
3394
+ if (before.length > 1) throw usage(`tasks run takes one ${flags.ready ? "channel" : "task"} before --: ${before[1]} is one too many.`);
3395
+ if (!flags.ready && before[0] === void 0) throw usage("Missing the task to run it on: its ID, or --ready and a channel.", { reason: "missing_arguments" });
3396
+ if (io.board) throw usage("tasks run isn't available in-process: it runs a command on this machine.", {
3397
+ reason: "not_available",
3398
+ next: []
3399
+ });
3400
+ const { board, claims } = tasksOn();
3401
+ const claim = await claimFor(board, claims, before[0]);
3402
+ if (typeof claim === "number") return claim;
3403
+ const id = claim.task.id;
3404
+ const lease = seconds("lease");
3405
+ const ran = await runCommand(command, {
3406
+ env: {
3407
+ ...process.env,
3408
+ BOARD_TASK: id
3409
+ },
3410
+ ...flags.json ? { stdout: "stderr" } : {},
3411
+ every: (Date.parse(claim.until) - Date.now()) / 3,
3412
+ async renew() {
3413
+ try {
3414
+ const renewed = await claim.renew(lease);
3415
+ await claims.put(id, {
3416
+ epoch: renewed.epoch,
3417
+ token: renewed.token,
3418
+ until: renewed.until
3419
+ });
3420
+ return true;
3421
+ } catch (error) {
3422
+ return !(error instanceof BoardError && error.code === "claim_lost");
3423
+ }
3424
+ }
3425
+ });
3426
+ if (ran.how === "lost") {
3427
+ await claims.drop(id);
3428
+ throw new Failed({
3429
+ class: "conflict",
3430
+ reason: "claim_lost",
3431
+ message: `Lost the claim on task ${ref(id)} while the command ran, so it was stopped.`,
3432
+ next: [{
3433
+ instruction: "See where the task stands",
3434
+ argv: [
3435
+ ...cli(),
3436
+ "read",
3437
+ id
3438
+ ]
3439
+ }]
3440
+ });
3441
+ }
3442
+ if (ran.how === "unstarted") {
3443
+ await claim.release().catch(() => {});
3444
+ await claims.drop(id);
3445
+ throw new Failed({
3446
+ class: "not_found",
3447
+ reason: "command_not_found",
3448
+ message: `Couldn't run ${command[0]}. ${sentence(ran.why)}`,
3449
+ details: [`Task ${ref(id)} was released.`]
3450
+ });
3451
+ }
3452
+ if (ran.how === "interrupted") {
3453
+ await withClaim(claims, id, () => claim.release());
3454
+ await claims.drop(id);
3455
+ return ran.code;
3456
+ }
3457
+ const settled = ran.code === 0 ? await withClaim(claims, id, () => claim.complete(flags.result)) : await withClaim(claims, id, () => claim.fail(ran.signal ? `killed by ${ran.signal}` : `exited ${ran.code}`));
3458
+ await claims.drop(id);
3459
+ printTask(settled, ran.code === 0 ? "completed" : "failed", ran.code === 0 ? {} : { code: ran.code });
3460
+ return ran.code;
3461
+ }
3462
+ const id = taskId(rest[0]);
3463
+ const one = (extra, takes) => {
3464
+ if (extra !== void 0) throw usage(`tasks ${verb} takes ${takes}: ${extra} is one too many.`);
3465
+ };
3466
+ const reason = (what) => {
3467
+ const given = rest[1]?.trim();
3468
+ if (!given) throw usage(`Missing ${what}, in a line.`, { reason: "missing_arguments" });
3469
+ return given;
3470
+ };
3471
+ const { board, claims } = tasksOn();
3472
+ switch (verb) {
3473
+ case "renew": {
3474
+ one(rest[1], "one task");
3475
+ const lease = seconds("lease");
3476
+ const held = await heldBy(board, claims, id);
3477
+ const claim = await withClaim(claims, id, () => held.renew(lease));
3478
+ await claims.put(id, {
3479
+ epoch: claim.epoch,
3480
+ token: claim.token,
3481
+ until: claim.until
3482
+ });
3483
+ printClaim(claim.task, claim);
3484
+ return 0;
3485
+ }
3486
+ case "release": {
3487
+ one(rest[1], "one task");
3488
+ const held = await heldBy(board, claims, id);
3489
+ const task = await withClaim(claims, id, () => held.release());
3490
+ await claims.drop(id);
3491
+ printTask(task, "released");
3492
+ return 0;
3493
+ }
3494
+ case "complete": {
3495
+ one(rest[2], "a task and its result, quoted");
3496
+ const held = await heldBy(board, claims, id);
3497
+ const task = await withClaim(claims, id, () => held.complete(rest[1]));
3498
+ await claims.drop(id);
3499
+ printTask(task, "completed");
3500
+ return 0;
3501
+ }
3502
+ case "fail": {
3503
+ one(rest[2], "a task and a reason, quoted");
3504
+ const why = reason("why it failed");
3505
+ const held = await heldBy(board, claims, id);
3506
+ const task = await withClaim(claims, id, () => held.fail(why));
3507
+ await claims.drop(id);
3508
+ printTask(task, "failed");
3509
+ return 0;
3510
+ }
3511
+ case "block": {
3512
+ one(rest[2], "a task and a reason, quoted");
3513
+ const why = reason("what you need from a person");
3514
+ const hold = flags.kind !== void 0 ? { kind: flags.kind } : {};
3515
+ const stored = await claims.get(id);
3516
+ const task = stored ? await withClaim(claims, id, () => board.tasks.held(id, stored).block(why, hold)) : await board.tasks.block(id, why, hold);
3517
+ await claims.drop(id);
3518
+ printTask(task, "blocked");
3519
+ return 0;
3520
+ }
3521
+ case "unblock":
3522
+ case "reopen": {
3523
+ one(rest[1], "one task");
3524
+ const from = verb === "unblock" ? "blocked" : "failed";
3525
+ const was = (await board.thread(id)).message.task?.state;
3526
+ const task = verb === "unblock" ? await board.tasks.unblock(id) : await board.tasks.reopen(id);
3527
+ if (was === from) printTask(task, verb === "unblock" ? "unblocked" : "reopened");
3528
+ else if (flags.json) result({
3529
+ task,
3530
+ outcome: "unchanged"
3531
+ });
3532
+ else out(`${messageRef(id)} wasn't ${from}`);
3533
+ return 0;
3534
+ }
3535
+ case "assign": {
3536
+ one(rest[2], "a task and a profile");
3537
+ const profile = rest[1];
3538
+ if (flags.pool && profile !== void 0) throw usage(`A profile keeps ${ref(id)} for it, and --pool for no one: pass one of them.`);
3539
+ if (!flags.pool && profile === void 0) throw usage("Missing the profile to assign it to, such as fixer, or --pool for anyone.", { reason: "missing_arguments" });
3540
+ const owner = profile === void 0 ? null : (await board.thread(id)).message.task?.owner;
3541
+ const task = await board.tasks.assign(id, profile === void 0 ? null : profileActor(owner ?? (await board.me()).principal, profile));
3542
+ if (flags.json) result({
3543
+ task,
3544
+ outcome: profile === void 0 ? "unassigned" : "assigned"
3545
+ });
3546
+ else out(profile === void 0 ? `unassigned ${messageRef(id)}` : `assigned ${messageRef(id)} to ${profile.toLowerCase()}`);
3547
+ return 0;
3548
+ }
3549
+ case "needs": {
3550
+ const needs = rest.slice(1).map((need) => taskId(need));
3551
+ if (flags.none && needs.length > 0) throw usage(`Tasks are what ${ref(id)} waits for, and --none for nothing: pass one of them.`);
3552
+ if (!flags.none && needs.length === 0) throw usage("Missing the tasks it waits for now, by ID, or --none for nothing.", { reason: "missing_arguments" });
3553
+ const task = await board.tasks.needs(id, needs);
3554
+ const now = task.task?.needs ?? [];
3555
+ if (flags.json) result({
3556
+ task,
3557
+ outcome: "set"
3558
+ });
3559
+ else out(`${messageRef(id)} needs ${now.length ? now.map((need) => ref(need)).join(" ") : "nothing"}`);
3560
+ return 0;
3561
+ }
3562
+ default: {
3563
+ one(rest[2], "a task and a reason, quoted");
3564
+ const task = await board.tasks.cancel(id, reason("why"));
3565
+ await claims.drop(id);
3566
+ printTask(task, "canceled");
3567
+ return 0;
3568
+ }
3569
+ }
3570
+ }
3571
+ /** How a board's own word about a task reads from here: the headline, and the way on. Null for any other code. */
3572
+ function taskFailure(code, status) {
3573
+ const { command, args } = current;
3574
+ const named = command === "tasks" && args[0] !== void 0 && TASK_VERBS.has(args[0]) && args[1] !== void 0 && isMessageRef(args[1]) ? messageId(args[1]) : void 0;
3575
+ const read = (instruction) => named === void 0 ? [] : [{
3576
+ instruction,
3577
+ argv: [
3578
+ ...cli(),
3579
+ "read",
3580
+ named
3581
+ ]
3582
+ }];
3583
+ const also = (instruction, ...words) => named === void 0 ? [] : [{
3584
+ instruction,
3585
+ argv: [
3586
+ ...cli(),
3587
+ "tasks",
3588
+ words[0],
3589
+ named,
3590
+ ...words.slice(1)
3591
+ ]
3592
+ }];
3593
+ switch (code) {
3594
+ case "task_claimed": return {
3595
+ class: "conflict",
3596
+ message: `Can't ${doing()}. Someone holds it.`,
3597
+ next: read("See who holds it, and until when")
3598
+ };
3599
+ case "task_assigned": return {
3600
+ class: "conflict",
3601
+ message: `Can't ${doing()}. It's assigned to another profile.`,
3602
+ next: [...read("See whom it's for"), ...also("Or, as its owner, return it to the pool", "assign", "--pool")]
3603
+ };
3604
+ case "task_waiting": return {
3605
+ class: "conflict",
3606
+ message: `Can't ${doing()}. It waits for other tasks.`,
3607
+ next: read("See what it waits for")
3608
+ };
3609
+ case "task_blocked": return {
3610
+ class: "conflict",
3611
+ message: `Can't ${doing()}. It's held for a person.`,
3612
+ next: [...read("See what it's held for"), ...also("Or, as its owner, lift the hold", "unblock")]
3613
+ };
3614
+ case "task_finished": return {
3615
+ class: "conflict",
3616
+ message: `Can't ${doing()}. It's finished.`,
3617
+ next: read("See how it ended")
3618
+ };
3619
+ case "claim_lost": return {
3620
+ class: "conflict",
3621
+ message: `Lost the claim on ${named === void 0 ? "the task" : `task ${ref(named)}`}. Its lease ran out, or the task moved on.`,
3622
+ next: [...read("See where it stands"), ...also("Or claim it again", "claim", ...asTyped())]
3623
+ };
3624
+ case "task_not_owned": return {
3625
+ class: "permission",
3626
+ message: `You can't ${doing()}. It's someone else's.`,
3627
+ next: read("See whose it is")
3628
+ };
3629
+ case "not_a_task": return {
3630
+ class: "not_found",
3631
+ message: `${named === void 0 ? "That" : ref(named)} isn't a task.`,
3632
+ next: also("Make it one", "create"),
3633
+ whole: true
3634
+ };
3635
+ case "already_a_task": return {
3636
+ class: "conflict",
3637
+ message: `${named === void 0 ? "That" : ref(named)} is a task already.`,
3638
+ next: read("See it"),
3639
+ whole: true
3640
+ };
3641
+ case "invalid_from": return {
3642
+ class: "usage",
3643
+ message: `Can't ${doing()}. --from takes an owner's ID: several can share a handle.`,
3644
+ next: [{
3645
+ instruction: "See everyone's IDs",
3646
+ argv: [...cli(), "actors"]
3647
+ }]
3648
+ };
3649
+ case "invalid_needs":
3650
+ if (flags["tasks-file"] !== void 0) return {
3651
+ class: "usage",
3652
+ message: `Can't ${doing()}. A task's needs are tasks you can read, or keys of the plan's own.`,
3653
+ next: [{
3654
+ instruction: "See the tasks there are",
3655
+ argv: [
3656
+ ...cli(),
3657
+ "tasks",
3658
+ "--state",
3659
+ "all"
3660
+ ]
3661
+ }]
3662
+ };
3663
+ if (command === "tasks" && args[0] === "needs") return {
3664
+ class: "usage",
3665
+ message: `Can't ${doing()}. It waits for tasks you can read, and none that waits for it.`,
3666
+ next: [...read("See what it waits for now"), {
3667
+ instruction: "Or see the tasks there are",
3668
+ argv: [
3669
+ ...cli(),
3670
+ "tasks",
3671
+ "--state",
3672
+ "all"
3673
+ ]
3674
+ }]
3675
+ };
3676
+ return {
3677
+ class: "usage",
3678
+ message: `Can't ${doing()}. --needs takes tasks you can read.`,
3679
+ next: [{
3680
+ instruction: "See the tasks there are",
3681
+ argv: [
3682
+ ...cli(),
3683
+ "tasks",
3684
+ "--state",
3685
+ "all"
3686
+ ]
3687
+ }]
3688
+ };
3689
+ case "claim_too_wide": return {
3690
+ class: "limit",
3691
+ message: `Can't ${doing()}. That's too many channels and owners.`,
3692
+ next: [{ instruction: "Name fewer owners with --from, or a smaller subtree" }]
3693
+ };
3694
+ case "channel_tree_too_large": return {
3695
+ class: "limit",
3696
+ message: `Can't ${doing()}. That's too many channels.`,
3697
+ next: [{ instruction: "Name a channel, or a smaller subtree" }]
3698
+ };
3699
+ case "no_tasks": return status === 501 ? {
3700
+ class: "platform",
3701
+ message: `Can't ${doing()}. This board keeps no tasks.`,
3702
+ next: []
3703
+ } : null;
3704
+ case "reserved_label": return {
3705
+ class: "usage",
3706
+ message: `Can't ${doing()}. Labels under board. are the board's own.`,
3707
+ next: stateCommand()
3708
+ };
3709
+ default: return null;
3710
+ }
3711
+ }
3712
+ /**
3713
+ * The `tasks` command for the change a write under `board.task` was after, from what this run was
3714
+ * given: a label write names the state it wanted, and a labeled post a task it meant to start.
3715
+ */
3716
+ function stateCommand() {
3717
+ const { command, args } = current;
3718
+ const tasksDo = (instruction, ...words) => ({
3719
+ instruction,
3720
+ argv: [
3721
+ ...cli(),
3722
+ "tasks",
3723
+ ...words
3724
+ ]
3725
+ });
3726
+ if (command === "label" && args[0] !== void 0) {
3727
+ const id = messageId(args[0]);
3728
+ const wanted = args.slice(1).find((pair) => pair.startsWith("board.task="))?.slice(11);
3729
+ if (wanted === void 0) return flags.unset?.includes("board.task") ? [tasksDo("Cancel the task", "cancel", id, "<REASON>")] : [];
3730
+ switch (wanted) {
3731
+ case "ready": return [tasksDo("Make the thread a task", "create", id), tasksDo("Or lift a hold on one", "unblock", id)];
3732
+ case "waiting": return [tasksDo("Make it a task that waits for another", "create", id, "--needs", "<ID>")];
3733
+ case "claimed": return [tasksDo("Claim it", "claim", id)];
3734
+ case "completed": return [tasksDo("Complete it, with the claim you hold", "complete", id)];
3735
+ case "failed": return [tasksDo("Fail it, with the claim you hold", "fail", id, "<REASON>")];
3736
+ case "blocked": return [tasksDo("Hold it for a person", "block", id, "<REASON>")];
3737
+ case "canceled": return [tasksDo("Cancel it", "cancel", id, "<REASON>")];
3738
+ default: return [{
3739
+ instruction: "See what changes a task",
3740
+ argv: [
3741
+ ...cli(),
3742
+ "tasks",
3743
+ "--help"
3744
+ ]
3745
+ }];
3746
+ }
3747
+ }
3748
+ if (flags.label?.some((pair) => pair === "board.task" || pair.startsWith("board.task=")) && command === "post" && args[0] !== void 0 && !isMessageRef(args[0])) return [tasksDo("Start it as a task", "create", args[0], "<TEXT>")];
3749
+ return [];
3750
+ }
2608
3751
  /** Words for a command this CLI names otherwise, and the command they mean. */
2609
3752
  const OTHER_NAMES = {
2610
3753
  search: {
@@ -2967,7 +4110,7 @@ function stopped(reason) {
2967
4110
  "revoke",
2968
4111
  "cancel",
2969
4112
  "join"
2970
- ].includes(sub ?? "");
4113
+ ].includes(sub ?? "") || current.command === "tasks" && TASK_VERBS.has(sub ?? "");
2971
4114
  return new Failed({
2972
4115
  class: timedOut ? "timeout" : "canceled",
2973
4116
  reason: timedOut ? "timeout" : "canceled",