@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,12 +1,13 @@
1
- import { S as mediaType, _ as ATTACHMENT_BYTES_MAX, a as forbidden, b as fileName, d as BoardError, f as createBoardClient, h as formatProfileHeader, l as toErrorResponse, m as eventsState, n as RejectedError, o as json, p as duration, r as badRequest, s as notFound, t as HttpError, u as unauthorized, y as IMPORT_BYTES_MAX } from "./errors-ZazTZh-s.mjs";
2
- import { g as RemoteWatcherId } from "./schemas-BhZaystC.mjs";
3
- import { A as SyncReceiptBody, C as SchemaBody, D as SyncCopiesQuery, E as SyncBody, F as routes, M as TypingBody, N as UpdateGrantBody, O as SyncFindQuery, P as UploadStartBody, S as SchedulesQuery, T as SourceReadQuery, _ as PostBody, a as EventsQuery, b as RegisterBody, c as GrantBody, d as InboxPushBody, f as InboxQuery, g as MessagesQuery, h as MatchesQuery, i as EditBody, j as ThreadsQuery, k as SyncImportBody, l as InboxAckBody, m as LinkedQuery, n as CreateChannelBody, o as ExplainQuery, p as LabelBody, r as DeleteBody, t as AckBody, u as InboxNextQuery, v as ReactBody, w as SourceJoinBody, x as ScheduleBody, y as Ref } from "./routes-CkUetTO2.mjs";
4
- import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-BHHKHA9q.mjs";
1
+ import { S as fileName, _ as formatProfileHeader, a as duplicateId, c as notFound, d as unauthorized, f as BoardError, h as eventsState, i as batchTooLarge, m as duration, n as RejectedError, o as forbidden, p as createBoardClient, r as badRequest, s as json, t as HttpError, u as toErrorResponse, w as mediaType, x as IMPORT_BYTES_MAX, y as ATTACHMENT_BYTES_MAX } from "./errors-DZ1tbwSM.mjs";
2
+ import { v as RESERVED_LABEL_PREFIX, w as TASK_LABEL, y as RemoteWatcherId } from "./schemas-7VFdomFB.mjs";
3
+ import { A as RegisterBody, B as SyncFindQuery, C as LabelBody, D as PostBody, E as MessagesQuery, F as SchemaBody, G as ThreadsQuery, H as SyncReceiptBody, I as SourceJoinBody, J as UploadStartBody, K as TypingBody, L as SourceReadQuery, M as RenewTaskBody, N as ScheduleBody, O as ReactBody, P as SchedulesQuery, R as SyncBody, S as InboxQuery, T as MatchesQuery, U as TaskNeedsBody, V as SyncImportBody, W as TasksQuery, Y as routes, a as ClaimReadyTaskBody, b as InboxNextQuery, c as CreateChannelBody, d as CreatedTasksQuery, f as DeleteBody, g as FailTaskBody, h as ExplainQuery, i as CancelTaskBody, j as ReleaseTaskBody, k as Ref, l as CreateTaskBody, m as EventsQuery, n as AssignTaskBody, o as ClaimTaskBody, p as EditBody, q as UpdateGrantBody, r as BlockTaskBody, s as CompleteTaskBody, t as AckBody, u as CreateTasksBody, v as GrantBody, w as LinkedQuery, x as InboxPushBody, y as InboxAckBody, z as SyncCopiesQuery } from "./routes-B2HHHD_C.mjs";
4
+ import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-BKsTcMAv.mjs";
5
5
  import { n as blocksIn, r as findBlocks } from "./blocks-CVoBC7ur.mjs";
6
- import { a as compileWatcher, c as METHODS, d as queryObject, f as readCapped, h as VERSION, i as runMatch, l as createRouter, m as SYNC, n as syncTarget, p as readJson, r as canonicalWatchers, t as SYNC_ACTOR, u as openapi } from "./origin-BbwhnKrg.mjs";
7
- import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-3udXjJAg.mjs";
8
- import { C as explainGrants, b as verifiesTokens, d as grantIssuers, f as hostPrincipal, i as VERCEL_ISSUER, l as createAuthority, t as DEFAULT_CAN$1, u as fromTokens, y as verifiedIssuers } from "./auth-aiOVE82-.mjs";
9
- import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-DasGZnfb.mjs";
6
+ import { i as mentionTerms, r as mentionTerm } from "./mentions-DfZGp3B-.mjs";
7
+ import { a as runMatch, d as openapi, f as queryObject, g as VERSION, h as SYNC, i as canonicalWatchers, l as METHODS, m as readJson, n as SYNC_ACTOR, o as compileWatcher, p as readCapped, r as syncTarget, t as batchPlan, u as createRouter } from "./task-batch-BJcLiYe1.mjs";
8
+ import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-Crbvd2Dm.mjs";
9
+ import { C as explainGrants, b as verifiesTokens, d as grantIssuers, f as hostPrincipal, i as VERCEL_ISSUER, l as createAuthority, t as DEFAULT_CAN$1, u as fromTokens, y as verifiedIssuers } from "./auth-C-pFnJBA.mjs";
10
+ import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-BBphaJ_G.mjs";
10
11
  import { t as checkValue } from "./data-values-CoTP0SQG.mjs";
11
12
  //#region src/server/registrant.ts
12
13
  /** Registering again this soon after the same registration only repeats it. */
@@ -408,6 +409,7 @@ function boardPolicy(reach) {
408
409
  ...refused("not a board route")
409
410
  },
410
411
  ...routeRules(prefix, reach.routes, scoped, transform),
412
+ ...(reach.under ?? []).flatMap(({ path, routes }) => routeRules(escaped(path.replace(/\/+$/, "")), routes, scoped, transform)),
411
413
  ...(reach.reads ?? []).map((path) => ({
412
414
  match: scoped({
413
415
  path: { exact: path },
@@ -445,6 +447,10 @@ const SANDBOX_ROUTES = [
445
447
  method: "GET",
446
448
  path: "/channels"
447
449
  },
450
+ {
451
+ method: "GET",
452
+ path: "/channels/:id"
453
+ },
448
454
  {
449
455
  method: "POST",
450
456
  path: "/channels"
@@ -539,6 +545,44 @@ const SANDBOX_ROUTES = [
539
545
  }
540
546
  ];
541
547
  /**
548
+ * What its task methods call there, under version 2's `/boards/<id>`: making a task, listing them, claiming the next
549
+ * ready one, and each change of one. A sandbox's policy hands it these and nothing else at that version.
550
+ */
551
+ const SANDBOX_TASK_ROUTES = [
552
+ {
553
+ method: "GET",
554
+ path: "/tasks"
555
+ },
556
+ {
557
+ method: "POST",
558
+ path: "/tasks"
559
+ },
560
+ {
561
+ method: "POST",
562
+ path: "/tasks/batch"
563
+ },
564
+ {
565
+ method: "POST",
566
+ path: "/tasks/claim"
567
+ },
568
+ ...[
569
+ "claim",
570
+ "renew",
571
+ "release",
572
+ "complete",
573
+ "fail",
574
+ "block",
575
+ "unblock",
576
+ "reopen",
577
+ "assign",
578
+ "needs",
579
+ "cancel"
580
+ ].map((change) => ({
581
+ method: "POST",
582
+ path: `/tasks/:task/${change}`
583
+ }))
584
+ ];
585
+ /**
542
586
  * Who a request to Vercel's API writes as, as the API reads it today: the profile's name alone in
543
587
  * `x-board-profile`, and its avatar in `x-board-avatar`, which board's protocol refuses for the
544
588
  * avatar parameter of `x-board-profile` (`formatProfileHeader`). Every request and sandbox policy
@@ -673,6 +717,47 @@ function operationId() {
673
717
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
674
718
  }
675
719
  const iso = (ms) => new Date(ms).toISOString();
720
+ /** A claim's token as the API takes one: 43 base64url characters. */
721
+ const CLAIM_TOKEN = /^[a-zA-Z0-9_-]{43}$/;
722
+ const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
723
+ /** A claim's secret, which the API has its caller make: 32 random bytes, of which it keeps the hash alone. */
724
+ const newClaimToken = () => base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
725
+ /**
726
+ * A token a caller holds, as the API takes one. One that isn't shaped like any this backend made can't be a claim's:
727
+ * it goes as its hash, which is shaped like one and matches none, so the API answers as it does for any wrong token.
728
+ */
729
+ const sendableToken = async (token) => CLAIM_TOKEN.test(token) ? token : base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))));
730
+ /** A task list's cursor before any task: a read after it starts at the oldest. */
731
+ const TASKS_START = "0";
732
+ /** Whether `value` is shaped like an ID, `<where it's from>:<who>`, as every principal's and actor's is: a handle isn't. */
733
+ const isId = (value) => /^[^\s:]+:\S+$/.test(value);
734
+ /** The board's task events, by the API's name for each: only a new task's differs, since the API's older tasks have a `task.created` of their own. */
735
+ const TASK_EVENTS = {
736
+ "task.made": "task.created",
737
+ "task.assigned": "task.assigned",
738
+ "task.needs_changed": "task.needs_changed",
739
+ "task.ready": "task.ready",
740
+ "task.claimed": "task.claimed",
741
+ "task.renewed": "task.renewed",
742
+ "task.released": "task.released",
743
+ "task.expired": "task.expired",
744
+ "task.completed": "task.completed",
745
+ "task.failed": "task.failed",
746
+ "task.blocked": "task.blocked",
747
+ "task.unblocked": "task.unblocked",
748
+ "task.canceled": "task.canceled",
749
+ "task.reopened": "task.reopened"
750
+ };
751
+ /** The API's codes for a task that can't change as asked, each a 409 on a board. */
752
+ const TASK_CONFLICTS = /* @__PURE__ */ new Set([
753
+ "already_a_task",
754
+ "task_claimed",
755
+ "task_assigned",
756
+ "task_waiting",
757
+ "task_blocked",
758
+ "task_finished",
759
+ "claim_lost"
760
+ ]);
676
761
  /** A grant as the API answers it, its `at` in milliseconds, as the protocol has it: an ISO string. */
677
762
  const grantFrom = (grant) => ({
678
763
  ...grant,
@@ -901,7 +986,7 @@ const originOf = (origin) => origin ? {
901
986
  /**
902
987
  * Vercel's board for your team, in Vercel's API: this deployment keeps nothing and reads and writes
903
988
  * it as itself, its people as themselves. Messages, threads, reactions, labels, a channel's
904
- * changes, schedules, files, watchers, and sync's records work: the API keeps sync's state, and
989
+ * changes, schedules, tasks, files, watchers, and sync's records work: the API keeps sync's state, and
905
990
  * the platforms stay with board()'s sync.
906
991
  */
907
992
  function createVercel(options, environment) {
@@ -920,13 +1005,15 @@ function createVercel(options, environment) {
920
1005
  const given = binding?.team ?? options.team;
921
1006
  return team ??= given ? Promise.resolve(given) : environment?.team() ?? Promise.resolve(null);
922
1007
  };
1008
+ /** What the API said of an error beside its code: a lost claim's `reason`. */
1009
+ const reasons = /* @__PURE__ */ new WeakMap();
923
1010
  /**
924
1011
  * One request to the API, as `who`. Its errors are the API's own, with its status and code. One the
925
1012
  * API puts off (429, or a 503) waits and goes again as it was, so a write keeps its operation ID
926
1013
  * and lands once.
927
1014
  */
928
1015
  async function api(who, method, path, init = {}) {
929
- const url = new URL(`${origin}/v1/messageboard${path}`);
1016
+ const url = new URL(`${origin}/v${init.version ?? 1}/messageboard${path}`);
930
1017
  const id = await teamId();
931
1018
  if (id) url.searchParams.set(id.startsWith("team_") ? "teamId" : "slug", id);
932
1019
  for (const [name, value] of Object.entries(init.query ?? {})) {
@@ -966,7 +1053,9 @@ function createVercel(options, environment) {
966
1053
  continue;
967
1054
  }
968
1055
  const error = body?.error;
969
- throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
1056
+ const refused = new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
1057
+ if (typeof error?.reason === "string" && /^[a-z_]{1,64}$/.test(error.reason)) reasons.set(refused, error.reason);
1058
+ throw refused;
970
1059
  }
971
1060
  }
972
1061
  /** A request on sync's routes, whose refusals board()'s sync knows only by the board's codes. */
@@ -1084,7 +1173,26 @@ function createVercel(options, environment) {
1084
1173
  }
1085
1174
  /** Channels' names by ID, as posts without a client ID named them: a post's own channel, which it may not be able to list. */
1086
1175
  const posted = /* @__PURE__ */ new Map();
1176
+ /**
1177
+ * The channel with `id`, asked for by it: a message names its channel by ID, and the board's whole
1178
+ * list, a page of the API's at a time, is a lot to read for one name. A list this process has
1179
+ * already read answers first, and one the API won't show by ID is looked for in the list, as before.
1180
+ */
1181
+ const byChannelId = /* @__PURE__ */ new Map();
1087
1182
  async function channelById(who, id) {
1183
+ const listed = channels ? (await loadChannels(who)).find((channel) => channel.id === id) : void 0;
1184
+ if (listed) return listed;
1185
+ let asked = byChannelId.get(id);
1186
+ if (!asked) {
1187
+ asked = onBoard(who, `/channels/${encodeURIComponent(id)}`).then((path) => api(who, "GET", path)).then(({ channel }) => channel).catch((error) => {
1188
+ byChannelId.delete(id);
1189
+ if (error instanceof HttpError && (error.status === 404 || error.status === 403)) return null;
1190
+ throw error;
1191
+ });
1192
+ byChannelId.set(id, asked);
1193
+ }
1194
+ const one = await asked;
1195
+ if (one) return one;
1088
1196
  const found = (await loadChannels(who)).find((channel) => channel.id === id) ?? (await loadChannels(who, true)).find((channel) => channel.id === id);
1089
1197
  if (!found) throw new HttpError(502, "remote_error", `Vercel's API names a channel it doesn't list: ${id}`);
1090
1198
  return found;
@@ -1359,6 +1467,25 @@ function createVercel(options, environment) {
1359
1467
  if (project === null || project === await ownProject(who)) return from;
1360
1468
  return `${await projectOf(who, by) ?? project}/${from}`;
1361
1469
  }
1470
+ /** A task as board shows it: the tasks it waits for by their roots' IDs, and its claim's end as a time. */
1471
+ const taskView = (task) => ({
1472
+ state: task.state,
1473
+ owner: task.owner,
1474
+ by: task.by,
1475
+ for: task.for,
1476
+ needs: task.needs.map((thread) => idAt(thread, 1)),
1477
+ epoch: task.epoch,
1478
+ claim: task.claim ? {
1479
+ actor: task.claim.actor,
1480
+ until: iso(task.claim.until)
1481
+ } : null,
1482
+ blocked: task.blocked ? {
1483
+ kind: task.blocked.kind,
1484
+ reason: task.blocked.reason
1485
+ } : null,
1486
+ result: task.result,
1487
+ reason: task.reason
1488
+ });
1362
1489
  async function view(who, message, channel) {
1363
1490
  const root = message.sequence === 1;
1364
1491
  const author = nameOf(who, message.createdBy);
@@ -1394,6 +1521,7 @@ function createVercel(options, environment) {
1394
1521
  id: message.schedule.id,
1395
1522
  n: message.schedule.n
1396
1523
  } } : {},
1524
+ ...root && message.task ? { task: taskView(message.task) } : {},
1397
1525
  blocks: (message.from ?? null) === null && message.deletedAt === void 0 ? blocksIn(message.text) : []
1398
1526
  };
1399
1527
  }
@@ -1460,15 +1588,27 @@ function createVercel(options, environment) {
1460
1588
  if (kept) return kept;
1461
1589
  const found = CURSOR.exec(cursor);
1462
1590
  if (!found) throw new HttpError(400, "invalid_cursor", `after: ${cursor} isn't a cursor here or a message's ID`);
1591
+ const t = parseInt(found[1], 36);
1463
1592
  return {
1464
- t: parseInt(found[1], 36),
1465
- feeds: {}
1593
+ t,
1594
+ feeds: {},
1595
+ floor: t
1466
1596
  };
1467
1597
  }
1468
1598
  /** A time a read goes on from: a cursor's, or a message's own. */
1469
1599
  async function timeOf(who, after) {
1470
1600
  return locate(after) ? (await messageById(who, after)).message.createdAt : positionOf(after).t;
1471
1601
  }
1602
+ /** Where a read after a message starts: its time, with no feed read yet. */
1603
+ async function afterMessage(who, id) {
1604
+ const t = await timeOf(who, id);
1605
+ return {
1606
+ t,
1607
+ feeds: {},
1608
+ past: id,
1609
+ floor: t
1610
+ };
1611
+ }
1472
1612
  /** Each channel's feed now, taken before a read, so what's posted while it reads comes after. */
1473
1613
  async function heads(who, listed) {
1474
1614
  const path = await onBoard(who, "/changes");
@@ -1527,9 +1667,29 @@ function createVercel(options, environment) {
1527
1667
  return message.from === key && importer !== null && (importer === project || await namedProject(who, importer) === project);
1528
1668
  };
1529
1669
  }
1670
+ /**
1671
+ * What `--mentions` matches, in a message's text, as on any board: `me` is the caller's handle and
1672
+ * actor ID, as the API names them. Anyone else is the name as written and what's under it: a
1673
+ * person's agents (`@julian/claude`), a project's imports. The API keeps no mentions, so this reads
1674
+ * them from the text of each message a read covers.
1675
+ */
1676
+ async function mentionsOf(who, value) {
1677
+ if (value === void 0) return void 0;
1678
+ let terms;
1679
+ let prefixes = [];
1680
+ if (value === "me") {
1681
+ const found = await api(who, "GET", await onBoard(who, "/me"));
1682
+ terms = [found.actor.id, ...found.view?.handle ? [mentionTerm(found.view.handle)] : []];
1683
+ } else {
1684
+ terms = [mentionTerm(value)];
1685
+ prefixes = [value.includes(":") ? `${value}+` : `${mentionTerm(value)}/`];
1686
+ }
1687
+ return (text) => mentionTerms(text).some((term) => terms.includes(term) || prefixes.some((prefix) => term.startsWith(prefix)));
1688
+ }
1530
1689
  const narrowOf = async (who, filters) => ({
1531
1690
  by: await byOf(who, filters.by),
1532
- source: await sourceOf(who, filters.from)
1691
+ source: await sourceOf(who, filters.from),
1692
+ mentions: await mentionsOf(who, filters.mentions)
1533
1693
  });
1534
1694
  /**
1535
1695
  * Whether a message matches a read's filters, `narrow` as `narrowOf` gives them for it. A label matches on the
@@ -1538,7 +1698,7 @@ function createVercel(options, environment) {
1538
1698
  async function matches(filters, message, thread, narrow) {
1539
1699
  if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
1540
1700
  if (narrow.by && !narrow.by(message.createdBy)) return false;
1541
- if (filters.mentions !== void 0) return false;
1701
+ if (filters.mentions !== void 0 && !narrow.mentions?.(message.text)) return false;
1542
1702
  if (filters.from !== void 0 && !await narrow.source?.(message)) return false;
1543
1703
  if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
1544
1704
  for (const [key, values] of filters.label ?? []) {
@@ -1552,12 +1712,34 @@ function createVercel(options, environment) {
1552
1712
  const first = filters.label?.find(([, values]) => values === null || values.length === 1);
1553
1713
  return first && (first[1] === null ? first[0] : `${first[0]}=${first[1][0]}`);
1554
1714
  }
1715
+ /** Every thread of a channel, each with its first and newest message where the API sends them (`threadPage`). */
1555
1716
  async function threadsOf(who, channel, filters, signal) {
1556
1717
  const label = indexed(filters);
1557
- return all(who, await onBoard(who, "/threads"), "threads", {
1558
- channelId: channel.id,
1559
- label
1560
- }, signal);
1718
+ const path = await onBoard(who, "/threads");
1719
+ const out = [];
1720
+ let cursor;
1721
+ do {
1722
+ const page = await threadPage(who, path, {
1723
+ channelId: channel.id,
1724
+ label,
1725
+ cursor
1726
+ }, signal);
1727
+ out.push(...page.threads);
1728
+ cursor = page.cursor ?? void 0;
1729
+ } while (cursor);
1730
+ return out;
1731
+ }
1732
+ /**
1733
+ * A thread's messages when its list brought them all: its first, and its newest when that's its
1734
+ * second. Most threads are a post or a post and a reply, and reading one of those costs nothing
1735
+ * more. Null for a longer one, or from an API that lists threads without their messages.
1736
+ */
1737
+ function whole(thread) {
1738
+ const root = thread.rootMessage;
1739
+ if (!root || root.sequence !== 1) return null;
1740
+ if (thread.messageCount === 1) return [root];
1741
+ const latest = thread.latestMessage;
1742
+ return thread.messageCount === 2 && latest?.sequence === 2 ? [root, latest] : null;
1561
1743
  }
1562
1744
  /** Whether the API lists threads with their first and newest messages (`include=messages`): until it refuses the parameter, it's asked. */
1563
1745
  let threadsWithMessages = true;
@@ -1608,6 +1790,69 @@ function createVercel(options, environment) {
1608
1790
  return out;
1609
1791
  }
1610
1792
  /**
1793
+ * A page's `older` on this board, for `channel`: the API's thread cursor, base64url JSON whose `scope` names the
1794
+ * channel, then `~<shown>` when the page stopped inside the API's. Anything else was never one: 400 `invalid_cursor`.
1795
+ */
1796
+ function olderIn(before, channel) {
1797
+ const refused = new HttpError(400, "invalid_cursor", `before isn't a page of #${channel.name}'s threads: pass a page's older as it came`);
1798
+ const found = /^([A-Za-z0-9_-]*)(?:~(\d{1,6}))?$/.exec(before);
1799
+ if (!found || !found[1] && found[2] === void 0) throw refused;
1800
+ if (found[1]) {
1801
+ let scope;
1802
+ try {
1803
+ const bytes = Uint8Array.from(atob(found[1].replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
1804
+ scope = JSON.parse(new TextDecoder().decode(bytes))?.scope;
1805
+ } catch {
1806
+ throw refused;
1807
+ }
1808
+ if (typeof scope !== "string" || !scope.split("#").includes(channel.id)) throw refused;
1809
+ }
1810
+ return {
1811
+ cursor: found[1] || void 0,
1812
+ skip: Number(found[2] ?? 0)
1813
+ };
1814
+ }
1815
+ /**
1816
+ * A channel's threads last active before `before`, a page's `older` (from the newest without it), newest first:
1817
+ * at most `limit`, and with `before` at most one of the API's pages, whose cursor is the `older` it answers.
1818
+ * A page cut short at `limit` answers its own cursor with how many of its threads were shown (`<cursor>~4`), so
1819
+ * the next read picks up where it stopped.
1820
+ */
1821
+ async function threadsBefore(who, channel, before, limit, signal) {
1822
+ const path = await onBoard(who, "/threads");
1823
+ let { cursor, skip } = before === void 0 ? {
1824
+ cursor: void 0,
1825
+ skip: 0
1826
+ } : olderIn(before, channel);
1827
+ const out = [];
1828
+ do {
1829
+ const found = await threadPage(who, path, {
1830
+ channelId: channel.id,
1831
+ label: void 0,
1832
+ cursor
1833
+ }, signal).catch((error) => {
1834
+ if (error instanceof HttpError && error.status === 400 && error.code === "invalid_cursor") throw new HttpError(400, "invalid_cursor", `before isn't a page of #${channel.name}'s threads: pass a page's older as it came`);
1835
+ throw error;
1836
+ });
1837
+ const fresh = found.threads.slice(skip);
1838
+ const room = limit - out.length;
1839
+ if (fresh.length > room) {
1840
+ out.push(...fresh.slice(0, room));
1841
+ return {
1842
+ threads: out,
1843
+ older: `${cursor ?? ""}~${skip + room}`
1844
+ };
1845
+ }
1846
+ out.push(...fresh);
1847
+ skip = 0;
1848
+ cursor = found.cursor ?? void 0;
1849
+ } while (cursor && before === void 0 && out.length < limit);
1850
+ return {
1851
+ threads: out,
1852
+ older: cursor ?? null
1853
+ };
1854
+ }
1855
+ /**
1611
1856
  * A page of threads as their summaries: each thread's first and newest messages as its thread list brought them,
1612
1857
  * or read by reference from an API that lists threads without them, then every author on the page is asked for
1613
1858
  * together, before any is named.
@@ -1665,12 +1910,23 @@ function createVercel(options, environment) {
1665
1910
  }
1666
1911
  return { profile: named(caller.self ?? "client") };
1667
1912
  }
1913
+ /**
1914
+ * The channel a post landed in, by name. A new post is in the one it named. Only a retried post ID may have landed in
1915
+ * another one, which a whole answer names by ID; a channel it may only post in it can't list, so it keeps the one it named.
1916
+ */
1917
+ async function landedIn(who, channelId, name, clientId) {
1918
+ if (channelId === void 0) return name;
1919
+ if (clientId !== void 0 && posted.get(channelId) !== name) return channelById(who, channelId).then((channel) => (posted.set(channelId, channel.name), channel.name), () => name);
1920
+ posted.set(channelId, name);
1921
+ return name;
1922
+ }
1668
1923
  /** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
1669
1924
  const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
1670
1925
  /** Messages a read covers, newest last: every thread's in the channels it names, or one thread's. */
1671
1926
  async function collect(who, filters, signal) {
1672
1927
  let listed;
1673
1928
  let threads;
1929
+ let feeds;
1674
1930
  if (filters.re !== void 0) {
1675
1931
  const found = await messageIn(who, filters.re, signal).catch((error) => {
1676
1932
  if (error instanceof HttpError && error.status === 404) return null;
@@ -1692,19 +1948,20 @@ function createVercel(options, environment) {
1692
1948
  thread: found.thread,
1693
1949
  channel
1694
1950
  }];
1951
+ feeds = await heads(who, listed);
1695
1952
  } else {
1696
1953
  listed = await channelsFor(who, filters.channel);
1954
+ feeds = await heads(who, listed);
1697
1955
  threads = (await Promise.all(listed.map(async (channel) => (await threadsOf(who, channel, filters, signal)).map((thread) => ({
1698
1956
  thread,
1699
1957
  channel
1700
1958
  }))))).flat();
1701
1959
  }
1702
- const feeds = await heads(who, listed);
1703
1960
  const narrow = await narrowOf(who, filters);
1704
1961
  let newest = 0;
1705
1962
  const messages = [];
1706
1963
  for (const { thread, channel } of threads) {
1707
- const all = await threadMessages(who, thread.id, signal);
1964
+ const all = whole(thread) ?? await threadMessages(who, thread.id, signal);
1708
1965
  const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
1709
1966
  for (const message of all) {
1710
1967
  newest = Math.max(newest, message.createdAt);
@@ -1758,8 +2015,9 @@ function createVercel(options, environment) {
1758
2015
  newest: Math.max(0, ...pages.flatMap((page) => page.messages.map((message) => message.createdAt)))
1759
2016
  };
1760
2017
  }
1761
- /** A change in the API's feed as a board event, with the message as it is now. Null for what isn't a message's. */
2018
+ /** A change in the API's feed as a board event, with the message as it is now. Null for what's neither a message's nor a task's. */
1762
2019
  async function eventOf(who, change, channel, cursor, filters, narrow, given, threads = threadReader(who)) {
2020
+ if (change.type.startsWith("task.")) return taskEventOf(who, change, channel, cursor, filters, narrow, given);
1763
2021
  if (!change.messageId || !change.type.startsWith("message.")) return null;
1764
2022
  let found = given ?? await messageById(who, change.messageId).catch((error) => {
1765
2023
  if (error instanceof HttpError && error.status === 404) return null;
@@ -1867,7 +2125,7 @@ function createVercel(options, environment) {
1867
2125
  const events = page.events.map((change, i) => ({
1868
2126
  change,
1869
2127
  i
1870
- })).slice(skip).filter(({ change }) => from || change.createdAt > position.t);
2128
+ })).slice(skip).filter(({ change }) => from || change.createdAt > position.t).filter(({ change }) => !(position.floor !== void 0 && change.createdAt <= position.floor) && !(change.type === "message.posted" && change.messageId === position.past));
1871
2129
  return {
1872
2130
  channel,
1873
2131
  at: from?.at ?? null,
@@ -1884,6 +2142,10 @@ function createVercel(options, environment) {
1884
2142
  }))).sort((a, b) => a.change.createdAt - b.change.createdAt);
1885
2143
  const events = [];
1886
2144
  naming(who, merged.flatMap(({ change }) => [change.actor, ...change.currentMessage ? [change.currentMessage.createdBy] : []]));
2145
+ const start = {
2146
+ ...position.past !== void 0 ? { past: position.past } : {},
2147
+ ...position.floor !== void 0 ? { floor: position.floor } : {}
2148
+ };
1887
2149
  for (const { change, i, page } of merged) {
1888
2150
  running[page.channel.id] = {
1889
2151
  at: page.at,
@@ -1896,7 +2158,8 @@ function createVercel(options, environment) {
1896
2158
  } : void 0;
1897
2159
  const event = await eventOf(who, change, page.channel.name, cursorOf({
1898
2160
  t: change.createdAt,
1899
- feeds: { ...running }
2161
+ feeds: { ...running },
2162
+ ...start
1900
2163
  }), filters, narrow, given, threads);
1901
2164
  if (event) events.push(event);
1902
2165
  }
@@ -1909,7 +2172,8 @@ function createVercel(options, environment) {
1909
2172
  events,
1910
2173
  position: {
1911
2174
  t: Math.max(position.t, ...merged.map(({ change }) => change.createdAt)),
1912
- feeds: after
2175
+ feeds: after,
2176
+ ...start
1913
2177
  }
1914
2178
  };
1915
2179
  }
@@ -2045,10 +2309,7 @@ function createVercel(options, environment) {
2045
2309
  let position = query.after === void 0 ? {
2046
2310
  t: Date.now(),
2047
2311
  feeds: await heads(who, listed)
2048
- } : locate(query.after) ? {
2049
- t: await timeOf(who, query.after),
2050
- feeds: {}
2051
- } : positionOf(query.after);
2312
+ } : locate(query.after) ? await afterMessage(who, query.after) : positionOf(query.after);
2052
2313
  const until = Date.now() + (query.wait ?? 0) * 1e3;
2053
2314
  let busy = false;
2054
2315
  for (;;) {
@@ -2490,6 +2751,277 @@ function createVercel(options, environment) {
2490
2751
  });
2491
2752
  throw error;
2492
2753
  };
2754
+ /**
2755
+ * What the API refused of a task, as a board says it: its codes with a board's statuses, and a
2756
+ * thread that isn't there as the message it is here. A lost claim keeps the API's word for why, in
2757
+ * its message.
2758
+ */
2759
+ function taskRefusal(error, about = {}) {
2760
+ if (!(error instanceof HttpError)) return error;
2761
+ const { code, message } = error;
2762
+ if (code === "thread_not_found") return notFound(`message not found: ${about.id ?? "that task"}`, "message_not_found");
2763
+ if (code === "not_a_task") return notFound(message, "not_a_task");
2764
+ if (code === "message_deleted") return badRequest(message, "message_deleted");
2765
+ if (code === "bad_request" || code === "invalid_for") return badRequest(message);
2766
+ if (code === "invalid_needs" || code === "reserved_label") return badRequest(message, code);
2767
+ if (code === "task_not_owned") return new HttpError(403, code, message);
2768
+ if (code === "claim_lost") {
2769
+ const reason = reasons.get(error);
2770
+ return new HttpError(409, "claim_lost", `this claim on ${about.id ?? "the task"} is over${reason ? ` (${reason})` : ""}: claim it again`);
2771
+ }
2772
+ if (TASK_CONFLICTS.has(code)) return new HttpError(409, code, message);
2773
+ return error;
2774
+ }
2775
+ /** One write to a task route, `/tasks` and `path` after it, with an operation ID of its own. */
2776
+ async function taskWrite(who, path, body, about = {}) {
2777
+ try {
2778
+ return await api(who, "POST", await onBoard(who, `/tasks${path}`), {
2779
+ version: 2,
2780
+ body: {
2781
+ operationId: operationId(),
2782
+ ...body
2783
+ },
2784
+ ...about.signal ? { signal: about.signal } : {}
2785
+ });
2786
+ } catch (error) {
2787
+ throw taskRefusal(error, about);
2788
+ }
2789
+ }
2790
+ /**
2791
+ * The task a board's ID names, as a task route's path takes it after `/tasks`: the API names a task by its thread,
2792
+ * and a board by its root. A reply names no task, so one that's there is 404 `not_a_task`, as on any board, and
2793
+ * nothing is asked of its thread.
2794
+ */
2795
+ async function taskPath(who, id, signal) {
2796
+ const at = locate(id);
2797
+ if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
2798
+ if (at.sequence !== 1) {
2799
+ await messageById(who, id, signal);
2800
+ throw notFound(`${id} isn't a task`, "not_a_task");
2801
+ }
2802
+ return `/${encodeURIComponent(at.threadId)}`;
2803
+ }
2804
+ /** A task's first message with the task on it, as a board's root carries it. */
2805
+ const firstOf = ({ id: _id, channelId: _channel, message, messageCount: _count, lastActivityAt: _at, lastMessage: _last, ...task }) => ({
2806
+ ...message,
2807
+ task
2808
+ });
2809
+ /** A task as a thread list brings a thread with its messages: its first message on it, which carries the task. */
2810
+ const listedOf = (task) => ({
2811
+ id: task.id,
2812
+ channelId: task.channelId,
2813
+ messageCount: task.messageCount,
2814
+ lastActivityAt: task.lastActivityAt,
2815
+ ...task.lastMessage ? { lastMessage: task.lastMessage } : {},
2816
+ createdAt: task.message.createdAt,
2817
+ createdBy: task.message.createdBy,
2818
+ rootMessage: firstOf(task)
2819
+ });
2820
+ /** A task's root as board shows it, from what a task route answered. */
2821
+ const rootOf = async (who, made) => view(who, firstOf(made.task), (await channelById(who, made.task.channelId)).name);
2822
+ /** What a claim answers once: the epoch and the end the API gave it, with the token this backend made for it. */
2823
+ function claimOf({ task }, token) {
2824
+ if (!task.claim) throw new HttpError(502, "remote_error", "Vercel's API answered a claim without one");
2825
+ return {
2826
+ epoch: task.epoch,
2827
+ token,
2828
+ until: iso(task.claim.until)
2829
+ };
2830
+ }
2831
+ /** What a claim's own write carries there: its token, as the API takes one, and its epoch. */
2832
+ const proofOf = async (proof) => ({
2833
+ claimToken: await sendableToken(proof.token),
2834
+ epoch: proof.epoch
2835
+ });
2836
+ /** The threads the tasks `refs` name: each a root's ID. Anything else is no task, as a task nobody can read is. */
2837
+ function needsOf(refs) {
2838
+ const threads = /* @__PURE__ */ new Set();
2839
+ for (const ref of refs) {
2840
+ const at = locate(ref);
2841
+ if (!at || at.sequence !== 1) throw badRequest(`needs: ${ref} isn't a task`, "invalid_needs");
2842
+ threads.add(at.threadId);
2843
+ }
2844
+ return [...threads];
2845
+ }
2846
+ /**
2847
+ * What makes a thread a task, as the API takes it: the token is this backend's, for a claim made in the same write.
2848
+ * Whom it's for is the API's to check, one of its owner's profiles, as on any board.
2849
+ */
2850
+ const taskSpec = (input, token) => ({
2851
+ ...input.needs?.length ? { needs: needsOf(input.needs) } : {},
2852
+ ...input.for ? { for: input.for } : {},
2853
+ ...token ? { claim: {
2854
+ claimToken: token,
2855
+ leaseSeconds: input.lease ?? 900
2856
+ } } : {}
2857
+ });
2858
+ /**
2859
+ * A task as a caller that may post but not read gets it back from a retry: the API answers its ID alone, so the task
2860
+ * is what was asked for. It waits when it names tasks to wait for, which the API checked, and no one holds it: a
2861
+ * claim takes `label`, which reads.
2862
+ */
2863
+ const askedTask = (owner, by, input) => ({
2864
+ state: input.needs?.length ? "waiting" : "ready",
2865
+ owner,
2866
+ by,
2867
+ for: input.for ?? null,
2868
+ needs: input.needs?.length ? needsOf(input.needs) : [],
2869
+ epoch: 0,
2870
+ claim: null,
2871
+ blocked: null,
2872
+ result: null,
2873
+ reason: null
2874
+ });
2875
+ /** Who a handle or an ID names, as IDs: an ID names itself, whether or not the board has seen it write. */
2876
+ async function idsNamed(who, value) {
2877
+ if (isId(value)) return /* @__PURE__ */ new Set([value]);
2878
+ const read = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : readNames(who);
2879
+ return new Set(goingBy(await read.views, await namesIn(read), value.toLowerCase()));
2880
+ }
2881
+ /**
2882
+ * A task's change in the API's feed as the board's event, built from the task as it was right
2883
+ * after it. It's delivered when its root matched the filters before the change or after it, as a
2884
+ * label's change is on any board: `board.task` is the label a task's change moves.
2885
+ */
2886
+ async function taskEventOf(who, change, channel, cursor, filters, narrow, given) {
2887
+ const type = TASK_EVENTS[change.type];
2888
+ if (!type || !change.messageId || type === "task.renewed" && !filters.all) return null;
2889
+ const found = given ?? await messageById(who, change.messageId).catch((error) => {
2890
+ if (error instanceof HttpError && error.status === 404) return null;
2891
+ throw error;
2892
+ });
2893
+ const task = change.task ?? found?.message.task;
2894
+ if (!found || !task || found.message.sequence !== 1) return null;
2895
+ const wearing = (own, state) => {
2896
+ const { [TASK_LABEL]: _state, ...rest } = own;
2897
+ return state === void 0 ? rest : {
2898
+ ...rest,
2899
+ [TASK_LABEL]: state
2900
+ };
2901
+ };
2902
+ const moved = change.labels?.[TASK_LABEL];
2903
+ const as = (labels) => ({
2904
+ message: {
2905
+ ...found.message,
2906
+ task,
2907
+ labels
2908
+ },
2909
+ thread: {
2910
+ ...found.thread,
2911
+ labels
2912
+ }
2913
+ });
2914
+ const after = as(found.message.deletedAt !== void 0 ? {} : wearing(labelsOf(found.message), task.state));
2915
+ const kept = { ...found.message.labels };
2916
+ const then = [as(wearing(kept, task.state)), ...moved ? [as(wearing(kept, moved.from))] : []];
2917
+ let matched = false;
2918
+ for (const { message, thread } of then) matched ||= await matches(filters, message, thread, narrow);
2919
+ if (!matched) return null;
2920
+ const message = await view(who, after.message, channel);
2921
+ const by = authorOf(change.actor);
2922
+ const base = {
2923
+ id: message.id,
2924
+ thread: message.thread
2925
+ };
2926
+ const claimed = {
2927
+ epoch: task.epoch,
2928
+ until: iso(task.claim?.until ?? change.createdAt)
2929
+ };
2930
+ let payload;
2931
+ switch (type) {
2932
+ case "task.created":
2933
+ payload = {
2934
+ ...base,
2935
+ needs: message.task.needs,
2936
+ for: task.for,
2937
+ by
2938
+ };
2939
+ break;
2940
+ case "task.assigned":
2941
+ payload = {
2942
+ ...base,
2943
+ for: task.for,
2944
+ by
2945
+ };
2946
+ break;
2947
+ case "task.needs_changed":
2948
+ payload = {
2949
+ ...base,
2950
+ needs: message.task.needs,
2951
+ by
2952
+ };
2953
+ break;
2954
+ case "task.claimed":
2955
+ case "task.renewed":
2956
+ payload = {
2957
+ ...base,
2958
+ ...claimed,
2959
+ by
2960
+ };
2961
+ break;
2962
+ case "task.released":
2963
+ payload = {
2964
+ ...base,
2965
+ epoch: task.epoch,
2966
+ by
2967
+ };
2968
+ break;
2969
+ case "task.completed":
2970
+ payload = {
2971
+ ...base,
2972
+ epoch: task.epoch,
2973
+ result: task.result,
2974
+ by
2975
+ };
2976
+ break;
2977
+ case "task.failed":
2978
+ payload = {
2979
+ ...base,
2980
+ epoch: task.epoch,
2981
+ reason: task.reason,
2982
+ by
2983
+ };
2984
+ break;
2985
+ case "task.blocked":
2986
+ payload = {
2987
+ ...base,
2988
+ kind: task.blocked?.kind ?? null,
2989
+ reason: task.blocked?.reason ?? "",
2990
+ by
2991
+ };
2992
+ break;
2993
+ case "task.canceled":
2994
+ payload = {
2995
+ ...base,
2996
+ reason: task.reason,
2997
+ by
2998
+ };
2999
+ break;
3000
+ case "task.unblocked":
3001
+ case "task.reopened":
3002
+ payload = {
3003
+ ...base,
3004
+ by
3005
+ };
3006
+ break;
3007
+ case "task.expired":
3008
+ payload = {
3009
+ ...base,
3010
+ epoch: task.epoch
3011
+ };
3012
+ break;
3013
+ default: payload = base;
3014
+ }
3015
+ const own = type === "task.expired" || type === "task.ready";
3016
+ return {
3017
+ cursor,
3018
+ type,
3019
+ createdAt: iso(change.createdAt),
3020
+ payload,
3021
+ message,
3022
+ ...own ? {} : { actor: await nameOf(who, change.actor) }
3023
+ };
3024
+ }
2493
3025
  const methods = {
2494
3026
  ...Object.fromEntries(METHODS.map((method) => [method, async () => {
2495
3027
  throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
@@ -2641,7 +3173,27 @@ function createVercel(options, environment) {
2641
3173
  const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
2642
3174
  return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
2643
3175
  };
2644
- if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0) {
3176
+ const byMessage = query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0;
3177
+ if (query.channel !== void 0 && !query.channel.endsWith("/") && !byMessage && !query.label?.length && after === void 0) {
3178
+ const listed = await channelsFor(who, query.channel);
3179
+ const feeds = await heads(who, listed);
3180
+ const found = await Promise.all(listed.map((channel) => threadsBefore(who, channel, query.before, limit, signal)));
3181
+ const page = listed.flatMap((channel, i) => found[i].threads.map((thread) => ({
3182
+ thread,
3183
+ channel,
3184
+ at: thread.lastActivityAt
3185
+ }))).reverse();
3186
+ return {
3187
+ threads: await summaries(who, page, signal),
3188
+ cursor: cursorOf({
3189
+ t: page.reduce((max, { at }) => Math.max(max, at), 0),
3190
+ feeds
3191
+ }),
3192
+ older: found[0]?.older ?? null
3193
+ };
3194
+ }
3195
+ if (query.before !== void 0) throw new HttpError(400, "invalid_request", "before: this board pages one channel's threads, with no filters");
3196
+ if (byMessage) {
2645
3197
  const { messages, feeds, newest } = await collect(who, query, signal);
2646
3198
  const latest = /* @__PURE__ */ new Map();
2647
3199
  for (const { message, thread, channel } of messages) latest.set(thread.id, {
@@ -2827,11 +3379,7 @@ function createVercel(options, environment) {
2827
3379
  }
2828
3380
  made = reply;
2829
3381
  }
2830
- const channelId = made.thread.channelId;
2831
- if (channelId !== void 0) {
2832
- if (clientId !== void 0 && posted.get(channelId) !== channelName) channelName = await channelById(who, channelId).then((channel) => (posted.set(channelId, channel.name), channel.name), () => channelName);
2833
- else posted.set(channelId, channelName);
2834
- }
3382
+ channelName = await landedIn(who, made.thread.channelId, channelName, clientId);
2835
3383
  return { message: await view(who, "text" in made.message ? made.message : await sent(who, made.message, input), channelName) };
2836
3384
  },
2837
3385
  async posted(caller, { id }, signal) {
@@ -3027,6 +3575,389 @@ function createVercel(options, environment) {
3027
3575
  canceled
3028
3576
  };
3029
3577
  },
3578
+ async tasks(caller, query, signal) {
3579
+ const who = whoOf(caller);
3580
+ const limit = query.limit ?? 50;
3581
+ let after;
3582
+ if (query.after !== void 0 && query.after !== TASKS_START) {
3583
+ const at = locate(query.after);
3584
+ if (!at) throw new HttpError(400, "invalid_cursor", `${query.after} isn't a cursor or a message ID on this board`);
3585
+ after = at.threadId;
3586
+ }
3587
+ const none = {
3588
+ tasks: [],
3589
+ cursor: query.after ?? TASKS_START
3590
+ };
3591
+ const needed = query.needs === void 0 ? void 0 : locate(query.needs);
3592
+ if (needed === null || needed !== void 0 && needed.sequence !== 1) return none;
3593
+ const by = await byOf(who, query.by);
3594
+ const owners = query.owner === void 0 ? null : await idsNamed(who, query.owner);
3595
+ const assignees = query.for === void 0 ? null : await idsNamed(who, query.for);
3596
+ const labels = query.label ?? [];
3597
+ const matching = (task) => {
3598
+ if (owners && !owners.has(task.owner)) return false;
3599
+ if (assignees && !(task.for !== null && assignees.has(task.for))) return false;
3600
+ if (by && !by(task.message.createdBy)) return false;
3601
+ const wears = task.message.labels;
3602
+ return labels.every(([key, values]) => wears !== void 0 && Object.hasOwn(wears, key) && (values === null || values.includes(wears[key])));
3603
+ };
3604
+ const asked = {
3605
+ state: query.state ?? "open",
3606
+ channel: query.channel,
3607
+ label: labels.map(([key, values]) => values === null || values.length !== 1 ? key : `${key}=${values[0]}`),
3608
+ owner: query.owner !== void 0 && isId(query.owner) ? query.owner : void 0,
3609
+ for: query.for !== void 0 && isId(query.for) ? query.for : void 0,
3610
+ needs: needed?.threadId
3611
+ };
3612
+ const path = await onBoard(who, "/tasks");
3613
+ const found = [];
3614
+ let from = after !== void 0 ? { after } : {};
3615
+ while (found.length < limit) {
3616
+ const page = await api(who, "GET", path, {
3617
+ version: 2,
3618
+ query: {
3619
+ ...asked,
3620
+ ...from
3621
+ },
3622
+ signal
3623
+ }).catch((error) => {
3624
+ throw taskRefusal(error);
3625
+ });
3626
+ for (const task of page.tasks) if (found.length < limit && matching(task)) found.push(task);
3627
+ if (!page.cursor) break;
3628
+ from = { cursor: page.cursor };
3629
+ }
3630
+ const tasks = await summaries(who, await Promise.all(found.map(async (task) => ({
3631
+ thread: listedOf(task),
3632
+ channel: await channelById(who, task.channelId)
3633
+ }))), signal);
3634
+ const last = found.at(-1);
3635
+ return {
3636
+ tasks,
3637
+ cursor: last ? idAt(last.id, 1) : none.cursor
3638
+ };
3639
+ },
3640
+ async createTask(caller, input, signal) {
3641
+ const who = whoOf(caller);
3642
+ const token = input.claim ? newClaimToken() : null;
3643
+ const spec = taskSpec(input, token);
3644
+ let made;
3645
+ let root;
3646
+ let task;
3647
+ if (input.re !== void 0) {
3648
+ const at = locate(input.re);
3649
+ if (!at) throw notFound(`message not found: ${input.re}`, "message_not_found");
3650
+ if (at.sequence !== 1) {
3651
+ await messageById(who, input.re, signal);
3652
+ throw badRequest(`${input.re} is a reply: a task is a thread, so name its root, ${idAt(at.threadId, 1)}`);
3653
+ }
3654
+ const adopted = await taskWrite(who, "", {
3655
+ threadId: at.threadId,
3656
+ ...spec
3657
+ }, {
3658
+ id: input.re,
3659
+ signal
3660
+ });
3661
+ made = adopted;
3662
+ task = adopted.task;
3663
+ root = await rootOf(who, adopted);
3664
+ } else {
3665
+ const clientId = input.id !== void 0 ? await clientIdOf(input.id) : void 0;
3666
+ const text = input.text ?? "";
3667
+ made = await taskWrite(who, "", {
3668
+ channel: input.channel,
3669
+ text,
3670
+ ...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
3671
+ ...clientId ? { clientId } : {},
3672
+ ...input.attachments?.length ? { attachments: input.attachments } : {},
3673
+ ...input.noSync ? { noSync: true } : {},
3674
+ ...spec
3675
+ }, { signal }).catch((error) => {
3676
+ if (error instanceof HttpError && error.code === "not_a_task") throw duplicateId();
3677
+ throw error;
3678
+ });
3679
+ if ("message" in made.task) {
3680
+ task = made.task;
3681
+ root = await view(who, firstOf(made.task), await landedIn(who, made.task.channelId, input.channel, clientId));
3682
+ } else {
3683
+ const { actor } = await self(who);
3684
+ task = askedTask(principalId(actor.principal), await actorOf(who), input);
3685
+ root = await view(who, {
3686
+ ...await sent(who, {
3687
+ id: idAt(made.task.id, 1),
3688
+ threadId: made.task.id,
3689
+ sequence: 1
3690
+ }, {
3691
+ text,
3692
+ labels: {
3693
+ ...input.labels,
3694
+ [TASK_LABEL]: task.state
3695
+ },
3696
+ attachments: input.attachments,
3697
+ noSync: input.noSync
3698
+ }),
3699
+ task
3700
+ }, input.channel);
3701
+ }
3702
+ }
3703
+ if (!token || made.claimed !== true || !task.claim) return { task: root };
3704
+ return {
3705
+ task: root,
3706
+ claim: {
3707
+ epoch: task.epoch,
3708
+ token,
3709
+ until: iso(task.claim.until)
3710
+ }
3711
+ };
3712
+ },
3713
+ async createTasks(caller, input, signal) {
3714
+ const who = whoOf(caller);
3715
+ const waits = input.tasks.map((task) => {
3716
+ const keys = [...new Set((task.needs ?? []).flatMap((need) => typeof need === "string" ? [] : [need.key]))];
3717
+ return {
3718
+ threads: needsOf((task.needs ?? []).filter((need) => typeof need === "string")),
3719
+ keys
3720
+ };
3721
+ });
3722
+ const tasks = input.tasks.map((task, at) => {
3723
+ const needs = [...waits[at].threads, ...waits[at].keys.map((key) => ({ key }))];
3724
+ return {
3725
+ ...task.key !== void 0 ? { key: task.key } : {},
3726
+ text: task.text,
3727
+ ...task.labels && Object.keys(task.labels).length ? { labels: task.labels } : {},
3728
+ ...task.noSync ? { noSync: true } : {},
3729
+ ...task.attachments?.length ? { attachments: task.attachments } : {},
3730
+ ...needs.length ? { needs } : {},
3731
+ ...task.for ? { for: task.for } : {}
3732
+ };
3733
+ });
3734
+ const body = {
3735
+ operationId: operationId(),
3736
+ channel: input.channel,
3737
+ ...input.id !== void 0 ? { idempotencyKey: input.id } : {},
3738
+ tasks
3739
+ };
3740
+ const made = await api(who, "POST", await onBoard(who, "/tasks/batch"), {
3741
+ version: 2,
3742
+ body,
3743
+ signal
3744
+ }).catch((error) => {
3745
+ if (error instanceof HttpError && error.code === "idempotency_key_reused") throw duplicateId();
3746
+ if (error instanceof HttpError && error.code === "entity_too_large") throw new HttpError(400, "batch_too_large", error.message);
3747
+ throw taskRefusal(error);
3748
+ });
3749
+ const threads = made.tasks.map((task) => task.id);
3750
+ const places = new Map(input.tasks.flatMap((task, at) => task.key !== void 0 ? [[task.key, at]] : []));
3751
+ return { tasks: await Promise.all(made.tasks.map(async (task, at) => {
3752
+ if ("message" in task) return view(who, firstOf(task), await landedIn(who, task.channelId, input.channel, void 0));
3753
+ const asked = input.tasks[at];
3754
+ const needs = [...waits[at].threads, ...waits[at].keys.map((key) => threads[places.get(key)])];
3755
+ const { actor } = await self(who);
3756
+ const stood = {
3757
+ state: needs.length ? "waiting" : "ready",
3758
+ owner: principalId(actor.principal),
3759
+ by: await actorOf(who),
3760
+ for: asked.for ?? null,
3761
+ needs,
3762
+ epoch: 0,
3763
+ claim: null,
3764
+ blocked: null,
3765
+ result: null,
3766
+ reason: null
3767
+ };
3768
+ const first = {
3769
+ id: idAt(task.id, 1),
3770
+ threadId: task.id,
3771
+ sequence: 1
3772
+ };
3773
+ return view(who, {
3774
+ ...await sent(who, first, {
3775
+ text: asked.text,
3776
+ labels: {
3777
+ ...asked.labels,
3778
+ [TASK_LABEL]: stood.state
3779
+ },
3780
+ attachments: asked.attachments,
3781
+ noSync: asked.noSync
3782
+ }),
3783
+ task: stood
3784
+ }, input.channel);
3785
+ })) };
3786
+ },
3787
+ async createdTasks(_caller, { id }) {
3788
+ throw notFound(`no batch of yours has id ${id}`, "batch_not_found");
3789
+ },
3790
+ async claimTask(caller, { id, lease }, signal) {
3791
+ const who = whoOf(caller);
3792
+ const token = newClaimToken();
3793
+ const made = await taskWrite(who, `${await taskPath(who, id, signal)}/claim`, {
3794
+ claimToken: token,
3795
+ leaseSeconds: lease ?? 900
3796
+ }, {
3797
+ id,
3798
+ signal
3799
+ });
3800
+ return {
3801
+ task: await rootOf(who, made),
3802
+ claim: claimOf(made, token)
3803
+ };
3804
+ },
3805
+ async claimReadyTask(caller, input, signal) {
3806
+ const who = whoOf(caller);
3807
+ for (const owner of input.from ?? []) if (!isId(owner)) throw badRequest(`from: ${owner} is a handle, which several can share: name the owner by ID`, "invalid_from");
3808
+ if (signal.aborted) return { task: null };
3809
+ const path = await onBoard(who, "/tasks/claim");
3810
+ const wait = Math.min(WAIT_MAX_S, Math.ceil(input.wait ?? 0));
3811
+ const token = newClaimToken();
3812
+ const body = {
3813
+ operationId: operationId(),
3814
+ claimToken: token,
3815
+ channel: input.channel,
3816
+ ...input.label && Object.keys(input.label).length ? { labels: input.label } : {},
3817
+ ...input.from?.length ? { from: input.from } : {},
3818
+ leaseSeconds: input.lease ?? 900,
3819
+ ...wait > 0 ? { wait } : {}
3820
+ };
3821
+ const release = async (found) => {
3822
+ if (found.task) await taskWrite(who, `/${encodeURIComponent(found.task.id)}/release`, {
3823
+ claimToken: token,
3824
+ epoch: found.task.epoch
3825
+ }).catch(() => {});
3826
+ };
3827
+ let found;
3828
+ try {
3829
+ found = await api(who, "POST", path, {
3830
+ version: 2,
3831
+ body,
3832
+ signal
3833
+ });
3834
+ } catch (error) {
3835
+ if (signal.aborted) {
3836
+ const { wait: _held, ...again } = body;
3837
+ waitUntil(api(who, "POST", path, {
3838
+ version: 2,
3839
+ body: again
3840
+ }).then(release, () => {}));
3841
+ return { task: null };
3842
+ }
3843
+ throw taskRefusal(error);
3844
+ }
3845
+ const { task } = found;
3846
+ if (!task) return { task: null };
3847
+ if (signal.aborted) {
3848
+ await release(found);
3849
+ return { task: null };
3850
+ }
3851
+ return {
3852
+ task: await rootOf(who, { task }),
3853
+ claim: claimOf({ task }, token)
3854
+ };
3855
+ },
3856
+ async renewTask(caller, { id, epoch, token, lease }, signal) {
3857
+ const who = whoOf(caller);
3858
+ const made = await taskWrite(who, `${await taskPath(who, id, signal)}/renew`, {
3859
+ ...await proofOf({
3860
+ epoch,
3861
+ token
3862
+ }),
3863
+ leaseSeconds: lease ?? 900
3864
+ }, {
3865
+ id,
3866
+ signal
3867
+ });
3868
+ return {
3869
+ task: await rootOf(who, made),
3870
+ until: claimOf(made, token).until
3871
+ };
3872
+ },
3873
+ async releaseTask(caller, { id, epoch, token }, signal) {
3874
+ const who = whoOf(caller);
3875
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/release`, await proofOf({
3876
+ epoch,
3877
+ token
3878
+ }), {
3879
+ id,
3880
+ signal
3881
+ })) };
3882
+ },
3883
+ async completeTask(caller, { id, epoch, token, result }, signal) {
3884
+ const who = whoOf(caller);
3885
+ const body = {
3886
+ ...await proofOf({
3887
+ epoch,
3888
+ token
3889
+ }),
3890
+ ...result !== void 0 ? { result } : {}
3891
+ };
3892
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/complete`, body, {
3893
+ id,
3894
+ signal
3895
+ })) };
3896
+ },
3897
+ async failTask(caller, { id, epoch, token, reason }, signal) {
3898
+ const who = whoOf(caller);
3899
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/fail`, {
3900
+ ...await proofOf({
3901
+ epoch,
3902
+ token
3903
+ }),
3904
+ reason
3905
+ }, {
3906
+ id,
3907
+ signal
3908
+ })) };
3909
+ },
3910
+ async blockTask(caller, { id, reason, kind, epoch, token }, signal) {
3911
+ const who = whoOf(caller);
3912
+ const proof = epoch !== void 0 && token !== void 0 ? await proofOf({
3913
+ epoch,
3914
+ token
3915
+ }) : null;
3916
+ const body = {
3917
+ reason,
3918
+ ...kind !== void 0 ? { kind } : {},
3919
+ ...proof
3920
+ };
3921
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/block`, body, {
3922
+ id,
3923
+ signal
3924
+ })) };
3925
+ },
3926
+ async unblockTask(caller, { id }, signal) {
3927
+ const who = whoOf(caller);
3928
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/unblock`, {}, {
3929
+ id,
3930
+ signal
3931
+ })) };
3932
+ },
3933
+ async reopenTask(caller, { id }, signal) {
3934
+ const who = whoOf(caller);
3935
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/reopen`, {}, {
3936
+ id,
3937
+ signal
3938
+ })) };
3939
+ },
3940
+ async assignTask(caller, { id, for: actor }, signal) {
3941
+ const who = whoOf(caller);
3942
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/assign`, { for: actor }, {
3943
+ id,
3944
+ signal
3945
+ })) };
3946
+ },
3947
+ async setTaskNeeds(caller, { id, needs }, signal) {
3948
+ const who = whoOf(caller);
3949
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/needs`, { needs: needsOf(needs) }, {
3950
+ id,
3951
+ signal
3952
+ })) };
3953
+ },
3954
+ async cancelTask(caller, { id, reason }, signal) {
3955
+ const who = whoOf(caller);
3956
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/cancel`, { reason }, {
3957
+ id,
3958
+ signal
3959
+ })) };
3960
+ },
3030
3961
  events: (caller, query, signal) => eventsAs(whoOf(caller), query, signal),
3031
3962
  async typing(caller, { id, status }, signal) {
3032
3963
  if (!binding || binding.sync.length === 0) return { targets: [] };
@@ -3242,7 +4173,8 @@ function createVercel(options, environment) {
3242
4173
  const who = { profile: null };
3243
4174
  const team = await teamId();
3244
4175
  const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
3245
- const url = `${origin}/v1/messageboard${await onBoard(who)}?teamId=${encodeURIComponent(id)}`;
4176
+ const board = await onBoard(who);
4177
+ const url = `${origin}/v1/messageboard${board}?teamId=${encodeURIComponent(id)}`;
3246
4178
  return {
3247
4179
  url,
3248
4180
  headers: {
@@ -3251,7 +4183,11 @@ function createVercel(options, environment) {
3251
4183
  "x-board-can": can
3252
4184
  },
3253
4185
  routes: SANDBOX_ROUTES,
3254
- reads: ["/v1/messageboard/me"]
4186
+ reads: ["/v1/messageboard/me"],
4187
+ under: [{
4188
+ path: `/v2/messageboard${board}`,
4189
+ routes: SANDBOX_TASK_ROUTES
4190
+ }]
3255
4191
  };
3256
4192
  },
3257
4193
  sendsSchedulesHere: false,
@@ -3520,9 +4456,19 @@ function avatarSvg(name) {
3520
4456
  const CREATED = /* @__PURE__ */ new Set([
3521
4457
  "post",
3522
4458
  "schedule",
4459
+ "createTask",
4460
+ "createTasks",
3523
4461
  "upload",
3524
4462
  "uploadFinish"
3525
4463
  ]);
4464
+ /**
4465
+ * Refuses a label write under `board.`: those keys are the board's own, which only its task writes
4466
+ * set, so no caller's write sets or unsets one, this deployment's own code included.
4467
+ */
4468
+ function ownLabels(set, unset = []) {
4469
+ const key = [...Object.keys(set ?? {}), ...unset].find((name) => name.startsWith(RESERVED_LABEL_PREFIX));
4470
+ if (key !== void 0) throw new HttpError(400, "reserved_label", `${key} is the board's own label: only its task writes set labels under ${RESERVED_LABEL_PREFIX}`);
4471
+ }
3526
4472
  /** Shown inline only when a browser can't run it: everything else downloads. */
3527
4473
  const INLINE = /^(image\/(png|jpeg|gif|webp|avif)|video\/(mp4|webm)|text\/plain)$/;
3528
4474
  /**
@@ -3558,6 +4504,8 @@ async function inputOf(name, request, url, params) {
3558
4504
  case "posted":
3559
4505
  case "synced":
3560
4506
  case "cancelSchedule":
4507
+ case "unblockTask":
4508
+ case "reopenTask":
3561
4509
  case "revokeGrant":
3562
4510
  case "schema":
3563
4511
  case "attachment":
@@ -3575,6 +4523,55 @@ async function inputOf(name, request, url, params) {
3575
4523
  case "post": return PostBody.parse(await body());
3576
4524
  case "createChannel": return CreateChannelBody.parse(await body());
3577
4525
  case "schedule": return ScheduleBody.parse(await body());
4526
+ case "tasks": return TasksQuery.parse(queryObject(url));
4527
+ case "createTask": return CreateTaskBody.parse(await body());
4528
+ case "createdTasks": return {
4529
+ id,
4530
+ ...CreatedTasksQuery.parse(queryObject(url))
4531
+ };
4532
+ case "createTasks": {
4533
+ const sent = await body();
4534
+ const tasks = sent?.tasks;
4535
+ if (Array.isArray(tasks) && tasks.length > 100) throw batchTooLarge(tasks.length, 100);
4536
+ return CreateTasksBody.parse(sent);
4537
+ }
4538
+ case "claimReadyTask": return ClaimReadyTaskBody.parse(await body());
4539
+ case "claimTask": return {
4540
+ id,
4541
+ ...ClaimTaskBody.parse(await body()) ?? {}
4542
+ };
4543
+ case "renewTask": return {
4544
+ id,
4545
+ ...RenewTaskBody.parse(await body())
4546
+ };
4547
+ case "releaseTask": return {
4548
+ id,
4549
+ ...ReleaseTaskBody.parse(await body())
4550
+ };
4551
+ case "completeTask": return {
4552
+ id,
4553
+ ...CompleteTaskBody.parse(await body())
4554
+ };
4555
+ case "failTask": return {
4556
+ id,
4557
+ ...FailTaskBody.parse(await body())
4558
+ };
4559
+ case "blockTask": return {
4560
+ id,
4561
+ ...BlockTaskBody.parse(await body())
4562
+ };
4563
+ case "assignTask": return {
4564
+ id,
4565
+ ...AssignTaskBody.parse(await body())
4566
+ };
4567
+ case "setTaskNeeds": return {
4568
+ id,
4569
+ ...TaskNeedsBody.parse(await body())
4570
+ };
4571
+ case "cancelTask": return {
4572
+ id,
4573
+ ...CancelTaskBody.parse(await body())
4574
+ };
3578
4575
  case "createGrant": return GrantBody.parse(await body());
3579
4576
  case "updateGrant": return {
3580
4577
  id,
@@ -3844,7 +4841,10 @@ async function createServe(context) {
3844
4841
  author,
3845
4842
  source,
3846
4843
  board: () => middlewareBoard ??= handleOf(MIDDLEWARE, null)
3847
- }, commit);
4844
+ }, (passed) => {
4845
+ if (passed.kind === "post") ownLabels(passed.labels);
4846
+ return commit(passed);
4847
+ });
3848
4848
  /** Whether a lookup found what it looked for: a 404 says it didn't. */
3849
4849
  async function found(lookup) {
3850
4850
  try {
@@ -3903,6 +4903,60 @@ async function createServe(context) {
3903
4903
  }));
3904
4904
  }
3905
4905
  /**
4906
+ * A digest of what a batch asks for, as it was given: its channel and its tasks, as many, in the
4907
+ * same order, each with the same key, text, labels, `noSync`, files, needs, and assignee. A field
4908
+ * left out is its empty value. A batch made under an `id` is that `id`'s only for the same one.
4909
+ */
4910
+ async function batchRequest(body) {
4911
+ const tasks = body.tasks.map((task) => [
4912
+ task.key ?? null,
4913
+ task.text,
4914
+ Object.entries(task.labels ?? {}).sort(([a], [b]) => a < b ? -1 : 1),
4915
+ task.noSync ?? false,
4916
+ task.attachments ?? [],
4917
+ task.needs ?? [],
4918
+ task.for ?? null
4919
+ ]);
4920
+ return (await sha256(JSON.stringify([body.channel, tasks]))).slice(0, 32);
4921
+ }
4922
+ /**
4923
+ * A batch's roots through the middleware, each as the post it is, in order, then `send` with what
4924
+ * it passed on: every one before any is written, so a root it drops makes none of them. A batch
4925
+ * that wouldn't land goes as it came, for the backend to say why. One that landed already never
4926
+ * gets here: its retry is answered before.
4927
+ */
4928
+ async function screenTasks(caller, input, signal, send) {
4929
+ const source = sourceOf(caller);
4930
+ if (middleware.length === 0 || source === null) return send(input.tasks);
4931
+ const { channel } = input;
4932
+ const access = accessOf(caller);
4933
+ const labels = input.tasks.some((task) => Object.keys(task.labels ?? {}).length > 0);
4934
+ if (access && (!access.can("post", channel) || labels && !access.can("label", channel))) return send(input.tasks);
4935
+ const { actor } = await whoIs(caller, signal);
4936
+ const passed = [];
4937
+ const from = async (at) => {
4938
+ const task = input.tasks[at];
4939
+ if (!task) return send(passed);
4940
+ const attachments = await attachmentsOf(caller, task.attachments, signal);
4941
+ return screen({
4942
+ kind: "post",
4943
+ channel,
4944
+ re: null,
4945
+ text: task.text,
4946
+ labels: task.labels ?? {},
4947
+ attachments
4948
+ }, actor, source, (write) => {
4949
+ passed.push({
4950
+ ...task,
4951
+ text: write.text,
4952
+ ...task.labels || Object.keys(write.labels).length > 0 ? { labels: write.labels } : {}
4953
+ });
4954
+ return from(at + 1);
4955
+ });
4956
+ };
4957
+ return from(0);
4958
+ }
4959
+ /**
3906
4960
  * A schedule, on a backend whose sends post elsewhere: its message through the middleware once,
3907
4961
  * as the caller's post of it, since its text and labels never change and no send comes back here.
3908
4962
  */
@@ -3993,6 +5047,8 @@ async function createServe(context) {
3993
5047
  * the platform. A retry of one that landed stands.
3994
5048
  */
3995
5049
  async function syncImport(caller, body, signal) {
5050
+ if (body.op === "post") ownLabels(body.labels);
5051
+ if (body.op === "labels") ownLabels(body.set, body.unset);
3996
5052
  const written = (body.op === "post" || body.op === "edit") && body.from === null ? body.text : null;
3997
5053
  if (written !== null) await checkBlocks(written);
3998
5054
  const send = async (patched) => {
@@ -4210,7 +5266,59 @@ async function createServe(context) {
4210
5266
  /** The protocol method `name`, as board() serves it: what it posts, edits, and imports goes through the middleware. */
4211
5267
  async function invoke(name, caller, input, signal) {
4212
5268
  switch (name) {
4213
- case "post": return post(caller, input, signal);
5269
+ case "post":
5270
+ ownLabels(input.labels);
5271
+ return post(caller, input, signal);
5272
+ case "label": {
5273
+ const { set, unset } = input;
5274
+ ownLabels(set, unset);
5275
+ return backend.label(caller, input, signal);
5276
+ }
5277
+ case "createTask": {
5278
+ const body = input;
5279
+ ownLabels(body.labels);
5280
+ if (body.channel === void 0) return backend.createTask(caller, body, signal);
5281
+ const { channel, labels, noSync, attachments, id } = body;
5282
+ const sent = body.text ?? "";
5283
+ await checkWrite(caller, sent, { channel }, signal);
5284
+ return screenPost(caller, {
5285
+ channel,
5286
+ text: sent,
5287
+ ...labels ? { labels } : {},
5288
+ ...noSync !== void 0 ? { noSync } : {},
5289
+ ...attachments ? { attachments } : {},
5290
+ ...id !== void 0 ? { id } : {}
5291
+ }, signal, async (screened) => {
5292
+ if (screened.text !== sent) await checkBlocks(screened.text);
5293
+ return backend.createTask(caller, {
5294
+ ...body,
5295
+ text: screened.text,
5296
+ ...screened.labels ? { labels: screened.labels } : {}
5297
+ }, signal);
5298
+ });
5299
+ }
5300
+ case "createTasks": {
5301
+ const body = input;
5302
+ for (const task of body.tasks) ownLabels(task.labels);
5303
+ const request = body.id !== void 0 ? body.request ?? await batchRequest(body) : void 0;
5304
+ if (body.id !== void 0) try {
5305
+ return await backend.createdTasks(caller, {
5306
+ id: body.id,
5307
+ request
5308
+ }, signal);
5309
+ } catch (error) {
5310
+ if (!(error instanceof HttpError && error.status === 404 && error.code === "batch_not_found")) throw error;
5311
+ }
5312
+ for (const task of body.tasks) await checkWrite(caller, task.text, { channel: body.channel }, signal);
5313
+ return screenTasks(caller, body, signal, async (tasks) => {
5314
+ for (const [at, task] of tasks.entries()) if (task.text !== body.tasks[at].text) await checkBlocks(task.text);
5315
+ return backend.createTasks(caller, {
5316
+ ...body,
5317
+ tasks,
5318
+ request
5319
+ }, signal);
5320
+ });
5321
+ }
4214
5322
  case "edit": {
4215
5323
  const edit = input;
4216
5324
  await checkWrite(caller, edit.text, { message: edit.id }, signal);
@@ -4222,6 +5330,7 @@ async function createServe(context) {
4222
5330
  case "syncImport": return syncImport(caller, input, signal);
4223
5331
  case "schedule": {
4224
5332
  const body = input;
5333
+ ownLabels(body.labels);
4225
5334
  await checkWrite(caller, body.text, body.channel !== void 0 ? { channel: body.channel } : { message: body.re }, signal);
4226
5335
  return backend.sendsSchedulesHere === false ? screenSchedule(caller, body, signal) : backend.schedule(caller, body, signal);
4227
5336
  }
@@ -4412,9 +5521,10 @@ async function createServe(context) {
4412
5521
  return {
4413
5522
  dispatch,
4414
5523
  async inject(request, caller, trigger, writes) {
4415
- if (trigger !== null && request.method === "POST" && new URL(request.url).pathname.endsWith("/messages")) {
5524
+ const pathname = new URL(request.url).pathname;
5525
+ if (trigger !== null && request.method === "POST" && (pathname.endsWith("/messages") || pathname.endsWith("/tasks") || pathname.endsWith("/tasks/batch"))) {
4416
5526
  const body = await request.json() ?? {};
4417
- body.id ??= await derivedId("board-inbound", trigger, "client", String(writes.made++));
5527
+ if (pathname.endsWith("/messages") || body.channel !== void 0) body.id ??= await derivedId("board-inbound", trigger, "client", String(writes.made++));
4418
5528
  request = new Request(request.url, {
4419
5529
  method: "POST",
4420
5530
  headers: request.headers,
@@ -4672,6 +5782,11 @@ function createBoard(options, runtime) {
4672
5782
  post: async (channel, input) => client.post(channel, await owned(input)),
4673
5783
  reply: async (re, input) => client.reply(re, await owned(input)),
4674
5784
  posted: async (given) => client.posted(await id(given)),
5785
+ tasks: {
5786
+ ...client.tasks,
5787
+ create: (async (target, input) => typeof target === "string" ? client.tasks.create(target, await owned(input)) : client.tasks.create(target, input)),
5788
+ createMany: async (channel, tasks, opts = {}) => client.tasks.createMany(channel, tasks, opts.id !== void 0 ? { id: await id(opts.id) } : opts)
5789
+ },
4675
5790
  request: (path, init = {}) => {
4676
5791
  const { as: profile, ...rest } = init;
4677
5792
  return profile !== void 0 ? asFrom(caller, stop)(profile).request(path, rest) : client.request(path, rest);
@@ -4807,4 +5922,73 @@ async function* events(client, query = {}, opts = {}) {
4807
5922
  }
4808
5923
  }
4809
5924
  //#endregion
4810
- export { isApiMessageId as a, tailWatchers as c, createVercel as i, deployedOnVercel as l, isBoardName as n, PROTOCOL_ROUTES as o, stoppedBy as r, withoutToken as s, createBoard as t };
5925
+ //#region src/client/chunks.ts
5926
+ /**
5927
+ * A chunk failed, with the chunks before it made: `code`, `status`, and `message` are the failure's
5928
+ * own, and `created` holds the tasks that were made, each at its task's place in the `tasks` given,
5929
+ * with `undefined` for the ones that weren't.
5930
+ */
5931
+ var TasksInChunksError = class extends BoardError {
5932
+ created;
5933
+ constructor(cause, created) {
5934
+ const failed = cause instanceof BoardError ? cause : null;
5935
+ super(failed?.code ?? "chunk_failed", cause instanceof Error ? cause.message : String(cause), failed?.status ?? 0, {
5936
+ ...failed?.hint !== void 0 ? { hint: failed.hint } : {},
5937
+ origin: failed?.origin ?? "handle"
5938
+ });
5939
+ this.name = "TasksInChunksError";
5940
+ this.cause = cause;
5941
+ this.created = created;
5942
+ }
5943
+ };
5944
+ /**
5945
+ * Makes `tasks` in `channel` with as many `tasks.createMany` calls as it takes, and answers their
5946
+ * roots in the order given. It makes each task after the ones it waits for by `key`, names a task
5947
+ * an earlier chunk made by the ID it got, and sends fewer when a board answers `batch_too_large`:
5948
+ * 50, then 25, down to one. With `id`, each chunk goes under an ID made from it and where the
5949
+ * chunk starts, and the plan's last task says the plan ends with it. So calling again with the
5950
+ * same `id` and tasks answers the chunks that landed and makes the rest. What landed can't change
5951
+ * and a plan that finished takes no more, wherever its chunks ended: both are a 409
5952
+ * `duplicate_id`, with nothing new made. What a call that stopped midway didn't make can still
5953
+ * change.
5954
+ *
5955
+ * It isn't one write. Each chunk is all or nothing, and the chunks land one after another: a task
5956
+ * of an earlier chunk that's ready can be claimed before a later chunk lands. When a chunk fails
5957
+ * it stops and throws a `TasksInChunksError`, whose `created` has what the chunks before it made.
5958
+ * A plan that must not start early waits for a task of the caller's own, which it completes once
5959
+ * this returns.
5960
+ */
5961
+ async function createTasksInChunks(board, channel, tasks, options = {}) {
5962
+ const plan = batchPlan(tasks);
5963
+ if ("problem" in plan) throw new BoardError("invalid_needs", `needs: ${plan.problem}`, 400);
5964
+ const { order } = plan;
5965
+ const places = new Map(tasks.flatMap((task, at) => task.key !== void 0 ? [[task.key, at]] : []));
5966
+ const created = tasks.map(() => void 0);
5967
+ let size = 100;
5968
+ for (let from = 0; from < order.length;) {
5969
+ const picked = order.slice(from, from + size);
5970
+ const names = new Map(picked.map((at, n) => [at, from + n === order.length - 1 ? "end" : String(n)]));
5971
+ const chunk = picked.map((at) => {
5972
+ const { needs, ...task } = tasks[at];
5973
+ const waits = needs?.map((need) => typeof need === "string" ? need : created[places.get(need.key)]?.id ?? { key: names.get(places.get(need.key)) });
5974
+ return {
5975
+ ...task,
5976
+ key: names.get(at),
5977
+ ...waits ? { needs: waits } : {}
5978
+ };
5979
+ });
5980
+ try {
5981
+ const made = await board.tasks.createMany(channel, chunk, options.id !== void 0 ? { id: `${options.id}/${from}` } : {});
5982
+ for (const [n, at] of picked.entries()) created[at] = made[n];
5983
+ from += picked.length;
5984
+ } catch (error) {
5985
+ if (!(error instanceof BoardError && (error.code === "batch_too_large" || error.code === "duplicate_id" && options.id !== void 0)) || picked.length === 1) throw new TasksInChunksError(error, created);
5986
+ do
5987
+ size = Math.ceil(size / 2);
5988
+ while (size >= picked.length);
5989
+ }
5990
+ }
5991
+ return created;
5992
+ }
5993
+ //#endregion
5994
+ export { stoppedBy as a, PROTOCOL_ROUTES as c, deployedOnVercel as d, isBoardName as i, withoutToken as l, createTasksInChunks as n, createVercel as o, createBoard as r, isApiMessageId as s, TasksInChunksError as t, tailWatchers as u };