@vercel/board 0.45.1 → 0.47.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 (88) hide show
  1. package/dist/{access-3udXjJAg.mjs → access-C06pIr0M.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-Dkyg-oo0.mjs} +3 -3
  5. package/dist/{auth-aiOVE82-.mjs → auth-B9-wXQ-x.mjs} +29 -9
  6. package/dist/{auth-BG_whr9_.d.mts → auth-li3lKwJG.d.mts} +1 -1
  7. package/dist/{backend-D6yTo8Un.d.mts → backend-i_esjwUS.d.mts} +144 -5
  8. package/dist/backend-local.d.mts +1 -1
  9. package/dist/backend-local.mjs +1 -1
  10. package/dist/{chat-provider-V2jnjVLq.d.mts → chat-provider-BWBGZOZY.d.mts} +4 -2
  11. package/dist/{chat-provider-BvNqOQFL.mjs → chat-provider-CD7jskh7.mjs} +7 -4
  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 +46 -15
  17. package/dist/{commands-DewS14_P.d.mts → commands-CJsOA-hf.d.mts} +60 -0
  18. package/dist/{commands-CqdnjUkm.mjs → commands-Dk6_cHLS.mjs} +325 -0
  19. package/dist/{conformance-BInS4_6b.mjs → conformance-CDP8y2Zm.mjs} +1063 -6
  20. package/dist/conformance.d.mts +6 -5
  21. package/dist/conformance.mjs +1 -1
  22. package/dist/{engine-XVBt02Bl.mjs → engine-j2VeNuKG.mjs} +51 -50
  23. package/dist/{errors-ZazTZh-s.mjs → errors-QhkdzI-o.mjs} +176 -9
  24. package/dist/{events-D17RndlV.mjs → events-MOcxGpOQ.mjs} +2 -2
  25. package/dist/{exports-DCxecX15.mjs → exports-CEqS-IPP.mjs} +1417 -84
  26. package/dist/exports-CF9rKCXd.d.mts +44 -0
  27. package/dist/{external-DfhN7lKK.mjs → external-BuVTXT1R.mjs} +7 -3
  28. package/dist/{index-Djmr4GzQ.d.mts → index-ttfx1TZ6.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-8YAhl_h3.mjs +2 -0
  36. package/dist/{inspect-CHsgnf_5.mjs → inspect-vOSrW_g6.mjs} +322 -50
  37. package/dist/{local-DE9vmanM.mjs → local-0ajWOVhN.mjs} +1673 -98
  38. package/dist/{main-CF1Me3jg.mjs → main-B8Zkd4Pm.mjs} +1282 -58
  39. package/dist/{memory-DyEL0fvN.mjs → memory-CMm-Fk_A.mjs} +2 -2
  40. package/dist/{mentions-DfZGp3B-.mjs → mentions-CnWt9Z5b.mjs} +34 -1
  41. package/dist/{middleware-BHHKHA9q.mjs → middleware-CT6vMNUc.mjs} +2 -2
  42. package/dist/{provider-BC9mPYVh.d.mts → provider-Bc3xI90K.d.mts} +199 -6
  43. package/dist/{routes-CkUetTO2.mjs → routes-ABXf3CKq.mjs} +261 -8
  44. package/dist/{routes-zm4TXKCC.d.mts → routes-CjA6Mp4D.d.mts} +610 -6
  45. package/dist/{schemas-BhZaystC.mjs → schemas-7VFdomFB.mjs} +34 -1
  46. package/dist/serve-BepKXDH3.mjs +285 -0
  47. package/dist/{server-Bmz0zqYM.mjs → server-4rQL3xuH.mjs} +41 -22
  48. package/dist/{serving-BLVRrJ7P.mjs → serving-BNdiReQT.mjs} +1 -1
  49. package/dist/{sql-CyVcjw8x.mjs → sql-IEbO5vXs.mjs} +174 -9
  50. package/dist/{sqlite-Con-8duk.mjs → sqlite-CVG8XKHm.mjs} +2 -2
  51. package/dist/{sqlite-db-BdzxtUOV.mjs → sqlite-db-BJjPQYx4.mjs} +1 -1
  52. package/dist/sync-chat-sdk.d.mts +16 -2
  53. package/dist/sync-chat-sdk.mjs +2 -2
  54. package/dist/sync-github.d.mts +16 -2
  55. package/dist/sync-github.mjs +3 -3
  56. package/dist/sync-linear.d.mts +17 -3
  57. package/dist/sync-linear.mjs +2 -2
  58. package/dist/sync-slack.d.mts +17 -3
  59. package/dist/sync-slack.mjs +107 -15
  60. package/dist/sync.d.mts +2 -2
  61. package/dist/sync.mjs +2 -2
  62. package/dist/{origin-BbwhnKrg.mjs → task-batch-BZXm6kOE.mjs} +83 -8
  63. package/dist/{tokens-BErYXuHZ.mjs → tokens-BCp4EWTQ.mjs} +2 -2
  64. package/docs/01-board/01-mounting.md +8 -5
  65. package/docs/01-board/03-identity.md +43 -23
  66. package/docs/01-board/04-messages.md +3 -2
  67. package/docs/01-board/06-watchers.md +3 -3
  68. package/docs/01-board/07-schedules.md +2 -2
  69. package/docs/01-board/08-middleware.md +7 -0
  70. package/docs/01-board/09-access.md +6 -4
  71. package/docs/01-board/10-local.md +4 -1
  72. package/docs/01-board/11-tasks.md +348 -0
  73. package/docs/02-sync/01-overview.md +4 -5
  74. package/docs/02-sync/02-functions.md +2 -2
  75. package/docs/02-sync/03-slack.md +8 -5
  76. package/docs/02-sync/06-providers.md +8 -0
  77. package/docs/03-guides/02-inspector.md +83 -10
  78. package/docs/03-guides/06-sandboxed-agents.md +7 -5
  79. package/docs/03-guides/07-build-a-ui.md +210 -0
  80. package/docs/03-guides/08-tailnet.md +123 -0
  81. package/docs/04-reference/01-cli.md +272 -23
  82. package/docs/04-reference/02-board.md +287 -7
  83. package/docs/04-reference/03-http.md +208 -13
  84. package/docs/04-reference/05-conformance.md +10 -7
  85. package/package.json +1 -1
  86. package/dist/exports-Gspe1eEq.d.mts +0 -4
  87. package/dist/inspect-C8U3A4jQ.mjs +0 -2
  88. package/dist/serve-CEMvl0EH.mjs +0 -181
@@ -1,19 +1,21 @@
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-QhkdzI-o.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-CT6vMNUc.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 { a as replaceMentions, n as isEmail, t as extractMentions } from "./mentions-CnWt9Z5b.mjs";
7
+ import { c as withMentions, g as VERSION } from "./task-batch-BZXm6kOE.mjs";
8
+ import { r as PERMISSIONS } from "./access-C06pIr0M.mjs";
9
+ import { i as isBoardName, n as createTasksInChunks, s as isApiMessageId, t as TasksInChunksError } from "./exports-CEqS-IPP.mjs";
10
+ import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-Dk6_cHLS.mjs";
11
+ 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-4rQL3xuH.mjs";
12
+ import { t as conformance } from "./conformance-CDP8y2Zm.mjs";
12
13
  import { n as displayText } from "./bots-CLKKMgYf.mjs";
13
14
  import { spawn } from "node:child_process";
14
- import { readFile, stat, writeFile } from "node:fs/promises";
15
+ import { createHash, randomUUID } from "node:crypto";
16
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
15
17
  import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
16
- import { homedir } from "node:os";
18
+ import { constants, homedir } from "node:os";
17
19
  import { basename, dirname, join } from "node:path";
18
20
  import { parseArgs } from "node:util";
19
21
  //#region src/cli/grants.ts
@@ -314,15 +316,22 @@ function reactions(message, names) {
314
316
  function reactionNames(messages) {
315
317
  return [...new Set(messages.flatMap((m) => Object.values(m.reactions).flatMap((actors) => actors.slice(0, 3))))];
316
318
  }
319
+ /** Each author's handle by ID, and those of `more`: who a mention shows as. */
320
+ const handlesOf = (messages, more = /* @__PURE__ */ new Map()) => new Map([...more, ...messages.flatMap((m) => m.author ? [[m.by.actor, m.author.handle]] : [])]);
321
+ /** The actors a thread's texts mention by ID, for looking up the ones who didn't write in it. */
322
+ function mentionedIn(messages) {
323
+ return [...new Set(messages.flatMap((m) => m.deleted ? [] : extractMentions(m.text).flatMap((token) => token.kind === "actor" && !isEmail(token.actor) ? [token.actor] : [])))];
324
+ }
317
325
  /** An actor's display name from `/actors`, the way a message's author shows: `claude via julian`. */
318
326
  const actorName = (actor) => shownName(actor);
319
327
  /**
320
328
  * A message's text as a terminal shows it: a bot's in its readable form, and each block as one
321
329
  * line, its schema and its data, where its fence was. A message that is only a block is that line.
322
330
  */
323
- function shownText(message) {
324
- const text = displayText(message.text, message.by.actor);
325
- if (!message.blocks?.length || text !== message.text) return text;
331
+ function shownText(message, handles = /* @__PURE__ */ new Map()) {
332
+ const said = replaceMentions(message.text, (token) => token.kind === "actor" && handles.has(token.actor) ? `@${handles.get(token.actor)}` : null);
333
+ const text = displayText(said, message.by.actor);
334
+ if (!message.blocks?.length || text !== said) return text;
326
335
  let out = "";
327
336
  let at = 0;
328
337
  for (const found of findBlocks(text)) {
@@ -350,7 +359,8 @@ function embed(link, pad) {
350
359
  function formatMessage(message, options = {}) {
351
360
  const pad = options.reply ? " " : " ";
352
361
  const head = `${options.reply ? " ↳ " : ""}#${message.id} ${authorName(message)} · ${ago(message.createdAt)}${message.editedAt ? " (edited)" : ""}${message.schedule ? ` · scheduled ${message.schedule.id}` : ""}${labels(message)}`;
353
- const body = message.deleted ? `${pad}(message removed)` : indent(shownText(message), pad);
362
+ const body = message.deleted ? `${pad}(message removed)` : indent(shownText(message, options.handles), pad);
363
+ const task = message.task ? [`${pad}task ${taskState(message, message.task, options.names ?? /* @__PURE__ */ new Map(), options.now ?? Date.now())}`] : [];
354
364
  const files = (message.attachments ?? []).map((a) => `${pad}file ${a.name} · ${a.type} · ${fileSize(a.size)} · ${a.id}`);
355
365
  const links = message.deleted ? [] : (message.links ?? []).flatMap((link) => embed(link, pad));
356
366
  const reacted = reactions(message, options.names ?? /* @__PURE__ */ new Map());
@@ -358,15 +368,82 @@ function formatMessage(message, options = {}) {
358
368
  return [
359
369
  head,
360
370
  body,
371
+ ...task,
361
372
  ...files,
362
373
  ...links,
363
374
  ...reacted ? [`${pad}${reacted}`] : [],
364
375
  ...undelivered
365
376
  ].join("\n");
366
377
  }
378
+ /** The first line of what a task came to, or of why it's held or ended: the rest is in its thread. */
379
+ const noteLine = (text, max = 60) => {
380
+ const [line = ""] = text.trim().split(/\r?\n/);
381
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
382
+ };
383
+ /** The profile an actor ID names (`vercel:user:u_abc+fixer` is `fixer`), or the ID itself when it names none. */
384
+ const profileOf = (actor) => actor.includes("+") ? actor.slice(actor.lastIndexOf("+") + 1) : actor;
385
+ /** How long a lease has left, as a duration flag would say it, to the minute from a minute up: `15m`, `45s`. */
386
+ function leaseLeft(until, now = Date.now()) {
387
+ const ms = Date.parse(until) - now;
388
+ if (ms <= 0) return "0s";
389
+ return span(ms < 6e4 ? Math.ceil(ms / 1e3) * 1e3 : Math.round(ms / 6e4) * 6e4);
390
+ }
391
+ /**
392
+ * A task's state as `read` says it under its root: who holds it and for how long, what it's held
393
+ * for or how it ended, then what it waits for, whom it's for, and whose it is when that isn't its
394
+ * root's author. `names` are the display names the reader knows, by actor ID.
395
+ */
396
+ function taskState(message, task, names, now) {
397
+ const named = (id) => names.get(id) ?? id;
398
+ const parts = [];
399
+ if (task.state === "claimed" && task.claim) {
400
+ const left = Date.parse(task.claim.until) - now;
401
+ parts.push(`claimed by ${named(task.claim.actor)}`, left > 0 ? `${leaseLeft(task.claim.until, now)} left` : "its lease ran out");
402
+ } else if (task.state === "blocked" && task.blocked) parts.push("blocked", ...task.blocked.kind ? [task.blocked.kind] : [], noteLine(task.blocked.reason));
403
+ else if (task.state === "completed") parts.push("completed", ...task.result ? [noteLine(task.result)] : []);
404
+ else if (task.state === "failed" || task.state === "canceled") parts.push(task.state, ...task.reason ? [noteLine(task.reason)] : []);
405
+ else parts.push(task.state);
406
+ if (task.needs.length) parts.push(`needs ${task.needs.map((id) => `#${id}`).join(" ")}`);
407
+ if (task.for !== null) parts.push(`for ${profileOf(task.for)}`);
408
+ if (task.owner !== message.by.principal) parts.push(`owner ${named(task.owner)}`);
409
+ return parts.join(" · ");
410
+ }
411
+ /** A claim as the CLI says it: the task, how long it's yours, and what it is. */
412
+ const claimLine = (task, until, now = Date.now()) => `#${task.id} yours for ${leaseLeft(until, now)} ${firstLine(task, 52)}`;
413
+ /**
414
+ * What a task's row says after its text: how it ended or what it's held for, in the `room` the row
415
+ * has left, or its own labels, whole, and what it waits for.
416
+ */
417
+ function taskNote(message, task, room) {
418
+ if (task.state === "completed" && task.result) return noteLine(task.result, room);
419
+ if ((task.state === "failed" || task.state === "canceled") && task.reason) return noteLine(task.reason, room);
420
+ if (task.state === "blocked" && task.blocked) return noteLine(task.blocked.reason, room);
421
+ 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(" ");
422
+ }
423
+ /** The widest a task's state is (`completed`), and how wide its first line's column is at least and at most. */
424
+ const STATE_WIDTH = 9;
425
+ const TASK_TEXT_MIN = 30;
426
+ const TASK_TEXT_MAX = 40;
427
+ /** The least a row leaves for how a task ended, however long its ID. */
428
+ const TASK_NOTE_MIN = 20;
429
+ /**
430
+ * Tasks, one a row: its ID, its state, its first line, and what's notable about it. The state's
431
+ * column is as wide as any state, and the text's at least 30, so one list lines up with the next.
432
+ * What a person wrote about how it ended is cut to fit 80 columns: the rest is in its thread.
433
+ */
434
+ function formatTasks(tasks) {
435
+ const rows = tasks.map(({ message }) => [
436
+ `#${message.id}`,
437
+ (message.task?.state ?? "").padEnd(STATE_WIDTH),
438
+ firstLine(message, TASK_TEXT_MAX).padEnd(TASK_TEXT_MIN)
439
+ ]);
440
+ const room = Math.max(TASK_NOTE_MIN, 80 - rows.reduce((widest, row) => Math.max(widest, row.join(" ").length), 0) - 2);
441
+ return table(rows.map((row, at) => [...row, tasks[at].message.task ? taskNote(tasks[at].message, tasks[at].message.task, room) : ""]));
442
+ }
367
443
  /** Threads in order, each root followed by its replies. */
368
- function formatThreads(messages, known = /* @__PURE__ */ new Map()) {
444
+ function formatThreads(messages, known = /* @__PURE__ */ new Map(), mentioned = /* @__PURE__ */ new Map()) {
369
445
  const names = new Map([...known, ...messages.map((m) => [m.by.actor, authorName(m)])]);
446
+ const handles = handlesOf(messages, mentioned);
370
447
  const byRoot = /* @__PURE__ */ new Map();
371
448
  const roots = [];
372
449
  const orphans = [];
@@ -374,25 +451,30 @@ function formatThreads(messages, known = /* @__PURE__ */ new Map()) {
374
451
  else (byRoot.get(message.re) ?? byRoot.set(message.re, []).get(message.re)).push(message);
375
452
  const rootIds = new Set(roots.map((r) => r.id));
376
453
  for (const [root, replies] of byRoot) if (!rootIds.has(root)) orphans.push(...replies);
377
- const blocks = roots.map((root) => [formatMessage(root, { names }), ...(byRoot.get(root.id) ?? []).map((r) => formatMessage(r, {
454
+ const blocks = roots.map((root) => [formatMessage(root, {
455
+ names,
456
+ handles
457
+ }), ...(byRoot.get(root.id) ?? []).map((r) => formatMessage(r, {
378
458
  reply: true,
379
- names
459
+ names,
460
+ handles
380
461
  }))].join("\n"));
381
462
  for (const reply of orphans) blocks.push(`(in thread #${reply.re})\n${formatMessage(reply, {
382
463
  reply: true,
383
- names
464
+ names,
465
+ handles
384
466
  })}`);
385
467
  return blocks.join("\n\n");
386
468
  }
387
- /** A root's first line, cut to fit 80 columns under its header. */
388
- function firstLine(message) {
469
+ /** A root's first line, cut to `max` characters: 74 fits 80 columns under its header. */
470
+ function firstLine(message, max = 74, handles) {
389
471
  if (message.deleted) return "(message removed)";
390
- const text = shownText(message).trim();
472
+ const text = shownText(message, handles).trim();
391
473
  const files = message.attachments?.length ?? 0;
392
474
  if (!text) return files ? `(${files} ${files === 1 ? "file" : "files"})` : "(no text)";
393
475
  const [line = "", ...rest] = text.split(/\r?\n/);
394
476
  const shown = rest.length ? `${line.trimEnd()} …` : line;
395
- return shown.length > 74 ? `${line.slice(0, 73)}…` : shown;
477
+ return shown.length > max ? `${line.slice(0, max - 1)}…` : shown;
396
478
  }
397
479
  /**
398
480
  * One block per thread, for `read <channel>`: the root's header and first line,
@@ -400,6 +482,7 @@ function firstLine(message) {
400
482
  */
401
483
  function formatThreadSummaries(threads, options = {}) {
402
484
  const now = options.now ?? Date.now();
485
+ const handles = handlesOf(threads.flatMap(({ message, last }) => last ? [message, last] : [message]), options.handles);
403
486
  return threads.map(({ message, replies, last }) => {
404
487
  const where = options.channel ? `${message.channel} ` : "";
405
488
  const head = `#${message.id} ${where}${authorName(message)} · ${ago(message.createdAt, now)}${labels(message)}`;
@@ -407,7 +490,7 @@ function formatThreadSummaries(threads, options = {}) {
407
490
  const counted = Object.entries(message.reactions).filter(([, actors]) => actors.length > 0).map(([emoji, actors]) => `${displayEmoji(emoji)} ${actors.length}`).join(" ");
408
491
  return [
409
492
  head,
410
- ` ${firstLine(message)}`,
493
+ ` ${firstLine(message, 74, handles)}`,
411
494
  ...counted ? [` ${counted}`] : [],
412
495
  ` ${activity}`
413
496
  ].join("\n");
@@ -533,9 +616,40 @@ function formatEvent(event) {
533
616
  return `#${message.id} ${where} labels ${[...set, ...unset].join(" ")}${event.actor ? ` by ${event.actor.name}` : ""}`;
534
617
  }
535
618
  case "message.sync_failed": return `#${message.id} ${where} ✗ didn't reach ${event.payload.target}: ${event.payload.error}`;
619
+ case "task.created":
620
+ case "task.assigned":
621
+ case "task.needs_changed":
622
+ case "task.ready":
623
+ case "task.claimed":
624
+ case "task.renewed":
625
+ case "task.released":
626
+ case "task.expired":
627
+ case "task.completed":
628
+ case "task.failed":
629
+ case "task.blocked":
630
+ case "task.unblocked":
631
+ case "task.canceled":
632
+ case "task.reopened": return `#${message.id} ${where} task ${taskEvent(event)}`;
536
633
  default: return `#${event.cursor} ${event.type}`;
537
634
  }
538
635
  }
636
+ /** What happened to a task, after `task`: `claimed by claude via ada`, `completed by claude via ada · tests pass`. */
637
+ function taskEvent(event) {
638
+ const by = event.actor ? ` by ${actorName(event.actor)}` : "";
639
+ const more = (...parts) => parts.filter((part) => !!part).map((part) => ` · ${part}`).join("");
640
+ switch (event.type) {
641
+ 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)}`;
642
+ case "task.assigned": return event.payload.for !== null ? `assigned to ${profileOf(event.payload.for)}${by}` : `unassigned${by}`;
643
+ case "task.needs_changed": return `needs ${event.payload.needs.length ? event.payload.needs.map((id) => `#${id}`).join(" ") : "nothing"}${by}`;
644
+ case "task.ready": return "ready";
645
+ case "task.expired": return "lease ran out";
646
+ case "task.completed": return `completed${by}${more(event.payload.result === null ? null : noteLine(event.payload.result))}`;
647
+ case "task.failed": return `failed${by}${more(noteLine(event.payload.reason))}`;
648
+ case "task.blocked": return `blocked${by}${more(event.payload.kind, noteLine(event.payload.reason))}`;
649
+ case "task.canceled": return `canceled${by}${more(noteLine(event.payload.reason))}`;
650
+ default: return `${event.type.slice(5)}${by}`;
651
+ }
652
+ }
539
653
  /**
540
654
  * Where a thread is synced, for `vb sync <id>`: a row a target, its sync key and where it is, then
541
655
  * the link to the message's copy there, or why it didn't reach it.
@@ -624,6 +738,169 @@ function formatSchema(schema) {
624
738
  return `${[schema.id, schema.description].filter(Boolean).join(" ")}\n\n${definition}`;
625
739
  }
626
740
  //#endregion
741
+ //#region src/cli/claims.ts
742
+ /** A claim whose lease ended this long ago is no one's to settle: its file goes when another is written. */
743
+ const DEAD_MS = 864e5;
744
+ /** The claims directory: `~/.config/board/claims`, or under `XDG_CONFIG_HOME`, as the CLI's tokens are. */
745
+ const claimsDir = () => join(configDir(), "claims");
746
+ /**
747
+ * The file one claim lives in: named for its board, task, and profile together, hashed, so a name
748
+ * says nothing of any of them, and never holds a token.
749
+ */
750
+ const fileOf = (board, task, profile) => join(claimsDir(), `${createHash("sha256").update(JSON.stringify([
751
+ board,
752
+ task,
753
+ profile
754
+ ])).digest("hex").slice(0, 32)}.json`);
755
+ async function read(file) {
756
+ try {
757
+ const stored = JSON.parse(await readFile(file, "utf8"));
758
+ if (typeof stored.epoch !== "number" || typeof stored.token !== "string" || typeof stored.until !== "string") return null;
759
+ return stored;
760
+ } catch {
761
+ return null;
762
+ }
763
+ }
764
+ /** Removes the claims whose leases ended long ago: a process that was killed leaves its file behind. */
765
+ async function prune(now) {
766
+ for (const name of await readdir(claimsDir()).catch(() => [])) {
767
+ if (!name.endsWith(".json")) {
768
+ const file = join(claimsDir(), name);
769
+ const info = await stat(file).catch(() => null);
770
+ if (info && now - info.mtimeMs > DEAD_MS) await unlink(file).catch(() => {});
771
+ continue;
772
+ }
773
+ const file = join(claimsDir(), name);
774
+ const stored = await read(file);
775
+ if (stored && now - Date.parse(stored.until) > DEAD_MS) await unlink(file).catch(() => {});
776
+ }
777
+ }
778
+ /**
779
+ * Claims in files, one per board, task, and profile: only this user reads them (the directory is
780
+ * 0700, each file 0600), and each is written whole or not at all. `board` is the board's own URL,
781
+ * asked for only when a claim is read or written; `profile` is the profile this run writes as, as
782
+ * an actor's ID has it, or null as yourself. A claim is its actor's: a run as another profile is
783
+ * another actor, and holds none of it.
784
+ */
785
+ function fileClaims(board, profile) {
786
+ let key = null;
787
+ const at = async (task) => fileOf(await (key ??= board()), task, profile);
788
+ return {
789
+ async get(task) {
790
+ const stored = await read(await at(task));
791
+ if (!stored || stored.board !== await key || stored.task !== task || stored.profile !== profile) return null;
792
+ return {
793
+ epoch: stored.epoch,
794
+ token: stored.token,
795
+ until: stored.until
796
+ };
797
+ },
798
+ async put(task, claim) {
799
+ const file = await at(task);
800
+ await mkdir(claimsDir(), {
801
+ recursive: true,
802
+ mode: 448
803
+ });
804
+ const stored = {
805
+ board: await key,
806
+ task,
807
+ profile,
808
+ ...claim
809
+ };
810
+ const partial = `${file}.${process.pid}.${randomUUID()}.tmp`;
811
+ await writeFile(partial, JSON.stringify(stored), { mode: 384 });
812
+ await rename(partial, file).catch(async (error) => {
813
+ await unlink(partial).catch(() => {});
814
+ throw error;
815
+ });
816
+ await prune(Date.now()).catch(() => {});
817
+ },
818
+ async drop(task) {
819
+ await unlink(await at(task)).catch(() => {});
820
+ }
821
+ };
822
+ }
823
+ /** A handle's claims, kept in this process: what `vb()` holds, where the board is a handle and no file is the caller's. */
824
+ const held = /* @__PURE__ */ new WeakMap();
825
+ /** Claims kept in memory, for as long as the process and the handle last: one per task and profile, as the files are. */
826
+ function memoryClaims(board, profile) {
827
+ const claims = held.get(board) ?? held.set(board, /* @__PURE__ */ new Map()).get(board);
828
+ const at = (task) => JSON.stringify([task, profile]);
829
+ return {
830
+ get: async (task) => claims.get(at(task)) ?? null,
831
+ put: async (task, claim) => void claims.set(at(task), claim),
832
+ drop: async (task) => void claims.delete(at(task))
833
+ };
834
+ }
835
+ //#endregion
836
+ //#region src/cli/run.ts
837
+ /** A claim is never renewed more often than this, however short its lease. */
838
+ const RENEW_MIN_MS = 1e4;
839
+ /**
840
+ * Runs `command` with this process's terminal, and calls `renew` every `every` milliseconds (at
841
+ * least 10 seconds apart) while it runs. With `stdout: 'stderr'`, what the command prints on its
842
+ * 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
843
+ * doesn't, the command is stopped. Ctrl-C stops it too. It answers once the command has ended and
844
+ * no renewal is still on its way.
845
+ */
846
+ function runCommand(command, options) {
847
+ return new Promise((resolve) => {
848
+ const child = spawn(command[0], command.slice(1), {
849
+ stdio: [
850
+ "inherit",
851
+ options.stdout === "stderr" ? 2 : "inherit",
852
+ "inherit"
853
+ ],
854
+ env: options.env
855
+ });
856
+ let interrupted = null;
857
+ let lost = false;
858
+ let ended = false;
859
+ let renewing = null;
860
+ const interrupt = () => {
861
+ interrupted = "SIGINT";
862
+ if (!process.stdin.isTTY) child.kill("SIGINT");
863
+ };
864
+ const terminate = () => {
865
+ interrupted = "SIGTERM";
866
+ child.kill("SIGTERM");
867
+ };
868
+ process.on("SIGINT", interrupt);
869
+ process.on("SIGTERM", terminate);
870
+ const timer = setInterval(() => {
871
+ if (renewing || lost) return;
872
+ renewing = options.renew().then((held) => {
873
+ if (held) return;
874
+ lost = true;
875
+ child.kill("SIGTERM");
876
+ }).finally(() => {
877
+ renewing = null;
878
+ });
879
+ }, Math.max(RENEW_MIN_MS, options.every));
880
+ const end = async (ran) => {
881
+ if (ended) return;
882
+ ended = true;
883
+ clearInterval(timer);
884
+ process.off("SIGINT", interrupt);
885
+ process.off("SIGTERM", terminate);
886
+ await renewing;
887
+ resolve(ran.how === "unstarted" ? ran : lost ? { how: "lost" } : interrupted ? {
888
+ how: "interrupted",
889
+ code: 128 + constants.signals[interrupted]
890
+ } : ran);
891
+ };
892
+ child.once("error", (error) => void end({
893
+ how: "unstarted",
894
+ why: error.code === "ENOENT" ? "there's no such command" : error.message
895
+ }));
896
+ child.once("exit", (code, signal) => void end({
897
+ how: "exited",
898
+ code: code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0),
899
+ signal
900
+ }));
901
+ });
902
+ }
903
+ //#endregion
627
904
  //#region src/cli/hooks.ts
628
905
  /**
629
906
  * Where each agent keeps hooks, and which of its events run ours. Claude Code
@@ -1072,11 +1349,24 @@ function commandWord(argv) {
1072
1349
  });
1073
1350
  return canonical(positionals[0]);
1074
1351
  }
1075
- const parseAll = (args) => parseArgs({
1076
- args,
1077
- allowPositionals: true,
1078
- options: OPTIONS
1079
- });
1352
+ /**
1353
+ * What the parser accepts for `word`'s command: every option, with the command's own definition
1354
+ * where it has one. `--claim` takes a value on `grants` and none on `tasks`, and each command's
1355
+ * data says which. The command is found before this applies, so one that's its command's own way
1356
+ * goes after the command's name.
1357
+ */
1358
+ function optionsFor(word) {
1359
+ const command = [...commands, ...Object.values(app.commands).map((own) => own.spec)].find((known) => known.name === word);
1360
+ if (!command) return OPTIONS;
1361
+ const own = [command, ...command.subcommands ?? []].flatMap((c) => c.options);
1362
+ const table = { ...OPTIONS };
1363
+ for (const { name, type, short, multiple } of own) table[name] = {
1364
+ type,
1365
+ ...short ? { short } : {},
1366
+ ...multiple ? { multiple } : {}
1367
+ };
1368
+ return table;
1369
+ }
1080
1370
  let app = {
1081
1371
  name: "board",
1082
1372
  commands: {}
@@ -1127,11 +1417,16 @@ function parse(argv) {
1127
1417
  const removed = removedCommand(word ?? "");
1128
1418
  if (removed) throw removed;
1129
1419
  try {
1130
- const parsed = parseAll(markAttachmentId(args));
1420
+ const table = optionsFor(word);
1421
+ const parsed = parseArgs({
1422
+ args: markAttachmentId(args),
1423
+ allowPositionals: true,
1424
+ options: table
1425
+ });
1131
1426
  ordered = parseArgs({
1132
1427
  args: markAttachmentId(args),
1133
1428
  allowPositionals: true,
1134
- options: OPTIONS,
1429
+ options: table,
1135
1430
  tokens: true
1136
1431
  }).tokens.flatMap((token) => token.kind === "option" ? [{
1137
1432
  name: token.name,
@@ -1145,6 +1440,7 @@ function parse(argv) {
1145
1440
  const known = specOf(word) && new Set(optionsOf(word));
1146
1441
  const foreign = known && ordered.find((option) => !known.has(option.name));
1147
1442
  if (foreign) throw foreignOption(foreign.name, word);
1443
+ if (canonical(positionals[0]) !== word) throw misplaced(args, word);
1148
1444
  }
1149
1445
  /** An option `word` doesn't take: what to do instead, where there's something better to say than that. */
1150
1446
  function foreignOption(name, word) {
@@ -1176,6 +1472,13 @@ function foreignOption(name, word) {
1176
1472
  }]
1177
1473
  });
1178
1474
  }
1475
+ /** An option `word`'s command reads its own way, written before the command: it goes after it. */
1476
+ function misplaced(args, word) {
1477
+ const at = args.indexOf(word ?? "");
1478
+ const before = (at === -1 ? args : args.slice(0, at)).filter((arg) => arg.startsWith("-"));
1479
+ const own = optionsFor(word);
1480
+ 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" });
1481
+ }
1179
1482
  /** What the parser rejected, as misuse: an unknown option (with the likeliest one meant), or an option without its value. */
1180
1483
  function parseFailure(error, argv, word) {
1181
1484
  const option = error.message.match(/--[a-z][\w-]*/)?.[0] ?? /'(-[^' ,]+)/.exec(error.message)?.[1];
@@ -1544,6 +1847,16 @@ function doing() {
1544
1847
  case "channels": return a === "create" ? `create ${b ?? "the channel"}` : "list channels";
1545
1848
  case "schedules":
1546
1849
  case "actors": return `list ${command}`;
1850
+ case "tasks": {
1851
+ if (a === void 0 || !TASK_VERBS.has(a)) return a === void 0 ? "list tasks" : `list tasks in ${a}`;
1852
+ const one = b === void 0 ? "a task" : `task ${ref(b)}`;
1853
+ if (a === "claim" || a === "run") return flags.ready ? `claim a task in ${b ?? "a channel"}` : `claim ${one}`;
1854
+ if (a === "create" && flags["tasks-file"] !== void 0) return `create tasks in ${b ?? "a channel"}`;
1855
+ if (a === "create") return b !== void 0 && isMessageRef(b) ? `make ${ref(b)} a task` : `create a task in ${b ?? "a channel"}`;
1856
+ if (a === "renew") return `renew the claim on ${one}`;
1857
+ if (a === "needs") return `change what ${one} needs`;
1858
+ return `${a} ${one}`;
1859
+ }
1547
1860
  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
1861
  case "schemas": return a === "create" ? `register schema ${b ?? ""}`.trimEnd() : a === "inspect" ? `read schema ${b ?? ""}`.trimEnd() : "list schemas";
1549
1862
  case "sources": return b === void 0 ? "list sources" : `${b} ${c ?? "it"} on ${a}`;
@@ -1579,6 +1892,7 @@ function missing() {
1579
1892
  "schedule"
1580
1893
  ].includes(command) && isMessageRef(a)) return `message ${ref(a)}`;
1581
1894
  if (command === "schedule" && a === "cancel" && b !== void 0) return `schedule ${b}`;
1895
+ if (command === "tasks" && TASK_VERBS.has(a) && b !== void 0 && isMessageRef(b)) return `message ${ref(b)}`;
1582
1896
  if (command === "grants" && (a === "revoke" || a === "update") && b !== void 0) return `grant ${b}`;
1583
1897
  if (command === "schemas" && a === "inspect" && b !== void 0) return `schema ${b}`;
1584
1898
  if (command === "download") return `attachment ${a}`;
@@ -1686,6 +2000,11 @@ function failureOf(error) {
1686
2000
  data: said
1687
2001
  });
1688
2002
  const specific = (fallback) => /^[a-z]+(_[a-z]+)+$/.test(code) && code !== "invalid_request" && code !== "remote_error" ? code : fallback;
2003
+ const about = taskFailure(code, status);
2004
+ if (about) return {
2005
+ ...theirs(about.class, code, about.message, about.next),
2006
+ ...about.whole ? { details: [] } : {}
2007
+ };
1689
2008
  if (status === 400 && code === "invalid_block" && flags.schema !== void 0 && parseSchemaId(flags.schema)) return theirs("usage", code, `Can't ${doing()}.`, [{
1690
2009
  instruction: `See what ${flags.schema} holds`,
1691
2010
  argv: [
@@ -1700,11 +2019,11 @@ function failureOf(error) {
1700
2019
  argv: [...cli(), "schemas"]
1701
2020
  }]);
1702
2021
  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" }]),
2022
+ ...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
2023
  details: []
1705
2024
  };
1706
2025
  if (status === 400) return theirs("usage", specific("invalid_arguments"), `Can't ${doing()}.`);
1707
- if (status === 401) return theirs("auth", "login_required", "The board didn't accept your credentials.", process.env.BOARD_TOKEN && reached && !vercelBoard(reached) ? [{ instruction: "Pass a token it accepts in BOARD_TOKEN, or unset it" }] : [{
2026
+ if (status === 401) return theirs("auth", "login_required", "The board didn't accept your credentials.", process.env.BOARD_TOKEN && (reached && !vercelBoard(reached) || credentialSource() === "BOARD_TOKEN") ? [{ instruction: "Pass a token it accepts in BOARD_TOKEN, or unset it" }] : [{
1708
2027
  instruction: "Log in again",
1709
2028
  argv: ["vercel", "login"]
1710
2029
  }]);
@@ -1923,21 +2242,60 @@ function hookAgents(names) {
1923
2242
  for (const name of names) if (!known.includes(name)) throw usage(`Unknown agent ${name}. The agents are ${known.join(", ")}.`);
1924
2243
  return names.length ? names : known;
1925
2244
  }
1926
- /** A post or reply: its ID, or with `--json`, the message. */
1927
- function printMessage(message) {
1928
- if (flags.json) result({
1929
- message,
1930
- outcome: "posted"
2245
+ /** Says what a write that went through had to say: in its JSON result with `--json`, on stderr otherwise. */
2246
+ function warn(warning) {
2247
+ if (flags.json) warnings.push(warning);
2248
+ else if (app.onWarning) app.onWarning(warning);
2249
+ else io.error(`${terminalText(`warning: ${warning.message}`)}\n`);
2250
+ }
2251
+ /**
2252
+ * What became of the `@handle`s a write's text typed: a line for each one that's now a mention, with
2253
+ * who it mentions, and a warning for each that names no one or several, which is still text. With
2254
+ * `--json` the lines are the result's `mentions`.
2255
+ */
2256
+ function sayMentions(mentions) {
2257
+ for (const { written, actor, candidates } of mentions ?? []) if (actor) {
2258
+ if (!flags.json) out(`mentioned ${actor.name} @${actor.handle}`);
2259
+ } else if (candidates.length === 0) warn({
2260
+ reason: "unknown_mention",
2261
+ message: `${written} names no one here: it stays text, and mentions no one.`
1931
2262
  });
1932
- else out(messageRef(message.id));
2263
+ else {
2264
+ const handles = candidates.map(({ handle }) => handle.toLowerCase());
2265
+ warn({
2266
+ reason: "ambiguous_mention",
2267
+ message: `${written} mentions no one here, and stays text: write ${candidates.map(({ id, handle }) => `@${handle}`.toLowerCase() !== written.toLowerCase() && handles.filter((other) => other === handle.toLowerCase()).length === 1 ? `@${handle}` : `@[${id}]`).join(" or ")}.`
2268
+ });
2269
+ }
2270
+ }
2271
+ /** A post or reply: its ID, or with `--json`, the message. Then what became of its mentions. */
2272
+ function printMessage(written) {
2273
+ const { mentions, ...message } = written;
2274
+ if (flags.json) {
2275
+ sayMentions(mentions);
2276
+ result({
2277
+ message,
2278
+ outcome: "posted",
2279
+ ...mentions ? { mentions } : {}
2280
+ });
2281
+ } else {
2282
+ out(messageRef(message.id));
2283
+ sayMentions(mentions);
2284
+ }
1933
2285
  }
1934
2286
  /** A write that answers nothing but that it went through: with `--json`, which message, and what happened to it. */
1935
- function printDone(id, outcome) {
1936
- if (flags.json) result({
1937
- message: { id },
1938
- outcome
1939
- });
1940
- else out(`${outcome} ${messageRef(id)}`);
2287
+ function printDone(id, outcome, mentions) {
2288
+ if (flags.json) {
2289
+ sayMentions(mentions);
2290
+ result({
2291
+ message: { id },
2292
+ outcome,
2293
+ ...mentions ? { mentions } : {}
2294
+ });
2295
+ } else {
2296
+ out(`${outcome} ${messageRef(id)}`);
2297
+ sayMentions(mentions);
2298
+ }
1941
2299
  }
1942
2300
  /** Best-effort: the URL is printed either way. */
1943
2301
  /** `url`, when it's an http or https URL as `new URL` reads it: the only kind the CLI opens, so a board can't hand the opener a flag or another scheme. */
@@ -2084,9 +2442,16 @@ async function run(command, args) {
2084
2442
  replies
2085
2443
  }), 0;
2086
2444
  const authors = new Set([thread.message, ...replies].map((m) => m.by.actor));
2087
- const unnamed = reactionNames([thread.message, ...replies]).filter((id) => !authors.has(id));
2088
- 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
- out(formatThreads([thread.message, ...replies], known));
2445
+ const { task } = thread.message;
2446
+ const working = task ? [...task.claim ? [task.claim.actor] : [], ...task.owner !== thread.message.by.principal ? [task.owner] : []] : [];
2447
+ const unnamed = [.../* @__PURE__ */ new Set([
2448
+ ...reactionNames([thread.message, ...replies]),
2449
+ ...working,
2450
+ ...mentionedIn([thread.message, ...replies])
2451
+ ])].filter((id) => !authors.has(id));
2452
+ const listed = unnamed.length ? (await board.actors().catch(() => [])).filter((a) => unnamed.includes(a.id)) : [];
2453
+ const known = new Map(listed.map((a) => [a.id, actorName(a)]));
2454
+ out(formatThreads([thread.message, ...replies], known, new Map(listed.map((a) => [a.id, a.handle]))));
2090
2455
  if (!narrowed) for (const schedule of thread.schedules ?? []) out(formatSchedule(schedule, { pad: " " }));
2091
2456
  return 0;
2092
2457
  }
@@ -2118,7 +2483,16 @@ async function run(command, args) {
2118
2483
  if (flags.json) return result(page), 0;
2119
2484
  const count = `${page.threads.length} ${page.threads.length === 1 ? "thread" : "threads"}`;
2120
2485
  out(`${target ?? "all channels"} · ${count} · cursor ${page.cursor}${page.threads.length ? "\n" : ""}`);
2121
- if (page.threads.length) out(formatThreadSummaries(page.threads, { channel: !target || target.endsWith("/") }));
2486
+ if (page.threads.length) {
2487
+ const roots = page.threads.map(({ message }) => message);
2488
+ const wrote = new Set(page.threads.flatMap(({ message, last }) => last ? [message.by.actor, last.by.actor] : [message.by.actor]));
2489
+ const unnamed = mentionedIn(roots).filter((id) => !wrote.has(id));
2490
+ const handles = new Map(unnamed.length ? (await client().actors().catch(() => [])).filter((a) => unnamed.includes(a.id)).map((a) => [a.id, a.handle]) : []);
2491
+ out(formatThreadSummaries(page.threads, {
2492
+ channel: !target || target.endsWith("/"),
2493
+ handles
2494
+ }));
2495
+ }
2122
2496
  out(`\nnew since then: ${commandLine(rerunWithout(["--after"], "--after", String(page.cursor)))}`);
2123
2497
  return 0;
2124
2498
  }
@@ -2192,7 +2566,7 @@ async function run(command, args) {
2192
2566
  const said = await content(body, { optional: !!flags.attach?.length });
2193
2567
  const files = await attachments(board);
2194
2568
  const where = isMessageRef(target) ? { re: messageId(target) } : target;
2195
- const schedule = await board.schedule(where, {
2569
+ const { mentions, ...made } = await board.schedule(where, {
2196
2570
  text: said,
2197
2571
  ...files.length ? { attachments: files } : {},
2198
2572
  ...flags.label?.length ? { labels: labelPairs(flags.label) } : {},
@@ -2204,11 +2578,17 @@ async function run(command, args) {
2204
2578
  ...flags.for ? { for: flags.for } : {},
2205
2579
  ...times !== void 0 ? { times } : {}
2206
2580
  });
2207
- if (flags.json) result({
2208
- schedule,
2209
- outcome: "scheduled"
2210
- });
2211
- else out(formatSchedule(schedule));
2581
+ if (flags.json) {
2582
+ sayMentions(mentions);
2583
+ result({
2584
+ schedule: made,
2585
+ outcome: "scheduled",
2586
+ ...mentions ? { mentions } : {}
2587
+ });
2588
+ } else {
2589
+ out(formatSchedule(made));
2590
+ sayMentions(mentions);
2591
+ }
2212
2592
  return 0;
2213
2593
  }
2214
2594
  case "grants": {
@@ -2401,8 +2781,8 @@ async function run(command, args) {
2401
2781
  case "hook": return 0;
2402
2782
  case "edit": {
2403
2783
  const id = messageId(args[0]);
2404
- await client().edit(id, await content(args[1]), ifRevision());
2405
- printDone(id, "edited");
2784
+ const { mentions } = await client().edit(id, await content(args[1]), ifRevision());
2785
+ printDone(id, "edited", mentions);
2406
2786
  return 0;
2407
2787
  }
2408
2788
  case "delete": {
@@ -2587,6 +2967,7 @@ async function run(command, args) {
2587
2967
  }
2588
2968
  return 0;
2589
2969
  }
2970
+ case "tasks": return tasks(args);
2590
2971
  default: {
2591
2972
  const own = app.commands[command];
2592
2973
  if (own) return own.run(args, context());
@@ -2605,6 +2986,849 @@ async function run(command, args) {
2605
2986
  }
2606
2987
  }
2607
2988
  }
2989
+ /** What `tasks` does to a task, by the word after it: any other word is a channel to list. */
2990
+ const TASK_VERBS = /* @__PURE__ */ new Set([
2991
+ "create",
2992
+ "claim",
2993
+ "run",
2994
+ "renew",
2995
+ "release",
2996
+ "complete",
2997
+ "fail",
2998
+ "block",
2999
+ "unblock",
3000
+ "reopen",
3001
+ "assign",
3002
+ "needs",
3003
+ "cancel"
3004
+ ]);
3005
+ const TASK_STATES = [
3006
+ "waiting",
3007
+ "ready",
3008
+ "claimed",
3009
+ "blocked",
3010
+ "completed",
3011
+ "failed",
3012
+ "canceled"
3013
+ ];
3014
+ /** A task's ID as you'd write it: `#812` or `812`. */
3015
+ const taskId = (value) => messageId(value, "task ID");
3016
+ /** `--wait` or `--lease` in seconds: a number and a unit, as `schedule` takes a duration. A lease is 30s to 1h. */
3017
+ function seconds(flag) {
3018
+ const value = flags[flag];
3019
+ if (value === void 0) return void 0;
3020
+ const found = /^(\d+(?:\.\d+)?)(s|m|h|d)$/.exec(value);
3021
+ if (!found) throw usage(`--${flag} takes a duration like 30s or 10m, and ${value} isn't one.`);
3022
+ const total = Number(found[1]) * {
3023
+ s: 1,
3024
+ m: 60,
3025
+ h: 3600,
3026
+ d: 86400
3027
+ }[found[2]];
3028
+ if (flag === "lease" && (total < 30 || total > 3600)) throw usage(`--lease takes 30s to 1h, and ${value} isn't in it.`);
3029
+ return total;
3030
+ }
3031
+ /**
3032
+ * `tasks create <channel> --tasks-file <path>`: the tasks a JSON file holds, as `tasks.createMany`
3033
+ * takes them, made in as many writes as the board needs. It prints each as the list shows one.
3034
+ * The whole plan goes under one key, `--idempotency-key`'s or this run's own, so one that stops
3035
+ * midway says what was made and is finished by the same command.
3036
+ */
3037
+ async function createPlan(target, text, path) {
3038
+ if (isMessageRef(target)) throw usage(`--tasks-file starts threads in a channel, and ${ref(target)} is a thread.`);
3039
+ const own = text !== void 0 ? "text" : [
3040
+ "text-file",
3041
+ "label",
3042
+ "needs",
3043
+ "for",
3044
+ "claim",
3045
+ "lease",
3046
+ "no-sync"
3047
+ ].find((name) => flags[name] !== void 0 && flags[name] !== false);
3048
+ 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.`);
3049
+ const board = client();
3050
+ const tasks = await planFrom(path, board);
3051
+ sentLength = Math.max(0, ...tasks.map((task) => typeof task.text === "string" ? task.text.length : 0));
3052
+ const key = flags["idempotency-key"] ?? crypto.randomUUID();
3053
+ let made;
3054
+ try {
3055
+ made = await createTasksInChunks(board, target, tasks, { id: key });
3056
+ } catch (error) {
3057
+ if (!(error instanceof TasksInChunksError)) throw error;
3058
+ const there = error.created.filter((task) => task !== void 0);
3059
+ const failed = failureOf(error);
3060
+ if (error.code === "duplicate_id") throw new Failed({
3061
+ ...failed,
3062
+ message: `${failed.message} That key made another plan.`,
3063
+ next: [{ instruction: "Leave what the key made as it was, or make new tasks under another key" }]
3064
+ });
3065
+ if (there.length === 0) throw new Failed(failed);
3066
+ throw new Failed({
3067
+ ...failed,
3068
+ details: [...failed.details ?? [], `made ${there.length} of ${tasks.length}: ${ref(there[0].id)} to ${ref(there.at(-1).id)}`],
3069
+ next: [{
3070
+ instruction: "Make the rest, under the same key: what was made stays as it is",
3071
+ argv: rerunWithout(["--idempotency-key"], "--idempotency-key", key)
3072
+ }],
3073
+ data: {
3074
+ ...failed.data,
3075
+ created: there.map((task) => task.id),
3076
+ total: tasks.length
3077
+ }
3078
+ });
3079
+ }
3080
+ if (flags.json) result({ tasks: made });
3081
+ else out(formatTasks(made.map((message) => ({
3082
+ message,
3083
+ replies: 0,
3084
+ last: null
3085
+ }))));
3086
+ return 0;
3087
+ }
3088
+ /** What a task of a `--tasks-file` takes, as `tasks.createMany` does. */
3089
+ const PLAN_KEYS = [
3090
+ "key",
3091
+ "text",
3092
+ "labels",
3093
+ "needs",
3094
+ "for",
3095
+ "noSync",
3096
+ "attachments"
3097
+ ];
3098
+ /** The help page that says what a plan holds. */
3099
+ const planHelp = () => ({
3100
+ instruction: "See what a plan takes",
3101
+ argv: [
3102
+ ...cli(),
3103
+ "tasks",
3104
+ "create",
3105
+ "--help"
3106
+ ]
3107
+ });
3108
+ /** 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. */
3109
+ function isNeed(need) {
3110
+ if (typeof need === "string") return need.replace(/^#/, "").length > 0;
3111
+ if (typeof need === "number") return Number.isSafeInteger(need) && need >= 0;
3112
+ if (typeof need !== "object" || need === null) return false;
3113
+ const keys = Object.keys(need);
3114
+ return keys.length === 1 && keys[0] === "key" && typeof need.key === "string";
3115
+ }
3116
+ /**
3117
+ * Refuses a plan that says something a task doesn't take, before anything is sent. The board
3118
+ * drops a key it doesn't know, so a `need` for `needs` would make a task that waits for nothing,
3119
+ * without a word: here the file can say which task, and the key that was meant.
3120
+ */
3121
+ function checkPlan(plan, where) {
3122
+ for (const [at, task] of plan.entries()) {
3123
+ const unknown = Object.keys(task).find((name) => !PLAN_KEYS.includes(name));
3124
+ if (unknown !== void 0) {
3125
+ const meant = PLAN_KEYS.find((known) => known.toLowerCase() === unknown.toLowerCase()) ?? closest(unknown, PLAN_KEYS);
3126
+ throw new Failed({
3127
+ class: "usage",
3128
+ reason: "invalid_arguments",
3129
+ message: `Unknown key ${JSON.stringify(unknown)} on task ${at + 1} of ${where}.${meant ? ` Did you mean ${JSON.stringify(meant)}?` : ""}`,
3130
+ ...meant ? {} : { details: [`a task takes ${PLAN_KEYS.join(", ")}`] },
3131
+ next: [planHelp()]
3132
+ });
3133
+ }
3134
+ if (!("needs" in task)) continue;
3135
+ const needs = "[{\"key\": \"fix\"}, \"812\"]";
3136
+ if (!Array.isArray(task.needs)) throw usage(`Task ${at + 1} of ${where} has needs that aren't a list, such as ${needs}.`, { next: [planHelp()] });
3137
+ const odd = task.needs.find((need) => !isNeed(need));
3138
+ if (odd !== void 0) {
3139
+ const said = JSON.stringify(odd);
3140
+ 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()] });
3141
+ }
3142
+ }
3143
+ }
3144
+ /** 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. */
3145
+ async function planFrom(path, board) {
3146
+ const where = path === "-" ? "stdin" : path;
3147
+ let source;
3148
+ if (path === "-") source = await io.stdin();
3149
+ else {
3150
+ const data = await io.readFile(path);
3151
+ if (!data) throw usage(`Can't read ${path}. There's no such file.`, {
3152
+ reason: "file_not_found",
3153
+ next: []
3154
+ });
3155
+ source = new TextDecoder().decode(data);
3156
+ }
3157
+ let parsed;
3158
+ try {
3159
+ parsed = JSON.parse(source);
3160
+ } catch {
3161
+ throw usage(`${where} isn't JSON.`, { next: [planHelp()] });
3162
+ }
3163
+ const shape = "A plan is a JSON array of tasks: [{\"key\": \"fix\", \"text\": \"…\"}, {\"text\": \"…\", \"needs\": [{\"key\": \"fix\"}]}].";
3164
+ 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()] });
3165
+ const plan = parsed;
3166
+ checkPlan(plan, where);
3167
+ const principal = plan.some((task) => typeof task.for === "string" && !task.for.includes(":")) ? (await board.me()).principal : "";
3168
+ return plan.map((task) => ({
3169
+ ...task,
3170
+ ...Array.isArray(task.needs) ? { needs: task.needs.map((need) => typeof need === "string" ? need.replace(/^#/, "") : typeof need === "number" ? String(need) : need) } : {},
3171
+ ...typeof task.for === "string" && !task.for.includes(":") ? { for: profileActor(principal, task.for) } : {}
3172
+ }));
3173
+ }
3174
+ /** `--claim`, on `tasks create`: a flag there (`optionsFor`), where a grant's takes a value. */
3175
+ const claimFlag = () => flags.claim === true;
3176
+ /**
3177
+ * The profile this run writes as, as an actor's ID has it: `--as`'s, or the environment's
3178
+ * (`BOARD_PROFILE`), or null as yourself. `vb()`'s board is a handle that already is someone, so
3179
+ * only `--as` names one there.
3180
+ */
3181
+ function writesAs() {
3182
+ const profile = profileFlag() ?? (io.board ? null : environmentProfile());
3183
+ const name = typeof profile === "string" ? profile : profile?.name ?? null;
3184
+ return name === null ? null : name.toLowerCase();
3185
+ }
3186
+ /** `--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. */
3187
+ const asTyped = () => flags.as ? ["--as", flags.as] : [];
3188
+ /**
3189
+ * This run's board, and the claims it holds there as whoever it writes as. A claim's token is the
3190
+ * CLI's to keep: in a file under its config directory, by the board's URL, the task, and the
3191
+ * profile this run writes as; or for `vb()`, whose board is a handle, in memory for as long as the
3192
+ * handle lasts.
3193
+ */
3194
+ function tasksOn() {
3195
+ const profile = writesAs();
3196
+ if (io.board) return {
3197
+ board: client(),
3198
+ claims: memoryClaims(io.claimsOf ?? io.board, profile)
3199
+ };
3200
+ const { board, url } = connection();
3201
+ return {
3202
+ board,
3203
+ claims: fileClaims(async () => url ?? (await board.discovery()).url, profile)
3204
+ };
3205
+ }
3206
+ /** The actor `profile` names under `principal`: a task is assigned to one of its owner's profiles. */
3207
+ const profileActor = (principal, profile) => `${principal}+${profile.toLowerCase()}`;
3208
+ /** A write to a task that answers its root: with `--json`, the task and what happened to it. */
3209
+ function printTask(task, outcome, more = {}) {
3210
+ if (flags.json) result({
3211
+ task,
3212
+ outcome,
3213
+ ...more
3214
+ });
3215
+ else out(`${outcome} ${messageRef(task.id)}`);
3216
+ }
3217
+ /** 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. */
3218
+ function printClaim(task, claim, more = {}) {
3219
+ if (flags.json) result({
3220
+ task,
3221
+ claim: {
3222
+ epoch: claim.epoch,
3223
+ until: claim.until
3224
+ },
3225
+ ...more
3226
+ });
3227
+ else out(claimLine(task, claim.until));
3228
+ }
3229
+ /**
3230
+ * This run's claim on task `id`, as the board's handle acts on it, or the failure that says it
3231
+ * holds none as whoever it writes as: a claim taken as one profile isn't another's, or yours.
3232
+ */
3233
+ async function heldBy(board, claims, id) {
3234
+ const stored = await claims.get(id);
3235
+ if (!stored) throw new Failed({
3236
+ class: "conflict",
3237
+ reason: "claim_not_held",
3238
+ message: `You hold no claim on task ${ref(id)} as ${writesAs() ?? "yourself"}.`,
3239
+ next: [{
3240
+ instruction: "Claim it",
3241
+ argv: [
3242
+ ...cli(),
3243
+ "tasks",
3244
+ "claim",
3245
+ id,
3246
+ ...asTyped()
3247
+ ]
3248
+ }]
3249
+ });
3250
+ return board.tasks.held(id, stored);
3251
+ }
3252
+ /** 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. */
3253
+ async function withClaim(claims, id, write) {
3254
+ try {
3255
+ return await write();
3256
+ } catch (error) {
3257
+ if (error instanceof BoardError && error.code === "claim_lost") await claims.drop(id);
3258
+ throw error;
3259
+ }
3260
+ }
3261
+ /**
3262
+ * Claims a task for this run, by its ID or with `--ready` the oldest ready one in `target`, and
3263
+ * keeps the claim. With nothing ready it fails: `nothing_ready`, or `timeout` once `--wait` ran
3264
+ * out, as `wait` does. Stopped while it waits, it answers the exit code instead.
3265
+ */
3266
+ async function claimFor(board, claims, target) {
3267
+ const lease = seconds("lease");
3268
+ if (!flags.ready) {
3269
+ for (const given of [
3270
+ "label",
3271
+ "from",
3272
+ "wait"
3273
+ ]) if (flags[given] !== void 0) throw usage(`--${given} goes with --ready, which claims the next ready task in a channel.`);
3274
+ const claim = await board.tasks.claim(taskId(target), lease !== void 0 ? { lease } : {});
3275
+ await claims.put(claim.task.id, {
3276
+ epoch: claim.epoch,
3277
+ token: claim.token,
3278
+ until: claim.until
3279
+ });
3280
+ return claim;
3281
+ }
3282
+ if (target === void 0) throw usage("Missing the channel to claim a task in: work, or work/ for all under it.", { reason: "missing_arguments" });
3283
+ const wait = seconds("wait");
3284
+ 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.", {
3285
+ reason: "not_available",
3286
+ next: []
3287
+ });
3288
+ const controller = new AbortController();
3289
+ const stop = stopOn(controller);
3290
+ let claim;
3291
+ try {
3292
+ claim = await board.tasks.claim({
3293
+ channel: target,
3294
+ ...flags.label?.length ? { label: labelPairs(flags.label) } : {},
3295
+ ...flags.from?.length ? { from: flags.from } : {},
3296
+ ...wait !== void 0 ? { wait } : {},
3297
+ ...lease !== void 0 ? { lease } : {}
3298
+ }, { signal: controller.signal });
3299
+ } catch (error) {
3300
+ if (controller.signal.aborted) return stop.interrupted() ? 130 : 0;
3301
+ throw error;
3302
+ } finally {
3303
+ stop.release();
3304
+ }
3305
+ if (claim) {
3306
+ await claims.put(claim.task.id, {
3307
+ epoch: claim.epoch,
3308
+ token: claim.token,
3309
+ until: claim.until
3310
+ });
3311
+ return claim;
3312
+ }
3313
+ if (controller.signal.aborted) return stop.interrupted() ? 130 : 0;
3314
+ if (wait !== void 0) throw new Failed({
3315
+ class: "timeout",
3316
+ reason: "timeout",
3317
+ message: `Nothing was ready in ${target} within ${flags.wait}.`
3318
+ });
3319
+ throw new Failed({
3320
+ class: "not_found",
3321
+ reason: "nothing_ready",
3322
+ message: `Nothing is ready in ${target}.`,
3323
+ next: [{
3324
+ instruction: "Wait for one",
3325
+ argv: rerun("--wait", "10m")
3326
+ }, {
3327
+ instruction: "Or see what's there",
3328
+ argv: [
3329
+ ...cli(),
3330
+ "tasks",
3331
+ target
3332
+ ]
3333
+ }]
3334
+ });
3335
+ }
3336
+ /** `tasks`: the list, or what the word after it does to a task. */
3337
+ async function tasks(args) {
3338
+ const [verb, ...rest] = args;
3339
+ if (verb === void 0 || !TASK_VERBS.has(verb)) {
3340
+ if (rest.length > 0) {
3341
+ const guess = closest(verb, TASK_VERBS);
3342
+ throw usage(`Unknown command ${verb} for ${named()} tasks.${guess ? ` Did you mean ${guess}?` : ""}`, { reason: "unknown_command" });
3343
+ }
3344
+ const state = flags.state;
3345
+ 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.`);
3346
+ const board = client();
3347
+ const limit = flags.limit ? Number(flags.limit) : 50;
3348
+ const page = await board.tasks.list({
3349
+ ...verb ? { channel: verb } : {},
3350
+ ...state ? { state } : {},
3351
+ ...flags.label?.length ? { label: flags.label } : {},
3352
+ ...flags.by ? { by: flags.by.replace(/^@/, "") } : {},
3353
+ ...flags.for ? { for: profileActor((await board.me()).principal, flags.for) } : {},
3354
+ ...flags.after !== void 0 ? { after: flags.after.replace(/^#/, "") } : {},
3355
+ limit
3356
+ });
3357
+ if (page.tasks.length === 0 && verb && flags.after === void 0) {
3358
+ const channels = (await board.channels()).map((c) => c.path);
3359
+ const name = verb.replace(/\/$/, "");
3360
+ if (!channels.some((path) => path === name || path.startsWith(`${name}/`))) {
3361
+ const meant = closest(verb, TASK_VERBS);
3362
+ if (meant) throw usage(`Unknown command ${verb} for ${named()} tasks. Did you mean ${meant}?`, { reason: "unknown_command" });
3363
+ const guess = closest(verb, channels);
3364
+ throw new Failed({
3365
+ class: "not_found",
3366
+ reason: "channel_not_found",
3367
+ message: `Couldn't find channel ${verb}.${guess ? ` Did you mean ${guess}?` : ""}`,
3368
+ next: [{
3369
+ instruction: "See its channels",
3370
+ argv: [...cli(), "channels"]
3371
+ }]
3372
+ });
3373
+ }
3374
+ }
3375
+ if (flags.json) return result(page), 0;
3376
+ if (page.tasks.length === 0) {
3377
+ const which = state === void 0 || state === "open" ? "open " : state === "all" ? "" : `${state} `;
3378
+ return out(`no ${which}tasks${verb ? ` in ${verb}` : ""}`), 0;
3379
+ }
3380
+ out(formatTasks(page.tasks));
3381
+ if (page.tasks.length === limit) out(`(more not shown: ${commandLine(rerunWithout(["--after"], "--after", page.cursor))})`);
3382
+ return 0;
3383
+ }
3384
+ if (verb === "create") {
3385
+ const [target, body, extra] = rest;
3386
+ if (!target) throw usage("Missing a channel to start a task in, or a thread's ID to make one of.", { reason: "missing_arguments" });
3387
+ if (extra !== void 0) throw usage(`tasks create takes a channel and quoted text: ${extra} is one too many.`);
3388
+ if (flags["tasks-file"] !== void 0) return createPlan(target, body, flags["tasks-file"]);
3389
+ const lease = seconds("lease");
3390
+ if (lease !== void 0 && !claimFlag()) throw usage("--lease is how long a claim holds the task: pass --claim too.");
3391
+ const { board, claims } = tasksOn();
3392
+ const about = {
3393
+ ...flags.needs?.length ? { needs: flags.needs.map((id) => taskId(id)) } : {},
3394
+ ...flags.for ? { for: profileActor((await board.me()).principal, flags.for) } : {},
3395
+ ...claimFlag() ? { claim: true } : {},
3396
+ ...lease !== void 0 ? { lease } : {}
3397
+ };
3398
+ let made;
3399
+ if (isMessageRef(target)) {
3400
+ const own = body !== void 0 ? "text" : [
3401
+ "text-file",
3402
+ "label",
3403
+ "no-sync",
3404
+ "idempotency-key"
3405
+ ].find((name) => flags[name] !== void 0 && flags[name] !== false);
3406
+ if (own !== void 0) throw usage(`${ref(target)} becomes a task as it is: ${own === "text" ? "text" : `--${own}`} is for a new thread.`, { next: [{
3407
+ instruction: "Make it a task as it is",
3408
+ argv: [
3409
+ ...cli(),
3410
+ "tasks",
3411
+ "create",
3412
+ messageId(target)
3413
+ ]
3414
+ }] });
3415
+ made = await board.tasks.create({ re: messageId(target) }, about);
3416
+ } else {
3417
+ const said = await text(body);
3418
+ sentLength = said.length;
3419
+ made = await board.tasks.create(target, {
3420
+ text: said,
3421
+ ...flags.label?.length ? { labels: labelPairs(flags.label) } : {},
3422
+ ...flags["no-sync"] ? { noSync: true } : {},
3423
+ ...flags["idempotency-key"] ? { id: flags["idempotency-key"] } : {},
3424
+ ...about
3425
+ });
3426
+ }
3427
+ const mentions = made.mentions ? { mentions: made.mentions } : {};
3428
+ if (flags.json) sayMentions(made.mentions);
3429
+ if (made.claim) {
3430
+ await claims.put(made.task.id, {
3431
+ epoch: made.claim.epoch,
3432
+ token: made.claim.token,
3433
+ until: made.claim.until
3434
+ });
3435
+ printClaim(made.task, made.claim, {
3436
+ outcome: "created",
3437
+ ...mentions
3438
+ });
3439
+ } else if (flags.json) result({
3440
+ task: made.task,
3441
+ outcome: "created",
3442
+ ...mentions
3443
+ });
3444
+ else out(messageRef(made.task.id));
3445
+ if (!flags.json) sayMentions(made.mentions);
3446
+ return 0;
3447
+ }
3448
+ if (verb === "claim") {
3449
+ if (rest.length > 1) throw usage(`tasks claim takes one ${flags.ready ? "channel" : "task"}: ${rest[1]} is one too many.`);
3450
+ if (!flags.ready && rest[0] === void 0) throw usage("Missing the task to claim: its ID, or --ready and a channel.", { reason: "missing_arguments" });
3451
+ const { board, claims } = tasksOn();
3452
+ const claim = await claimFor(board, claims, rest[0]);
3453
+ if (typeof claim === "number") return claim;
3454
+ printClaim(claim.task, claim);
3455
+ return 0;
3456
+ }
3457
+ if (verb === "run") {
3458
+ const dash = typed.indexOf("--");
3459
+ const command = dash === -1 ? [] : typed.slice(dash + 1);
3460
+ if (command.length === 0) throw usage("Missing the command to run: put it after --.", {
3461
+ reason: "missing_arguments",
3462
+ next: [{
3463
+ instruction: "Run a command on a task",
3464
+ argv: [
3465
+ ...cli(),
3466
+ "tasks",
3467
+ "run",
3468
+ "<ID>",
3469
+ "--",
3470
+ "<COMMAND>"
3471
+ ]
3472
+ }]
3473
+ });
3474
+ const before = rest.slice(0, rest.length - command.length);
3475
+ if (before.length > 1) throw usage(`tasks run takes one ${flags.ready ? "channel" : "task"} before --: ${before[1]} is one too many.`);
3476
+ 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" });
3477
+ if (io.board) throw usage("tasks run isn't available in-process: it runs a command on this machine.", {
3478
+ reason: "not_available",
3479
+ next: []
3480
+ });
3481
+ const { board, claims } = tasksOn();
3482
+ const claim = await claimFor(board, claims, before[0]);
3483
+ if (typeof claim === "number") return claim;
3484
+ const id = claim.task.id;
3485
+ const lease = seconds("lease");
3486
+ const ran = await runCommand(command, {
3487
+ env: {
3488
+ ...process.env,
3489
+ BOARD_TASK: id
3490
+ },
3491
+ ...flags.json ? { stdout: "stderr" } : {},
3492
+ every: (Date.parse(claim.until) - Date.now()) / 3,
3493
+ async renew() {
3494
+ try {
3495
+ const renewed = await claim.renew(lease);
3496
+ await claims.put(id, {
3497
+ epoch: renewed.epoch,
3498
+ token: renewed.token,
3499
+ until: renewed.until
3500
+ });
3501
+ return true;
3502
+ } catch (error) {
3503
+ return !(error instanceof BoardError && error.code === "claim_lost");
3504
+ }
3505
+ }
3506
+ });
3507
+ if (ran.how === "lost") {
3508
+ await claims.drop(id);
3509
+ throw new Failed({
3510
+ class: "conflict",
3511
+ reason: "claim_lost",
3512
+ message: `Lost the claim on task ${ref(id)} while the command ran, so it was stopped.`,
3513
+ next: [{
3514
+ instruction: "See where the task stands",
3515
+ argv: [
3516
+ ...cli(),
3517
+ "read",
3518
+ id
3519
+ ]
3520
+ }]
3521
+ });
3522
+ }
3523
+ if (ran.how === "unstarted") {
3524
+ await claim.release().catch(() => {});
3525
+ await claims.drop(id);
3526
+ throw new Failed({
3527
+ class: "not_found",
3528
+ reason: "command_not_found",
3529
+ message: `Couldn't run ${command[0]}. ${sentence(ran.why)}`,
3530
+ details: [`Task ${ref(id)} was released.`]
3531
+ });
3532
+ }
3533
+ if (ran.how === "interrupted") {
3534
+ await withClaim(claims, id, () => claim.release());
3535
+ await claims.drop(id);
3536
+ return ran.code;
3537
+ }
3538
+ 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}`));
3539
+ await claims.drop(id);
3540
+ printTask(settled, ran.code === 0 ? "completed" : "failed", ran.code === 0 ? {} : { code: ran.code });
3541
+ return ran.code;
3542
+ }
3543
+ const id = taskId(rest[0]);
3544
+ const one = (extra, takes) => {
3545
+ if (extra !== void 0) throw usage(`tasks ${verb} takes ${takes}: ${extra} is one too many.`);
3546
+ };
3547
+ const reason = (what) => {
3548
+ const given = rest[1]?.trim();
3549
+ if (!given) throw usage(`Missing ${what}, in a line.`, { reason: "missing_arguments" });
3550
+ return given;
3551
+ };
3552
+ const { board, claims } = tasksOn();
3553
+ switch (verb) {
3554
+ case "renew": {
3555
+ one(rest[1], "one task");
3556
+ const lease = seconds("lease");
3557
+ const held = await heldBy(board, claims, id);
3558
+ const claim = await withClaim(claims, id, () => held.renew(lease));
3559
+ await claims.put(id, {
3560
+ epoch: claim.epoch,
3561
+ token: claim.token,
3562
+ until: claim.until
3563
+ });
3564
+ printClaim(claim.task, claim);
3565
+ return 0;
3566
+ }
3567
+ case "release": {
3568
+ one(rest[1], "one task");
3569
+ const held = await heldBy(board, claims, id);
3570
+ const task = await withClaim(claims, id, () => held.release());
3571
+ await claims.drop(id);
3572
+ printTask(task, "released");
3573
+ return 0;
3574
+ }
3575
+ case "complete": {
3576
+ one(rest[2], "a task and its result, quoted");
3577
+ const held = await heldBy(board, claims, id);
3578
+ const task = await withClaim(claims, id, () => held.complete(rest[1]));
3579
+ await claims.drop(id);
3580
+ printTask(task, "completed");
3581
+ return 0;
3582
+ }
3583
+ case "fail": {
3584
+ one(rest[2], "a task and a reason, quoted");
3585
+ const why = reason("why it failed");
3586
+ const held = await heldBy(board, claims, id);
3587
+ const task = await withClaim(claims, id, () => held.fail(why));
3588
+ await claims.drop(id);
3589
+ printTask(task, "failed");
3590
+ return 0;
3591
+ }
3592
+ case "block": {
3593
+ one(rest[2], "a task and a reason, quoted");
3594
+ const why = reason("what you need from a person");
3595
+ const hold = flags.kind !== void 0 ? { kind: flags.kind } : {};
3596
+ const stored = await claims.get(id);
3597
+ const task = stored ? await withClaim(claims, id, () => board.tasks.held(id, stored).block(why, hold)) : await board.tasks.block(id, why, hold);
3598
+ await claims.drop(id);
3599
+ printTask(task, "blocked");
3600
+ return 0;
3601
+ }
3602
+ case "unblock":
3603
+ case "reopen": {
3604
+ one(rest[1], "one task");
3605
+ const from = verb === "unblock" ? "blocked" : "failed";
3606
+ const was = (await board.thread(id)).message.task?.state;
3607
+ const task = verb === "unblock" ? await board.tasks.unblock(id) : await board.tasks.reopen(id);
3608
+ if (was === from) printTask(task, verb === "unblock" ? "unblocked" : "reopened");
3609
+ else if (flags.json) result({
3610
+ task,
3611
+ outcome: "unchanged"
3612
+ });
3613
+ else out(`${messageRef(id)} wasn't ${from}`);
3614
+ return 0;
3615
+ }
3616
+ case "assign": {
3617
+ one(rest[2], "a task and a profile");
3618
+ const profile = rest[1];
3619
+ if (flags.pool && profile !== void 0) throw usage(`A profile keeps ${ref(id)} for it, and --pool for no one: pass one of them.`);
3620
+ 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" });
3621
+ const owner = profile === void 0 ? null : (await board.thread(id)).message.task?.owner;
3622
+ const task = await board.tasks.assign(id, profile === void 0 ? null : profileActor(owner ?? (await board.me()).principal, profile));
3623
+ if (flags.json) result({
3624
+ task,
3625
+ outcome: profile === void 0 ? "unassigned" : "assigned"
3626
+ });
3627
+ else out(profile === void 0 ? `unassigned ${messageRef(id)}` : `assigned ${messageRef(id)} to ${profile.toLowerCase()}`);
3628
+ return 0;
3629
+ }
3630
+ case "needs": {
3631
+ const needs = rest.slice(1).map((need) => taskId(need));
3632
+ if (flags.none && needs.length > 0) throw usage(`Tasks are what ${ref(id)} waits for, and --none for nothing: pass one of them.`);
3633
+ if (!flags.none && needs.length === 0) throw usage("Missing the tasks it waits for now, by ID, or --none for nothing.", { reason: "missing_arguments" });
3634
+ const task = await board.tasks.needs(id, needs);
3635
+ const now = task.task?.needs ?? [];
3636
+ if (flags.json) result({
3637
+ task,
3638
+ outcome: "set"
3639
+ });
3640
+ else out(`${messageRef(id)} needs ${now.length ? now.map((need) => ref(need)).join(" ") : "nothing"}`);
3641
+ return 0;
3642
+ }
3643
+ default: {
3644
+ one(rest[2], "a task and a reason, quoted");
3645
+ const task = await board.tasks.cancel(id, reason("why"));
3646
+ await claims.drop(id);
3647
+ printTask(task, "canceled");
3648
+ return 0;
3649
+ }
3650
+ }
3651
+ }
3652
+ /** How a board's own word about a task reads from here: the headline, and the way on. Null for any other code. */
3653
+ function taskFailure(code, status) {
3654
+ const { command, args } = current;
3655
+ 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;
3656
+ const read = (instruction) => named === void 0 ? [] : [{
3657
+ instruction,
3658
+ argv: [
3659
+ ...cli(),
3660
+ "read",
3661
+ named
3662
+ ]
3663
+ }];
3664
+ const also = (instruction, ...words) => named === void 0 ? [] : [{
3665
+ instruction,
3666
+ argv: [
3667
+ ...cli(),
3668
+ "tasks",
3669
+ words[0],
3670
+ named,
3671
+ ...words.slice(1)
3672
+ ]
3673
+ }];
3674
+ switch (code) {
3675
+ case "task_claimed": return {
3676
+ class: "conflict",
3677
+ message: `Can't ${doing()}. Someone holds it.`,
3678
+ next: read("See who holds it, and until when")
3679
+ };
3680
+ case "task_assigned": return {
3681
+ class: "conflict",
3682
+ message: `Can't ${doing()}. It's assigned to another profile.`,
3683
+ next: [...read("See whom it's for"), ...also("Or, as its owner, return it to the pool", "assign", "--pool")]
3684
+ };
3685
+ case "task_waiting": return {
3686
+ class: "conflict",
3687
+ message: `Can't ${doing()}. It waits for other tasks.`,
3688
+ next: read("See what it waits for")
3689
+ };
3690
+ case "task_blocked": return {
3691
+ class: "conflict",
3692
+ message: `Can't ${doing()}. It's held for a person.`,
3693
+ next: [...read("See what it's held for"), ...also("Or, as its owner, lift the hold", "unblock")]
3694
+ };
3695
+ case "task_finished": return {
3696
+ class: "conflict",
3697
+ message: `Can't ${doing()}. It's finished.`,
3698
+ next: read("See how it ended")
3699
+ };
3700
+ case "claim_lost": return {
3701
+ class: "conflict",
3702
+ message: `Lost the claim on ${named === void 0 ? "the task" : `task ${ref(named)}`}. Its lease ran out, or the task moved on.`,
3703
+ next: [...read("See where it stands"), ...also("Or claim it again", "claim", ...asTyped())]
3704
+ };
3705
+ case "task_not_owned": return {
3706
+ class: "permission",
3707
+ message: `You can't ${doing()}. It's someone else's.`,
3708
+ next: read("See whose it is")
3709
+ };
3710
+ case "not_a_task": return {
3711
+ class: "not_found",
3712
+ message: `${named === void 0 ? "That" : ref(named)} isn't a task.`,
3713
+ next: also("Make it one", "create"),
3714
+ whole: true
3715
+ };
3716
+ case "already_a_task": return {
3717
+ class: "conflict",
3718
+ message: `${named === void 0 ? "That" : ref(named)} is a task already.`,
3719
+ next: read("See it"),
3720
+ whole: true
3721
+ };
3722
+ case "invalid_from": return {
3723
+ class: "usage",
3724
+ message: `Can't ${doing()}. --from takes an owner's ID: several can share a handle.`,
3725
+ next: [{
3726
+ instruction: "See everyone's IDs",
3727
+ argv: [...cli(), "actors"]
3728
+ }]
3729
+ };
3730
+ case "invalid_needs":
3731
+ if (flags["tasks-file"] !== void 0) return {
3732
+ class: "usage",
3733
+ message: `Can't ${doing()}. A task's needs are tasks you can read, or keys of the plan's own.`,
3734
+ next: [{
3735
+ instruction: "See the tasks there are",
3736
+ argv: [
3737
+ ...cli(),
3738
+ "tasks",
3739
+ "--state",
3740
+ "all"
3741
+ ]
3742
+ }]
3743
+ };
3744
+ if (command === "tasks" && args[0] === "needs") return {
3745
+ class: "usage",
3746
+ message: `Can't ${doing()}. It waits for tasks you can read, and none that waits for it.`,
3747
+ next: [...read("See what it waits for now"), {
3748
+ instruction: "Or see the tasks there are",
3749
+ argv: [
3750
+ ...cli(),
3751
+ "tasks",
3752
+ "--state",
3753
+ "all"
3754
+ ]
3755
+ }]
3756
+ };
3757
+ return {
3758
+ class: "usage",
3759
+ message: `Can't ${doing()}. --needs takes tasks you can read.`,
3760
+ next: [{
3761
+ instruction: "See the tasks there are",
3762
+ argv: [
3763
+ ...cli(),
3764
+ "tasks",
3765
+ "--state",
3766
+ "all"
3767
+ ]
3768
+ }]
3769
+ };
3770
+ case "claim_too_wide": return {
3771
+ class: "limit",
3772
+ message: `Can't ${doing()}. That's too many channels and owners.`,
3773
+ next: [{ instruction: "Name fewer owners with --from, or a smaller subtree" }]
3774
+ };
3775
+ case "channel_tree_too_large": return {
3776
+ class: "limit",
3777
+ message: `Can't ${doing()}. That's too many channels.`,
3778
+ next: [{ instruction: "Name a channel, or a smaller subtree" }]
3779
+ };
3780
+ case "no_tasks": return status === 501 ? {
3781
+ class: "platform",
3782
+ message: `Can't ${doing()}. This board keeps no tasks.`,
3783
+ next: []
3784
+ } : null;
3785
+ case "reserved_label": return {
3786
+ class: "usage",
3787
+ message: `Can't ${doing()}. Labels under board. are the board's own.`,
3788
+ next: stateCommand()
3789
+ };
3790
+ default: return null;
3791
+ }
3792
+ }
3793
+ /**
3794
+ * The `tasks` command for the change a write under `board.task` was after, from what this run was
3795
+ * given: a label write names the state it wanted, and a labeled post a task it meant to start.
3796
+ */
3797
+ function stateCommand() {
3798
+ const { command, args } = current;
3799
+ const tasksDo = (instruction, ...words) => ({
3800
+ instruction,
3801
+ argv: [
3802
+ ...cli(),
3803
+ "tasks",
3804
+ ...words
3805
+ ]
3806
+ });
3807
+ if (command === "label" && args[0] !== void 0) {
3808
+ const id = messageId(args[0]);
3809
+ const wanted = args.slice(1).find((pair) => pair.startsWith("board.task="))?.slice(11);
3810
+ if (wanted === void 0) return flags.unset?.includes("board.task") ? [tasksDo("Cancel the task", "cancel", id, "<REASON>")] : [];
3811
+ switch (wanted) {
3812
+ case "ready": return [tasksDo("Make the thread a task", "create", id), tasksDo("Or lift a hold on one", "unblock", id)];
3813
+ case "waiting": return [tasksDo("Make it a task that waits for another", "create", id, "--needs", "<ID>")];
3814
+ case "claimed": return [tasksDo("Claim it", "claim", id)];
3815
+ case "completed": return [tasksDo("Complete it, with the claim you hold", "complete", id)];
3816
+ case "failed": return [tasksDo("Fail it, with the claim you hold", "fail", id, "<REASON>")];
3817
+ case "blocked": return [tasksDo("Hold it for a person", "block", id, "<REASON>")];
3818
+ case "canceled": return [tasksDo("Cancel it", "cancel", id, "<REASON>")];
3819
+ default: return [{
3820
+ instruction: "See what changes a task",
3821
+ argv: [
3822
+ ...cli(),
3823
+ "tasks",
3824
+ "--help"
3825
+ ]
3826
+ }];
3827
+ }
3828
+ }
3829
+ 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>")];
3830
+ return [];
3831
+ }
2608
3832
  /** Words for a command this CLI names otherwise, and the command they mean. */
2609
3833
  const OTHER_NAMES = {
2610
3834
  search: {
@@ -2967,7 +4191,7 @@ function stopped(reason) {
2967
4191
  "revoke",
2968
4192
  "cancel",
2969
4193
  "join"
2970
- ].includes(sub ?? "");
4194
+ ].includes(sub ?? "") || current.command === "tasks" && TASK_VERBS.has(sub ?? "");
2971
4195
  return new Failed({
2972
4196
  class: timedOut ? "timeout" : "canceled",
2973
4197
  reason: timedOut ? "timeout" : "canceled",