@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,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-QhkdzI-o.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-ABXf3CKq.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-CT6vMNUc.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 { a as replaceMentions, i as mentionTerms, o as settleMentions, r as mentionTerm, t as extractMentions } from "./mentions-CnWt9Z5b.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-BZXm6kOE.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-C06pIr0M.mjs";
9
+ import { C as verifiesTokens, E as explainGrants, S as verifiedIssuers, d as createAuthority, f as fromTokens, m as hostPrincipal, o as VERCEL_ISSUER, p as grantIssuers, t as DEFAULT_CAN$1, v as namesByLogin } from "./auth-B9-wXQ-x.mjs";
10
+ import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-Dkyg-oo0.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,
@@ -845,7 +930,7 @@ function actorView(actor, view, project) {
845
930
  };
846
931
  if (profile?.platform) {
847
932
  const { userId, platform, key } = profile.platform;
848
- const handle = importedHandleOf(view?.handle ?? "", principal, view, userId, project);
933
+ const handle = view ? importedHandleOf(view.handle, principal, view, userId, project) : actor.id;
849
934
  return {
850
935
  id: actor.id,
851
936
  kind: "external",
@@ -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;
@@ -1180,22 +1288,40 @@ function createVercel(options, environment) {
1180
1288
  for (const reaction of await all(who, path, "reactions")) (out[reaction.emoji] ??= []).push(reaction.actor.id);
1181
1289
  return out;
1182
1290
  }
1183
- /** Who's written here, by actor ID, as the API names them: messages carry only the actor. */
1184
- let actorNames = null;
1291
+ const namesBy = /* @__PURE__ */ new Map();
1292
+ const namesOf = (who) => {
1293
+ const narrowing = who.can ?? "";
1294
+ let names = namesBy.get(narrowing);
1295
+ if (!names) {
1296
+ if (namesBy.size >= 100) namesBy.clear();
1297
+ namesBy.set(narrowing, names = {
1298
+ list: null,
1299
+ unlisted: /* @__PURE__ */ new Set(),
1300
+ asked: /* @__PURE__ */ new Map(),
1301
+ asking: null,
1302
+ unnamed: /* @__PURE__ */ new Set(),
1303
+ unhandled: /* @__PURE__ */ new Map()
1304
+ });
1305
+ }
1306
+ return names;
1307
+ };
1185
1308
  /** How long names are kept before they're read again: someone renamed shows by their new name after this. */
1186
1309
  const NAMES_FRESH_MS = 3e5;
1187
- /** Actors a list read again for them didn't have: it isn't read again for them. */
1188
- const unlisted = /* @__PURE__ */ new Set();
1189
- /** Reads the list, kept as the current one; a read that fails isn't kept, so the next name tries again. */
1310
+ /** An answer that says no to the request itself, and not that the API couldn't serve it now. */
1311
+ const refusal = (error) => error instanceof HttpError && error.status >= 400 && error.status < 500 && error.status !== 429;
1312
+ /** Reads the list, kept as the current one; a read that fails isn't kept, so the next name tries again, unless the API refused it. */
1190
1313
  const readNames = (who) => {
1314
+ const names = namesOf(who);
1191
1315
  const views = (async () => new Map((await all(who, await onBoard(who, "/actors"), "actors")).map((view) => [view.id, view])))();
1192
1316
  const read = {
1193
1317
  at: Date.now(),
1194
- views
1318
+ views,
1319
+ refused: false
1195
1320
  };
1196
- actorNames = read;
1197
- views.catch(() => {
1198
- if (actorNames === read) actorNames = null;
1321
+ names.list = read;
1322
+ views.catch((error) => {
1323
+ if (refusal(error)) read.refused = true;
1324
+ else if (names.list === read) names.list = null;
1199
1325
  });
1200
1326
  return read;
1201
1327
  };
@@ -1205,10 +1331,6 @@ function createVercel(options, environment) {
1205
1331
  let namesById = true;
1206
1332
  /** Actor IDs one request names, as many as the API takes. */
1207
1333
  const NAMED_AT_ONCE = 100;
1208
- /** Each actor asked for by ID, and when: one the API didn't have is asked for again after `NAMES_FRESH_MS`, as one it had is. */
1209
- const asked = /* @__PURE__ */ new Map();
1210
- /** The request for actors by ID that hasn't gone out yet: everyone named before this turn's promises settle shares it. */
1211
- let asking = null;
1212
1334
  /**
1213
1335
  * Once everything already running in this turn has had its say, and before any timer or request answers: the
1214
1336
  * views of a page each name their author as they start, a few promise steps apart, and what waits on them
@@ -1223,7 +1345,7 @@ function createVercel(options, environment) {
1223
1345
  const { actors } = await api(who, "GET", await onBoard(who, "/actors"), { query: { id: ids } });
1224
1346
  return new Map(actors.map((view) => [view.id, view]));
1225
1347
  } catch (error) {
1226
- if (!(error instanceof HttpError && error.status >= 400 && error.status < 500 && error.status !== 429)) throw error;
1348
+ if (!refusal(error)) throw error;
1227
1349
  if (error.status === 400 && /additional property/i.test(error.message)) namesById = false;
1228
1350
  return null;
1229
1351
  }
@@ -1238,19 +1360,21 @@ function createVercel(options, environment) {
1238
1360
  * doesn't have or a read that failed, which isn't kept; null when the API doesn't answer by ID.
1239
1361
  */
1240
1362
  function byId(who, id) {
1363
+ const names = namesOf(who);
1364
+ const { asked } = names;
1241
1365
  const kept = asked.get(id);
1242
1366
  if (kept && Date.now() - kept.at <= NAMES_FRESH_MS) return kept.view;
1243
- let batch = asking;
1367
+ let batch = names.asking;
1244
1368
  if (!batch || batch.ids.length >= NAMED_AT_ONCE) {
1245
1369
  const ids = [];
1246
1370
  const next = {
1247
1371
  ids,
1248
1372
  views: settled().then(() => {
1249
- if (asking === next) asking = null;
1373
+ if (names.asking === next) names.asking = null;
1250
1374
  return readNamed(who, ids);
1251
1375
  })
1252
1376
  };
1253
- batch = asking = next;
1377
+ batch = names.asking = next;
1254
1378
  }
1255
1379
  batch.ids.push(id);
1256
1380
  const view = batch.views.then((views) => views === null ? null : views.get(id), () => {
@@ -1275,12 +1399,13 @@ function createVercel(options, environment) {
1275
1399
  }
1276
1400
  /** An actor as the actors list names them: read again every few minutes, and at once for someone who wrote since it was. */
1277
1401
  async function listed(who, id) {
1278
- const current = !actorNames || Date.now() - actorNames.at > NAMES_FRESH_MS ? readNames(who) : actorNames;
1402
+ const names = namesOf(who);
1403
+ const current = !names.list || Date.now() - names.list.at > NAMES_FRESH_MS ? readNames(who) : names.list;
1279
1404
  let found = await inList(current, id);
1280
- if (!found && !unlisted.has(id)) {
1281
- const again = actorNames && actorNames !== current ? actorNames : readNames(who);
1405
+ if (!found && !current.refused && !names.unlisted.has(id)) {
1406
+ const again = names.list && names.list !== current ? names.list : readNames(who);
1282
1407
  found = await inList(again, id);
1283
- if (!found && await again.views.then(() => true, () => false)) unlisted.add(id);
1408
+ if (!found && await again.views.then(() => true, () => false)) names.unlisted.add(id);
1284
1409
  }
1285
1410
  return found;
1286
1411
  }
@@ -1318,20 +1443,19 @@ function createVercel(options, environment) {
1318
1443
  if (!names) namesRead.set(read, names = read.views.then(projectNamesOf, () => /* @__PURE__ */ new Map()));
1319
1444
  return names;
1320
1445
  }
1321
- /** What a fresh read of the actors still didn't name: it isn't read again for them until names are read anyway. */
1322
- const unnamed = /* @__PURE__ */ new Set();
1323
1446
  /**
1324
1447
  * Projects' names by ID, as the actors list names them, read again at once when `wanted` (one or more projects, by
1325
1448
  * their IDs) isn't among them, as for someone new since the list was read.
1326
1449
  */
1327
1450
  async function projectNames(who, wanted) {
1328
- const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
1451
+ const mine = namesOf(who);
1452
+ const kept = mine.list && Date.now() - mine.list.at <= NAMES_FRESH_MS ? mine.list : null;
1329
1453
  let names = await namesIn(kept ?? readNames(who));
1330
- if (!wanted || wanted.found(names) || !kept || unnamed.has(wanted.key)) return names;
1331
- names = await namesIn(actorNames && actorNames !== kept ? actorNames : readNames(who));
1454
+ if (!wanted || wanted.found(names) || !kept || kept.refused || mine.unnamed.has(wanted.key)) return names;
1455
+ names = await namesIn(mine.list && mine.list !== kept ? mine.list : readNames(who));
1332
1456
  if (!wanted.found(names)) {
1333
- if (unnamed.size >= 1e3) unnamed.clear();
1334
- unnamed.add(wanted.key);
1457
+ if (mine.unnamed.size >= 1e3) mine.unnamed.clear();
1458
+ mine.unnamed.add(wanted.key);
1335
1459
  }
1336
1460
  return names;
1337
1461
  }
@@ -1359,6 +1483,25 @@ function createVercel(options, environment) {
1359
1483
  if (project === null || project === await ownProject(who)) return from;
1360
1484
  return `${await projectOf(who, by) ?? project}/${from}`;
1361
1485
  }
1486
+ /** A task as board shows it: the tasks it waits for by their roots' IDs, and its claim's end as a time. */
1487
+ const taskView = (task) => ({
1488
+ state: task.state,
1489
+ owner: task.owner,
1490
+ by: task.by,
1491
+ for: task.for,
1492
+ needs: task.needs.map((thread) => idAt(thread, 1)),
1493
+ epoch: task.epoch,
1494
+ claim: task.claim ? {
1495
+ actor: task.claim.actor,
1496
+ until: iso(task.claim.until)
1497
+ } : null,
1498
+ blocked: task.blocked ? {
1499
+ kind: task.blocked.kind,
1500
+ reason: task.blocked.reason
1501
+ } : null,
1502
+ result: task.result,
1503
+ reason: task.reason
1504
+ });
1362
1505
  async function view(who, message, channel) {
1363
1506
  const root = message.sequence === 1;
1364
1507
  const author = nameOf(who, message.createdBy);
@@ -1394,6 +1537,7 @@ function createVercel(options, environment) {
1394
1537
  id: message.schedule.id,
1395
1538
  n: message.schedule.n
1396
1539
  } } : {},
1540
+ ...root && message.task ? { task: taskView(message.task) } : {},
1397
1541
  blocks: (message.from ?? null) === null && message.deletedAt === void 0 ? blocksIn(message.text) : []
1398
1542
  };
1399
1543
  }
@@ -1460,15 +1604,27 @@ function createVercel(options, environment) {
1460
1604
  if (kept) return kept;
1461
1605
  const found = CURSOR.exec(cursor);
1462
1606
  if (!found) throw new HttpError(400, "invalid_cursor", `after: ${cursor} isn't a cursor here or a message's ID`);
1607
+ const t = parseInt(found[1], 36);
1463
1608
  return {
1464
- t: parseInt(found[1], 36),
1465
- feeds: {}
1609
+ t,
1610
+ feeds: {},
1611
+ floor: t
1466
1612
  };
1467
1613
  }
1468
1614
  /** A time a read goes on from: a cursor's, or a message's own. */
1469
1615
  async function timeOf(who, after) {
1470
1616
  return locate(after) ? (await messageById(who, after)).message.createdAt : positionOf(after).t;
1471
1617
  }
1618
+ /** Where a read after a message starts: its time, with no feed read yet. */
1619
+ async function afterMessage(who, id) {
1620
+ const t = await timeOf(who, id);
1621
+ return {
1622
+ t,
1623
+ feeds: {},
1624
+ past: id,
1625
+ floor: t
1626
+ };
1627
+ }
1472
1628
  /** Each channel's feed now, taken before a read, so what's posted while it reads comes after. */
1473
1629
  async function heads(who, listed) {
1474
1630
  const path = await onBoard(who, "/changes");
@@ -1481,8 +1637,6 @@ function createVercel(options, environment) {
1481
1637
  skip: 0
1482
1638
  }]));
1483
1639
  }
1484
- /** Handles a fresh read of the names didn't have, by when: `--by` doesn't read again for them for a while. */
1485
- const unhandled = /* @__PURE__ */ new Map();
1486
1640
  /**
1487
1641
  * Who `--by` names: `me`, the actor itself; or an actor, a principal and its agents, a profile, or
1488
1642
  * a handle as the board shows it (`julian`, `julian/claude`), a person's covering their agents.
@@ -1497,7 +1651,8 @@ function createVercel(options, environment) {
1497
1651
  if (!by.startsWith("vercel:")) {
1498
1652
  const handle = by.toLowerCase();
1499
1653
  const find = async (read) => goingBy(await read.views, await namesIn(read), handle);
1500
- const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
1654
+ const { list, unhandled } = namesOf(who);
1655
+ const kept = list && Date.now() - list.at <= NAMES_FRESH_MS ? list : null;
1501
1656
  let ids = await find(kept ?? readNames(who));
1502
1657
  const missed = unhandled.get(handle);
1503
1658
  if (ids.length === 0 && kept && !(missed !== void 0 && Date.now() - missed <= NAMES_FRESH_MS)) ids = await find(readNames(who));
@@ -1527,9 +1682,29 @@ function createVercel(options, environment) {
1527
1682
  return message.from === key && importer !== null && (importer === project || await namedProject(who, importer) === project);
1528
1683
  };
1529
1684
  }
1685
+ /**
1686
+ * What `--mentions` matches, in a message's text, as on any board: `me` is the caller's handle and
1687
+ * actor ID, as the API names them. Anyone else is the name as written and what's under it: a
1688
+ * person's agents (`@julian/claude`), a project's imports. The API keeps no mentions, so this reads
1689
+ * them from the text of each message a read covers.
1690
+ */
1691
+ async function mentionsOf(who, value) {
1692
+ if (value === void 0) return void 0;
1693
+ let terms;
1694
+ let prefixes = [];
1695
+ if (value === "me") {
1696
+ const found = await api(who, "GET", await onBoard(who, "/me"));
1697
+ terms = [found.actor.id, ...found.view?.handle ? [mentionTerm(found.view.handle)] : []];
1698
+ } else {
1699
+ terms = [mentionTerm(value)];
1700
+ prefixes = [value.includes(":") ? `${value}+` : `${mentionTerm(value)}/`];
1701
+ }
1702
+ return (text) => mentionTerms(text).some((term) => terms.includes(term) || prefixes.some((prefix) => term.startsWith(prefix)));
1703
+ }
1530
1704
  const narrowOf = async (who, filters) => ({
1531
1705
  by: await byOf(who, filters.by),
1532
- source: await sourceOf(who, filters.from)
1706
+ source: await sourceOf(who, filters.from),
1707
+ mentions: await mentionsOf(who, filters.mentions)
1533
1708
  });
1534
1709
  /**
1535
1710
  * Whether a message matches a read's filters, `narrow` as `narrowOf` gives them for it. A label matches on the
@@ -1538,7 +1713,7 @@ function createVercel(options, environment) {
1538
1713
  async function matches(filters, message, thread, narrow) {
1539
1714
  if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
1540
1715
  if (narrow.by && !narrow.by(message.createdBy)) return false;
1541
- if (filters.mentions !== void 0) return false;
1716
+ if (filters.mentions !== void 0 && !narrow.mentions?.(message.text)) return false;
1542
1717
  if (filters.from !== void 0 && !await narrow.source?.(message)) return false;
1543
1718
  if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
1544
1719
  for (const [key, values] of filters.label ?? []) {
@@ -1552,12 +1727,34 @@ function createVercel(options, environment) {
1552
1727
  const first = filters.label?.find(([, values]) => values === null || values.length === 1);
1553
1728
  return first && (first[1] === null ? first[0] : `${first[0]}=${first[1][0]}`);
1554
1729
  }
1730
+ /** Every thread of a channel, each with its first and newest message where the API sends them (`threadPage`). */
1555
1731
  async function threadsOf(who, channel, filters, signal) {
1556
1732
  const label = indexed(filters);
1557
- return all(who, await onBoard(who, "/threads"), "threads", {
1558
- channelId: channel.id,
1559
- label
1560
- }, signal);
1733
+ const path = await onBoard(who, "/threads");
1734
+ const out = [];
1735
+ let cursor;
1736
+ do {
1737
+ const page = await threadPage(who, path, {
1738
+ channelId: channel.id,
1739
+ label,
1740
+ cursor
1741
+ }, signal);
1742
+ out.push(...page.threads);
1743
+ cursor = page.cursor ?? void 0;
1744
+ } while (cursor);
1745
+ return out;
1746
+ }
1747
+ /**
1748
+ * A thread's messages when its list brought them all: its first, and its newest when that's its
1749
+ * second. Most threads are a post or a post and a reply, and reading one of those costs nothing
1750
+ * more. Null for a longer one, or from an API that lists threads without their messages.
1751
+ */
1752
+ function whole(thread) {
1753
+ const root = thread.rootMessage;
1754
+ if (!root || root.sequence !== 1) return null;
1755
+ if (thread.messageCount === 1) return [root];
1756
+ const latest = thread.latestMessage;
1757
+ return thread.messageCount === 2 && latest?.sequence === 2 ? [root, latest] : null;
1561
1758
  }
1562
1759
  /** Whether the API lists threads with their first and newest messages (`include=messages`): until it refuses the parameter, it's asked. */
1563
1760
  let threadsWithMessages = true;
@@ -1608,6 +1805,69 @@ function createVercel(options, environment) {
1608
1805
  return out;
1609
1806
  }
1610
1807
  /**
1808
+ * A page's `older` on this board, for `channel`: the API's thread cursor, base64url JSON whose `scope` names the
1809
+ * channel, then `~<shown>` when the page stopped inside the API's. Anything else was never one: 400 `invalid_cursor`.
1810
+ */
1811
+ function olderIn(before, channel) {
1812
+ 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`);
1813
+ const found = /^([A-Za-z0-9_-]*)(?:~(\d{1,6}))?$/.exec(before);
1814
+ if (!found || !found[1] && found[2] === void 0) throw refused;
1815
+ if (found[1]) {
1816
+ let scope;
1817
+ try {
1818
+ const bytes = Uint8Array.from(atob(found[1].replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
1819
+ scope = JSON.parse(new TextDecoder().decode(bytes))?.scope;
1820
+ } catch {
1821
+ throw refused;
1822
+ }
1823
+ if (typeof scope !== "string" || !scope.split("#").includes(channel.id)) throw refused;
1824
+ }
1825
+ return {
1826
+ cursor: found[1] || void 0,
1827
+ skip: Number(found[2] ?? 0)
1828
+ };
1829
+ }
1830
+ /**
1831
+ * A channel's threads last active before `before`, a page's `older` (from the newest without it), newest first:
1832
+ * at most `limit`, and with `before` at most one of the API's pages, whose cursor is the `older` it answers.
1833
+ * A page cut short at `limit` answers its own cursor with how many of its threads were shown (`<cursor>~4`), so
1834
+ * the next read picks up where it stopped.
1835
+ */
1836
+ async function threadsBefore(who, channel, before, limit, signal) {
1837
+ const path = await onBoard(who, "/threads");
1838
+ let { cursor, skip } = before === void 0 ? {
1839
+ cursor: void 0,
1840
+ skip: 0
1841
+ } : olderIn(before, channel);
1842
+ const out = [];
1843
+ do {
1844
+ const found = await threadPage(who, path, {
1845
+ channelId: channel.id,
1846
+ label: void 0,
1847
+ cursor
1848
+ }, signal).catch((error) => {
1849
+ 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`);
1850
+ throw error;
1851
+ });
1852
+ const fresh = found.threads.slice(skip);
1853
+ const room = limit - out.length;
1854
+ if (fresh.length > room) {
1855
+ out.push(...fresh.slice(0, room));
1856
+ return {
1857
+ threads: out,
1858
+ older: `${cursor ?? ""}~${skip + room}`
1859
+ };
1860
+ }
1861
+ out.push(...fresh);
1862
+ skip = 0;
1863
+ cursor = found.cursor ?? void 0;
1864
+ } while (cursor && before === void 0 && out.length < limit);
1865
+ return {
1866
+ threads: out,
1867
+ older: cursor ?? null
1868
+ };
1869
+ }
1870
+ /**
1611
1871
  * A page of threads as their summaries: each thread's first and newest messages as its thread list brought them,
1612
1872
  * or read by reference from an API that lists threads without them, then every author on the page is asked for
1613
1873
  * together, before any is named.
@@ -1665,12 +1925,23 @@ function createVercel(options, environment) {
1665
1925
  }
1666
1926
  return { profile: named(caller.self ?? "client") };
1667
1927
  }
1928
+ /**
1929
+ * 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
1930
+ * 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.
1931
+ */
1932
+ async function landedIn(who, channelId, name, clientId) {
1933
+ if (channelId === void 0) return name;
1934
+ if (clientId !== void 0 && posted.get(channelId) !== name) return channelById(who, channelId).then((channel) => (posted.set(channelId, channel.name), channel.name), () => name);
1935
+ posted.set(channelId, name);
1936
+ return name;
1937
+ }
1668
1938
  /** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
1669
1939
  const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
1670
1940
  /** Messages a read covers, newest last: every thread's in the channels it names, or one thread's. */
1671
1941
  async function collect(who, filters, signal) {
1672
1942
  let listed;
1673
1943
  let threads;
1944
+ let feeds;
1674
1945
  if (filters.re !== void 0) {
1675
1946
  const found = await messageIn(who, filters.re, signal).catch((error) => {
1676
1947
  if (error instanceof HttpError && error.status === 404) return null;
@@ -1692,19 +1963,20 @@ function createVercel(options, environment) {
1692
1963
  thread: found.thread,
1693
1964
  channel
1694
1965
  }];
1966
+ feeds = await heads(who, listed);
1695
1967
  } else {
1696
1968
  listed = await channelsFor(who, filters.channel);
1969
+ feeds = await heads(who, listed);
1697
1970
  threads = (await Promise.all(listed.map(async (channel) => (await threadsOf(who, channel, filters, signal)).map((thread) => ({
1698
1971
  thread,
1699
1972
  channel
1700
1973
  }))))).flat();
1701
1974
  }
1702
- const feeds = await heads(who, listed);
1703
1975
  const narrow = await narrowOf(who, filters);
1704
1976
  let newest = 0;
1705
1977
  const messages = [];
1706
1978
  for (const { thread, channel } of threads) {
1707
- const all = await threadMessages(who, thread.id, signal);
1979
+ const all = whole(thread) ?? await threadMessages(who, thread.id, signal);
1708
1980
  const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
1709
1981
  for (const message of all) {
1710
1982
  newest = Math.max(newest, message.createdAt);
@@ -1758,8 +2030,9 @@ function createVercel(options, environment) {
1758
2030
  newest: Math.max(0, ...pages.flatMap((page) => page.messages.map((message) => message.createdAt)))
1759
2031
  };
1760
2032
  }
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. */
2033
+ /** 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
2034
  async function eventOf(who, change, channel, cursor, filters, narrow, given, threads = threadReader(who)) {
2035
+ if (change.type.startsWith("task.")) return taskEventOf(who, change, channel, cursor, filters, narrow, given);
1763
2036
  if (!change.messageId || !change.type.startsWith("message.")) return null;
1764
2037
  let found = given ?? await messageById(who, change.messageId).catch((error) => {
1765
2038
  if (error instanceof HttpError && error.status === 404) return null;
@@ -1867,7 +2140,7 @@ function createVercel(options, environment) {
1867
2140
  const events = page.events.map((change, i) => ({
1868
2141
  change,
1869
2142
  i
1870
- })).slice(skip).filter(({ change }) => from || change.createdAt > position.t);
2143
+ })).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
2144
  return {
1872
2145
  channel,
1873
2146
  at: from?.at ?? null,
@@ -1884,6 +2157,10 @@ function createVercel(options, environment) {
1884
2157
  }))).sort((a, b) => a.change.createdAt - b.change.createdAt);
1885
2158
  const events = [];
1886
2159
  naming(who, merged.flatMap(({ change }) => [change.actor, ...change.currentMessage ? [change.currentMessage.createdBy] : []]));
2160
+ const start = {
2161
+ ...position.past !== void 0 ? { past: position.past } : {},
2162
+ ...position.floor !== void 0 ? { floor: position.floor } : {}
2163
+ };
1887
2164
  for (const { change, i, page } of merged) {
1888
2165
  running[page.channel.id] = {
1889
2166
  at: page.at,
@@ -1896,7 +2173,8 @@ function createVercel(options, environment) {
1896
2173
  } : void 0;
1897
2174
  const event = await eventOf(who, change, page.channel.name, cursorOf({
1898
2175
  t: change.createdAt,
1899
- feeds: { ...running }
2176
+ feeds: { ...running },
2177
+ ...start
1900
2178
  }), filters, narrow, given, threads);
1901
2179
  if (event) events.push(event);
1902
2180
  }
@@ -1909,7 +2187,8 @@ function createVercel(options, environment) {
1909
2187
  events,
1910
2188
  position: {
1911
2189
  t: Math.max(position.t, ...merged.map(({ change }) => change.createdAt)),
1912
- feeds: after
2190
+ feeds: after,
2191
+ ...start
1913
2192
  }
1914
2193
  };
1915
2194
  }
@@ -2045,10 +2324,7 @@ function createVercel(options, environment) {
2045
2324
  let position = query.after === void 0 ? {
2046
2325
  t: Date.now(),
2047
2326
  feeds: await heads(who, listed)
2048
- } : locate(query.after) ? {
2049
- t: await timeOf(who, query.after),
2050
- feeds: {}
2051
- } : positionOf(query.after);
2327
+ } : locate(query.after) ? await afterMessage(who, query.after) : positionOf(query.after);
2052
2328
  const until = Date.now() + (query.wait ?? 0) * 1e3;
2053
2329
  let busy = false;
2054
2330
  for (;;) {
@@ -2410,6 +2686,21 @@ function createVercel(options, environment) {
2410
2686
  avatar,
2411
2687
  isBot
2412
2688
  });
2689
+ /** The platform users an import's text mentions, for the API to meet as it meets the author. */
2690
+ const mentioned = (body) => body.mentioned?.length ? { mentioned: body.mentioned.map(platformUser) } : {};
2691
+ /**
2692
+ * An import's text, its mentions of its keys' users (`@[slack:user:U0456]`) as the API names
2693
+ * them: this project's profiles of them, as it names the author. Where that would take the text
2694
+ * past what a message holds, it stays as it came, and sync still finds who the short ID names.
2695
+ */
2696
+ async function asNamed(who, body) {
2697
+ const keys = body.from === null ? [.../* @__PURE__ */ new Set([body.author.id.split(":")[0], ...(binding?.sync ?? []).map((entry) => entry.key)])] : [body.from];
2698
+ const ours = (actor) => keys.some((key) => actor.startsWith(`${key}:`));
2699
+ if (!keys.some((key) => body.text.includes(`@[${key}:`))) return body.text;
2700
+ const owner = principalId((await self(who)).actor.principal);
2701
+ const named = replaceMentions(body.text, (token) => token.kind === "actor" && ours(token.actor) ? `@[${owner}+${token.actor}]` : null);
2702
+ return named.length > 1e4 ? body.text : named;
2703
+ }
2413
2704
  /** An import as the API takes it: a channel by its ID, and a reply's `after` as its sequence in the thread. */
2414
2705
  async function importBody(who, body) {
2415
2706
  const base = {
@@ -2432,11 +2723,12 @@ function createVercel(options, environment) {
2432
2723
  ...body.source ? { source: body.source } : {},
2433
2724
  ...body.channel !== void 0 ? { channelId: (await channelToPost(who, body.channel)).id } : {},
2434
2725
  ...body.re !== void 0 ? { re: body.re } : {},
2435
- text: body.text,
2726
+ text: await asNamed(who, body),
2436
2727
  ...body.labels && Object.keys(body.labels).length ? { labels: body.labels } : {},
2437
2728
  ...body.noSync ? { noSync: true } : {},
2438
2729
  ...body.attachments?.length ? { attachments: body.attachments } : {},
2439
2730
  ...body.links?.length ? { links: body.links } : {},
2731
+ ...mentioned(body),
2440
2732
  ...body.id !== void 0 ? { id: body.id } : {},
2441
2733
  ...after !== void 0 ? { after } : {}
2442
2734
  };
@@ -2448,9 +2740,10 @@ function createVercel(options, environment) {
2448
2740
  };
2449
2741
  if (body.op === "edit") return {
2450
2742
  ...changed,
2451
- text: body.text,
2743
+ text: await asNamed(who, body),
2452
2744
  ...body.source ? { source: body.source } : {},
2453
- ...body.revision !== void 0 ? { revision: body.revision } : {}
2745
+ ...body.revision !== void 0 ? { revision: body.revision } : {},
2746
+ ...mentioned(body)
2454
2747
  };
2455
2748
  if (body.op === "delete") return {
2456
2749
  ...changed,
@@ -2490,6 +2783,278 @@ function createVercel(options, environment) {
2490
2783
  });
2491
2784
  throw error;
2492
2785
  };
2786
+ /**
2787
+ * What the API refused of a task, as a board says it: its codes with a board's statuses, and a
2788
+ * thread that isn't there as the message it is here. A lost claim keeps the API's word for why, in
2789
+ * its message.
2790
+ */
2791
+ function taskRefusal(error, about = {}) {
2792
+ if (!(error instanceof HttpError)) return error;
2793
+ const { code, message } = error;
2794
+ if (code === "thread_not_found") return notFound(`message not found: ${about.id ?? "that task"}`, "message_not_found");
2795
+ if (code === "not_a_task") return notFound(message, "not_a_task");
2796
+ if (code === "message_deleted") return badRequest(message, "message_deleted");
2797
+ if (code === "bad_request" || code === "invalid_for") return badRequest(message);
2798
+ if (code === "invalid_needs" || code === "reserved_label") return badRequest(message, code);
2799
+ if (code === "task_not_owned") return new HttpError(403, code, message);
2800
+ if (code === "claim_lost") {
2801
+ const reason = reasons.get(error);
2802
+ return new HttpError(409, "claim_lost", `this claim on ${about.id ?? "the task"} is over${reason ? ` (${reason})` : ""}: claim it again`);
2803
+ }
2804
+ if (TASK_CONFLICTS.has(code)) return new HttpError(409, code, message);
2805
+ return error;
2806
+ }
2807
+ /** One write to a task route, `/tasks` and `path` after it, with an operation ID of its own. */
2808
+ async function taskWrite(who, path, body, about = {}) {
2809
+ try {
2810
+ return await api(who, "POST", await onBoard(who, `/tasks${path}`), {
2811
+ version: 2,
2812
+ body: {
2813
+ operationId: operationId(),
2814
+ ...body
2815
+ },
2816
+ ...about.signal ? { signal: about.signal } : {}
2817
+ });
2818
+ } catch (error) {
2819
+ throw taskRefusal(error, about);
2820
+ }
2821
+ }
2822
+ /**
2823
+ * 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,
2824
+ * 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
2825
+ * nothing is asked of its thread.
2826
+ */
2827
+ async function taskPath(who, id, signal) {
2828
+ const at = locate(id);
2829
+ if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
2830
+ if (at.sequence !== 1) {
2831
+ await messageById(who, id, signal);
2832
+ throw notFound(`${id} isn't a task`, "not_a_task");
2833
+ }
2834
+ return `/${encodeURIComponent(at.threadId)}`;
2835
+ }
2836
+ /** A task's first message with the task on it, as a board's root carries it. */
2837
+ const firstOf = ({ id: _id, channelId: _channel, message, messageCount: _count, lastActivityAt: _at, lastMessage: _last, ...task }) => ({
2838
+ ...message,
2839
+ task
2840
+ });
2841
+ /** A task as a thread list brings a thread with its messages: its first message on it, which carries the task. */
2842
+ const listedOf = (task) => ({
2843
+ id: task.id,
2844
+ channelId: task.channelId,
2845
+ messageCount: task.messageCount,
2846
+ lastActivityAt: task.lastActivityAt,
2847
+ ...task.lastMessage ? { lastMessage: task.lastMessage } : {},
2848
+ createdAt: task.message.createdAt,
2849
+ createdBy: task.message.createdBy,
2850
+ rootMessage: firstOf(task)
2851
+ });
2852
+ /** A task's root as board shows it, from what a task route answered. */
2853
+ const rootOf = async (who, made) => view(who, firstOf(made.task), (await channelById(who, made.task.channelId)).name);
2854
+ /** What a claim answers once: the epoch and the end the API gave it, with the token this backend made for it. */
2855
+ function claimOf({ task }, token) {
2856
+ if (!task.claim) throw new HttpError(502, "remote_error", "Vercel's API answered a claim without one");
2857
+ return {
2858
+ epoch: task.epoch,
2859
+ token,
2860
+ until: iso(task.claim.until)
2861
+ };
2862
+ }
2863
+ /** What a claim's own write carries there: its token, as the API takes one, and its epoch. */
2864
+ const proofOf = async (proof) => ({
2865
+ claimToken: await sendableToken(proof.token),
2866
+ epoch: proof.epoch
2867
+ });
2868
+ /** The threads the tasks `refs` name: each a root's ID. Anything else is no task, as a task nobody can read is. */
2869
+ function needsOf(refs) {
2870
+ const threads = /* @__PURE__ */ new Set();
2871
+ for (const ref of refs) {
2872
+ const at = locate(ref);
2873
+ if (!at || at.sequence !== 1) throw badRequest(`needs: ${ref} isn't a task`, "invalid_needs");
2874
+ threads.add(at.threadId);
2875
+ }
2876
+ return [...threads];
2877
+ }
2878
+ /**
2879
+ * 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.
2880
+ * Whom it's for is the API's to check, one of its owner's profiles, as on any board.
2881
+ */
2882
+ const taskSpec = (input, token) => ({
2883
+ ...input.needs?.length ? { needs: needsOf(input.needs) } : {},
2884
+ ...input.for ? { for: input.for } : {},
2885
+ ...token ? { claim: {
2886
+ claimToken: token,
2887
+ leaseSeconds: input.lease ?? 900
2888
+ } } : {}
2889
+ });
2890
+ /**
2891
+ * 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
2892
+ * is what was asked for. It waits when it names tasks to wait for, which the API checked, and no one holds it: a
2893
+ * claim takes `label`, which reads.
2894
+ */
2895
+ const askedTask = (owner, by, input) => ({
2896
+ state: input.needs?.length ? "waiting" : "ready",
2897
+ owner,
2898
+ by,
2899
+ for: input.for ?? null,
2900
+ needs: input.needs?.length ? needsOf(input.needs) : [],
2901
+ epoch: 0,
2902
+ claim: null,
2903
+ blocked: null,
2904
+ result: null,
2905
+ reason: null
2906
+ });
2907
+ /** Who a handle or an ID names, as IDs: an ID names itself, whether or not the board has seen it write. */
2908
+ async function idsNamed(who, value) {
2909
+ if (isId(value)) return /* @__PURE__ */ new Set([value]);
2910
+ const { list } = namesOf(who);
2911
+ const read = list && Date.now() - list.at <= NAMES_FRESH_MS ? list : readNames(who);
2912
+ return new Set(goingBy(await read.views, await namesIn(read), value.toLowerCase()));
2913
+ }
2914
+ /**
2915
+ * A task's change in the API's feed as the board's event, built from the task as it was right
2916
+ * after it. It's delivered when its root matched the filters before the change or after it, as a
2917
+ * label's change is on any board: `board.task` is the label a task's change moves.
2918
+ */
2919
+ async function taskEventOf(who, change, channel, cursor, filters, narrow, given) {
2920
+ const type = TASK_EVENTS[change.type];
2921
+ if (!type || !change.messageId || type === "task.renewed" && !filters.all) return null;
2922
+ const found = given ?? await messageById(who, change.messageId).catch((error) => {
2923
+ if (error instanceof HttpError && error.status === 404) return null;
2924
+ throw error;
2925
+ });
2926
+ const task = change.task ?? found?.message.task;
2927
+ if (!found || !task || found.message.sequence !== 1) return null;
2928
+ const wearing = (own, state) => {
2929
+ const { [TASK_LABEL]: _state, ...rest } = own;
2930
+ return state === void 0 ? rest : {
2931
+ ...rest,
2932
+ [TASK_LABEL]: state
2933
+ };
2934
+ };
2935
+ const moved = change.labels?.[TASK_LABEL];
2936
+ const as = (labels) => ({
2937
+ message: {
2938
+ ...found.message,
2939
+ task,
2940
+ labels
2941
+ },
2942
+ thread: {
2943
+ ...found.thread,
2944
+ labels
2945
+ }
2946
+ });
2947
+ const after = as(found.message.deletedAt !== void 0 ? {} : wearing(labelsOf(found.message), task.state));
2948
+ const kept = { ...found.message.labels };
2949
+ const then = [as(wearing(kept, task.state)), ...moved ? [as(wearing(kept, moved.from))] : []];
2950
+ let matched = false;
2951
+ for (const { message, thread } of then) matched ||= await matches(filters, message, thread, narrow);
2952
+ if (!matched) return null;
2953
+ const message = await view(who, after.message, channel);
2954
+ const by = authorOf(change.actor);
2955
+ const base = {
2956
+ id: message.id,
2957
+ thread: message.thread
2958
+ };
2959
+ const claimed = {
2960
+ epoch: task.epoch,
2961
+ until: iso(task.claim?.until ?? change.createdAt)
2962
+ };
2963
+ let payload;
2964
+ switch (type) {
2965
+ case "task.created":
2966
+ payload = {
2967
+ ...base,
2968
+ needs: message.task.needs,
2969
+ for: task.for,
2970
+ by
2971
+ };
2972
+ break;
2973
+ case "task.assigned":
2974
+ payload = {
2975
+ ...base,
2976
+ for: task.for,
2977
+ by
2978
+ };
2979
+ break;
2980
+ case "task.needs_changed":
2981
+ payload = {
2982
+ ...base,
2983
+ needs: message.task.needs,
2984
+ by
2985
+ };
2986
+ break;
2987
+ case "task.claimed":
2988
+ case "task.renewed":
2989
+ payload = {
2990
+ ...base,
2991
+ ...claimed,
2992
+ by
2993
+ };
2994
+ break;
2995
+ case "task.released":
2996
+ payload = {
2997
+ ...base,
2998
+ epoch: task.epoch,
2999
+ by
3000
+ };
3001
+ break;
3002
+ case "task.completed":
3003
+ payload = {
3004
+ ...base,
3005
+ epoch: task.epoch,
3006
+ result: task.result,
3007
+ by
3008
+ };
3009
+ break;
3010
+ case "task.failed":
3011
+ payload = {
3012
+ ...base,
3013
+ epoch: task.epoch,
3014
+ reason: task.reason,
3015
+ by
3016
+ };
3017
+ break;
3018
+ case "task.blocked":
3019
+ payload = {
3020
+ ...base,
3021
+ kind: task.blocked?.kind ?? null,
3022
+ reason: task.blocked?.reason ?? "",
3023
+ by
3024
+ };
3025
+ break;
3026
+ case "task.canceled":
3027
+ payload = {
3028
+ ...base,
3029
+ reason: task.reason,
3030
+ by
3031
+ };
3032
+ break;
3033
+ case "task.unblocked":
3034
+ case "task.reopened":
3035
+ payload = {
3036
+ ...base,
3037
+ by
3038
+ };
3039
+ break;
3040
+ case "task.expired":
3041
+ payload = {
3042
+ ...base,
3043
+ epoch: task.epoch
3044
+ };
3045
+ break;
3046
+ default: payload = base;
3047
+ }
3048
+ const own = type === "task.expired" || type === "task.ready";
3049
+ return {
3050
+ cursor,
3051
+ type,
3052
+ createdAt: iso(change.createdAt),
3053
+ payload,
3054
+ message,
3055
+ ...own ? {} : { actor: await nameOf(who, change.actor) }
3056
+ };
3057
+ }
2493
3058
  const methods = {
2494
3059
  ...Object.fromEntries(METHODS.map((method) => [method, async () => {
2495
3060
  throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
@@ -2641,7 +3206,27 @@ function createVercel(options, environment) {
2641
3206
  const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
2642
3207
  return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
2643
3208
  };
2644
- if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0) {
3209
+ const byMessage = query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0;
3210
+ if (query.channel !== void 0 && !query.channel.endsWith("/") && !byMessage && !query.label?.length && after === void 0) {
3211
+ const listed = await channelsFor(who, query.channel);
3212
+ const feeds = await heads(who, listed);
3213
+ const found = await Promise.all(listed.map((channel) => threadsBefore(who, channel, query.before, limit, signal)));
3214
+ const page = listed.flatMap((channel, i) => found[i].threads.map((thread) => ({
3215
+ thread,
3216
+ channel,
3217
+ at: thread.lastActivityAt
3218
+ }))).reverse();
3219
+ return {
3220
+ threads: await summaries(who, page, signal),
3221
+ cursor: cursorOf({
3222
+ t: page.reduce((max, { at }) => Math.max(max, at), 0),
3223
+ feeds
3224
+ }),
3225
+ older: found[0]?.older ?? null
3226
+ };
3227
+ }
3228
+ if (query.before !== void 0) throw new HttpError(400, "invalid_request", "before: this board pages one channel's threads, with no filters");
3229
+ if (byMessage) {
2645
3230
  const { messages, feeds, newest } = await collect(who, query, signal);
2646
3231
  const latest = /* @__PURE__ */ new Map();
2647
3232
  for (const { message, thread, channel } of messages) latest.set(thread.id, {
@@ -2827,11 +3412,7 @@ function createVercel(options, environment) {
2827
3412
  }
2828
3413
  made = reply;
2829
3414
  }
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
- }
3415
+ channelName = await landedIn(who, made.thread.channelId, channelName, clientId);
2835
3416
  return { message: await view(who, "text" in made.message ? made.message : await sent(who, made.message, input), channelName) };
2836
3417
  },
2837
3418
  async posted(caller, { id }, signal) {
@@ -3027,6 +3608,389 @@ function createVercel(options, environment) {
3027
3608
  canceled
3028
3609
  };
3029
3610
  },
3611
+ async tasks(caller, query, signal) {
3612
+ const who = whoOf(caller);
3613
+ const limit = query.limit ?? 50;
3614
+ let after;
3615
+ if (query.after !== void 0 && query.after !== TASKS_START) {
3616
+ const at = locate(query.after);
3617
+ if (!at) throw new HttpError(400, "invalid_cursor", `${query.after} isn't a cursor or a message ID on this board`);
3618
+ after = at.threadId;
3619
+ }
3620
+ const none = {
3621
+ tasks: [],
3622
+ cursor: query.after ?? TASKS_START
3623
+ };
3624
+ const needed = query.needs === void 0 ? void 0 : locate(query.needs);
3625
+ if (needed === null || needed !== void 0 && needed.sequence !== 1) return none;
3626
+ const by = await byOf(who, query.by);
3627
+ const owners = query.owner === void 0 ? null : await idsNamed(who, query.owner);
3628
+ const assignees = query.for === void 0 ? null : await idsNamed(who, query.for);
3629
+ const labels = query.label ?? [];
3630
+ const matching = (task) => {
3631
+ if (owners && !owners.has(task.owner)) return false;
3632
+ if (assignees && !(task.for !== null && assignees.has(task.for))) return false;
3633
+ if (by && !by(task.message.createdBy)) return false;
3634
+ const wears = task.message.labels;
3635
+ return labels.every(([key, values]) => wears !== void 0 && Object.hasOwn(wears, key) && (values === null || values.includes(wears[key])));
3636
+ };
3637
+ const asked = {
3638
+ state: query.state ?? "open",
3639
+ channel: query.channel,
3640
+ label: labels.map(([key, values]) => values === null || values.length !== 1 ? key : `${key}=${values[0]}`),
3641
+ owner: query.owner !== void 0 && isId(query.owner) ? query.owner : void 0,
3642
+ for: query.for !== void 0 && isId(query.for) ? query.for : void 0,
3643
+ needs: needed?.threadId
3644
+ };
3645
+ const path = await onBoard(who, "/tasks");
3646
+ const found = [];
3647
+ let from = after !== void 0 ? { after } : {};
3648
+ while (found.length < limit) {
3649
+ const page = await api(who, "GET", path, {
3650
+ version: 2,
3651
+ query: {
3652
+ ...asked,
3653
+ ...from
3654
+ },
3655
+ signal
3656
+ }).catch((error) => {
3657
+ throw taskRefusal(error);
3658
+ });
3659
+ for (const task of page.tasks) if (found.length < limit && matching(task)) found.push(task);
3660
+ if (!page.cursor) break;
3661
+ from = { cursor: page.cursor };
3662
+ }
3663
+ const tasks = await summaries(who, await Promise.all(found.map(async (task) => ({
3664
+ thread: listedOf(task),
3665
+ channel: await channelById(who, task.channelId)
3666
+ }))), signal);
3667
+ const last = found.at(-1);
3668
+ return {
3669
+ tasks,
3670
+ cursor: last ? idAt(last.id, 1) : none.cursor
3671
+ };
3672
+ },
3673
+ async createTask(caller, input, signal) {
3674
+ const who = whoOf(caller);
3675
+ const token = input.claim ? newClaimToken() : null;
3676
+ const spec = taskSpec(input, token);
3677
+ let made;
3678
+ let root;
3679
+ let task;
3680
+ if (input.re !== void 0) {
3681
+ const at = locate(input.re);
3682
+ if (!at) throw notFound(`message not found: ${input.re}`, "message_not_found");
3683
+ if (at.sequence !== 1) {
3684
+ await messageById(who, input.re, signal);
3685
+ throw badRequest(`${input.re} is a reply: a task is a thread, so name its root, ${idAt(at.threadId, 1)}`);
3686
+ }
3687
+ const adopted = await taskWrite(who, "", {
3688
+ threadId: at.threadId,
3689
+ ...spec
3690
+ }, {
3691
+ id: input.re,
3692
+ signal
3693
+ });
3694
+ made = adopted;
3695
+ task = adopted.task;
3696
+ root = await rootOf(who, adopted);
3697
+ } else {
3698
+ const clientId = input.id !== void 0 ? await clientIdOf(input.id) : void 0;
3699
+ const text = input.text ?? "";
3700
+ made = await taskWrite(who, "", {
3701
+ channel: input.channel,
3702
+ text,
3703
+ ...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
3704
+ ...clientId ? { clientId } : {},
3705
+ ...input.attachments?.length ? { attachments: input.attachments } : {},
3706
+ ...input.noSync ? { noSync: true } : {},
3707
+ ...spec
3708
+ }, { signal }).catch((error) => {
3709
+ if (error instanceof HttpError && error.code === "not_a_task") throw duplicateId();
3710
+ throw error;
3711
+ });
3712
+ if ("message" in made.task) {
3713
+ task = made.task;
3714
+ root = await view(who, firstOf(made.task), await landedIn(who, made.task.channelId, input.channel, clientId));
3715
+ } else {
3716
+ const { actor } = await self(who);
3717
+ task = askedTask(principalId(actor.principal), await actorOf(who), input);
3718
+ root = await view(who, {
3719
+ ...await sent(who, {
3720
+ id: idAt(made.task.id, 1),
3721
+ threadId: made.task.id,
3722
+ sequence: 1
3723
+ }, {
3724
+ text,
3725
+ labels: {
3726
+ ...input.labels,
3727
+ [TASK_LABEL]: task.state
3728
+ },
3729
+ attachments: input.attachments,
3730
+ noSync: input.noSync
3731
+ }),
3732
+ task
3733
+ }, input.channel);
3734
+ }
3735
+ }
3736
+ if (!token || made.claimed !== true || !task.claim) return { task: root };
3737
+ return {
3738
+ task: root,
3739
+ claim: {
3740
+ epoch: task.epoch,
3741
+ token,
3742
+ until: iso(task.claim.until)
3743
+ }
3744
+ };
3745
+ },
3746
+ async createTasks(caller, input, signal) {
3747
+ const who = whoOf(caller);
3748
+ const waits = input.tasks.map((task) => {
3749
+ const keys = [...new Set((task.needs ?? []).flatMap((need) => typeof need === "string" ? [] : [need.key]))];
3750
+ return {
3751
+ threads: needsOf((task.needs ?? []).filter((need) => typeof need === "string")),
3752
+ keys
3753
+ };
3754
+ });
3755
+ const tasks = input.tasks.map((task, at) => {
3756
+ const needs = [...waits[at].threads, ...waits[at].keys.map((key) => ({ key }))];
3757
+ return {
3758
+ ...task.key !== void 0 ? { key: task.key } : {},
3759
+ text: task.text,
3760
+ ...task.labels && Object.keys(task.labels).length ? { labels: task.labels } : {},
3761
+ ...task.noSync ? { noSync: true } : {},
3762
+ ...task.attachments?.length ? { attachments: task.attachments } : {},
3763
+ ...needs.length ? { needs } : {},
3764
+ ...task.for ? { for: task.for } : {}
3765
+ };
3766
+ });
3767
+ const body = {
3768
+ operationId: operationId(),
3769
+ channel: input.channel,
3770
+ ...input.id !== void 0 ? { idempotencyKey: input.id } : {},
3771
+ tasks
3772
+ };
3773
+ const made = await api(who, "POST", await onBoard(who, "/tasks/batch"), {
3774
+ version: 2,
3775
+ body,
3776
+ signal
3777
+ }).catch((error) => {
3778
+ if (error instanceof HttpError && error.code === "idempotency_key_reused") throw duplicateId();
3779
+ if (error instanceof HttpError && error.code === "entity_too_large") throw new HttpError(400, "batch_too_large", error.message);
3780
+ throw taskRefusal(error);
3781
+ });
3782
+ const threads = made.tasks.map((task) => task.id);
3783
+ const places = new Map(input.tasks.flatMap((task, at) => task.key !== void 0 ? [[task.key, at]] : []));
3784
+ return { tasks: await Promise.all(made.tasks.map(async (task, at) => {
3785
+ if ("message" in task) return view(who, firstOf(task), await landedIn(who, task.channelId, input.channel, void 0));
3786
+ const asked = input.tasks[at];
3787
+ const needs = [...waits[at].threads, ...waits[at].keys.map((key) => threads[places.get(key)])];
3788
+ const { actor } = await self(who);
3789
+ const stood = {
3790
+ state: needs.length ? "waiting" : "ready",
3791
+ owner: principalId(actor.principal),
3792
+ by: await actorOf(who),
3793
+ for: asked.for ?? null,
3794
+ needs,
3795
+ epoch: 0,
3796
+ claim: null,
3797
+ blocked: null,
3798
+ result: null,
3799
+ reason: null
3800
+ };
3801
+ const first = {
3802
+ id: idAt(task.id, 1),
3803
+ threadId: task.id,
3804
+ sequence: 1
3805
+ };
3806
+ return view(who, {
3807
+ ...await sent(who, first, {
3808
+ text: asked.text,
3809
+ labels: {
3810
+ ...asked.labels,
3811
+ [TASK_LABEL]: stood.state
3812
+ },
3813
+ attachments: asked.attachments,
3814
+ noSync: asked.noSync
3815
+ }),
3816
+ task: stood
3817
+ }, input.channel);
3818
+ })) };
3819
+ },
3820
+ async createdTasks(_caller, { id }) {
3821
+ throw notFound(`no batch of yours has id ${id}`, "batch_not_found");
3822
+ },
3823
+ async claimTask(caller, { id, lease }, signal) {
3824
+ const who = whoOf(caller);
3825
+ const token = newClaimToken();
3826
+ const made = await taskWrite(who, `${await taskPath(who, id, signal)}/claim`, {
3827
+ claimToken: token,
3828
+ leaseSeconds: lease ?? 900
3829
+ }, {
3830
+ id,
3831
+ signal
3832
+ });
3833
+ return {
3834
+ task: await rootOf(who, made),
3835
+ claim: claimOf(made, token)
3836
+ };
3837
+ },
3838
+ async claimReadyTask(caller, input, signal) {
3839
+ const who = whoOf(caller);
3840
+ 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");
3841
+ if (signal.aborted) return { task: null };
3842
+ const path = await onBoard(who, "/tasks/claim");
3843
+ const wait = Math.min(WAIT_MAX_S, Math.ceil(input.wait ?? 0));
3844
+ const token = newClaimToken();
3845
+ const body = {
3846
+ operationId: operationId(),
3847
+ claimToken: token,
3848
+ channel: input.channel,
3849
+ ...input.label && Object.keys(input.label).length ? { labels: input.label } : {},
3850
+ ...input.from?.length ? { from: input.from } : {},
3851
+ leaseSeconds: input.lease ?? 900,
3852
+ ...wait > 0 ? { wait } : {}
3853
+ };
3854
+ const release = async (found) => {
3855
+ if (found.task) await taskWrite(who, `/${encodeURIComponent(found.task.id)}/release`, {
3856
+ claimToken: token,
3857
+ epoch: found.task.epoch
3858
+ }).catch(() => {});
3859
+ };
3860
+ let found;
3861
+ try {
3862
+ found = await api(who, "POST", path, {
3863
+ version: 2,
3864
+ body,
3865
+ signal
3866
+ });
3867
+ } catch (error) {
3868
+ if (signal.aborted) {
3869
+ const { wait: _held, ...again } = body;
3870
+ waitUntil(api(who, "POST", path, {
3871
+ version: 2,
3872
+ body: again
3873
+ }).then(release, () => {}));
3874
+ return { task: null };
3875
+ }
3876
+ throw taskRefusal(error);
3877
+ }
3878
+ const { task } = found;
3879
+ if (!task) return { task: null };
3880
+ if (signal.aborted) {
3881
+ await release(found);
3882
+ return { task: null };
3883
+ }
3884
+ return {
3885
+ task: await rootOf(who, { task }),
3886
+ claim: claimOf({ task }, token)
3887
+ };
3888
+ },
3889
+ async renewTask(caller, { id, epoch, token, lease }, signal) {
3890
+ const who = whoOf(caller);
3891
+ const made = await taskWrite(who, `${await taskPath(who, id, signal)}/renew`, {
3892
+ ...await proofOf({
3893
+ epoch,
3894
+ token
3895
+ }),
3896
+ leaseSeconds: lease ?? 900
3897
+ }, {
3898
+ id,
3899
+ signal
3900
+ });
3901
+ return {
3902
+ task: await rootOf(who, made),
3903
+ until: claimOf(made, token).until
3904
+ };
3905
+ },
3906
+ async releaseTask(caller, { id, epoch, token }, signal) {
3907
+ const who = whoOf(caller);
3908
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/release`, await proofOf({
3909
+ epoch,
3910
+ token
3911
+ }), {
3912
+ id,
3913
+ signal
3914
+ })) };
3915
+ },
3916
+ async completeTask(caller, { id, epoch, token, result }, signal) {
3917
+ const who = whoOf(caller);
3918
+ const body = {
3919
+ ...await proofOf({
3920
+ epoch,
3921
+ token
3922
+ }),
3923
+ ...result !== void 0 ? { result } : {}
3924
+ };
3925
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/complete`, body, {
3926
+ id,
3927
+ signal
3928
+ })) };
3929
+ },
3930
+ async failTask(caller, { id, epoch, token, reason }, signal) {
3931
+ const who = whoOf(caller);
3932
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/fail`, {
3933
+ ...await proofOf({
3934
+ epoch,
3935
+ token
3936
+ }),
3937
+ reason
3938
+ }, {
3939
+ id,
3940
+ signal
3941
+ })) };
3942
+ },
3943
+ async blockTask(caller, { id, reason, kind, epoch, token }, signal) {
3944
+ const who = whoOf(caller);
3945
+ const proof = epoch !== void 0 && token !== void 0 ? await proofOf({
3946
+ epoch,
3947
+ token
3948
+ }) : null;
3949
+ const body = {
3950
+ reason,
3951
+ ...kind !== void 0 ? { kind } : {},
3952
+ ...proof
3953
+ };
3954
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/block`, body, {
3955
+ id,
3956
+ signal
3957
+ })) };
3958
+ },
3959
+ async unblockTask(caller, { id }, signal) {
3960
+ const who = whoOf(caller);
3961
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/unblock`, {}, {
3962
+ id,
3963
+ signal
3964
+ })) };
3965
+ },
3966
+ async reopenTask(caller, { id }, signal) {
3967
+ const who = whoOf(caller);
3968
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/reopen`, {}, {
3969
+ id,
3970
+ signal
3971
+ })) };
3972
+ },
3973
+ async assignTask(caller, { id, for: actor }, signal) {
3974
+ const who = whoOf(caller);
3975
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/assign`, { for: actor }, {
3976
+ id,
3977
+ signal
3978
+ })) };
3979
+ },
3980
+ async setTaskNeeds(caller, { id, needs }, signal) {
3981
+ const who = whoOf(caller);
3982
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/needs`, { needs: needsOf(needs) }, {
3983
+ id,
3984
+ signal
3985
+ })) };
3986
+ },
3987
+ async cancelTask(caller, { id, reason }, signal) {
3988
+ const who = whoOf(caller);
3989
+ return { task: await rootOf(who, await taskWrite(who, `${await taskPath(who, id, signal)}/cancel`, { reason }, {
3990
+ id,
3991
+ signal
3992
+ })) };
3993
+ },
3030
3994
  events: (caller, query, signal) => eventsAs(whoOf(caller), query, signal),
3031
3995
  async typing(caller, { id, status }, signal) {
3032
3996
  if (!binding || binding.sync.length === 0) return { targets: [] };
@@ -3242,7 +4206,8 @@ function createVercel(options, environment) {
3242
4206
  const who = { profile: null };
3243
4207
  const team = await teamId();
3244
4208
  const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
3245
- const url = `${origin}/v1/messageboard${await onBoard(who)}?teamId=${encodeURIComponent(id)}`;
4209
+ const board = await onBoard(who);
4210
+ const url = `${origin}/v1/messageboard${board}?teamId=${encodeURIComponent(id)}`;
3246
4211
  return {
3247
4212
  url,
3248
4213
  headers: {
@@ -3251,7 +4216,11 @@ function createVercel(options, environment) {
3251
4216
  "x-board-can": can
3252
4217
  },
3253
4218
  routes: SANDBOX_ROUTES,
3254
- reads: ["/v1/messageboard/me"]
4219
+ reads: ["/v1/messageboard/me"],
4220
+ under: [{
4221
+ path: `/v2/messageboard${board}`,
4222
+ routes: SANDBOX_TASK_ROUTES
4223
+ }]
3255
4224
  };
3256
4225
  },
3257
4226
  sendsSchedulesHere: false,
@@ -3423,6 +4392,8 @@ function createPolicy(options, keeps, serving, trust = null) {
3423
4392
  return {
3424
4393
  /** Whether requests are served at all: only where the backend keeps the board. */
3425
4394
  open: keeps,
4395
+ /** Whether the verifier names people by their logins, so a grant here names a user by one. */
4396
+ logins: options.authenticate !== void 0 && namesByLogin(options.authenticate),
3426
4397
  project,
3427
4398
  discoveryIdentity,
3428
4399
  /**
@@ -3520,9 +4491,19 @@ function avatarSvg(name) {
3520
4491
  const CREATED = /* @__PURE__ */ new Set([
3521
4492
  "post",
3522
4493
  "schedule",
4494
+ "createTask",
4495
+ "createTasks",
3523
4496
  "upload",
3524
4497
  "uploadFinish"
3525
4498
  ]);
4499
+ /**
4500
+ * Refuses a label write under `board.`: those keys are the board's own, which only its task writes
4501
+ * set, so no caller's write sets or unsets one, this deployment's own code included.
4502
+ */
4503
+ function ownLabels(set, unset = []) {
4504
+ const key = [...Object.keys(set ?? {}), ...unset].find((name) => name.startsWith(RESERVED_LABEL_PREFIX));
4505
+ 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}`);
4506
+ }
3526
4507
  /** Shown inline only when a browser can't run it: everything else downloads. */
3527
4508
  const INLINE = /^(image\/(png|jpeg|gif|webp|avif)|video\/(mp4|webm)|text\/plain)$/;
3528
4509
  /**
@@ -3558,6 +4539,8 @@ async function inputOf(name, request, url, params) {
3558
4539
  case "posted":
3559
4540
  case "synced":
3560
4541
  case "cancelSchedule":
4542
+ case "unblockTask":
4543
+ case "reopenTask":
3561
4544
  case "revokeGrant":
3562
4545
  case "schema":
3563
4546
  case "attachment":
@@ -3575,6 +4558,55 @@ async function inputOf(name, request, url, params) {
3575
4558
  case "post": return PostBody.parse(await body());
3576
4559
  case "createChannel": return CreateChannelBody.parse(await body());
3577
4560
  case "schedule": return ScheduleBody.parse(await body());
4561
+ case "tasks": return TasksQuery.parse(queryObject(url));
4562
+ case "createTask": return CreateTaskBody.parse(await body());
4563
+ case "createdTasks": return {
4564
+ id,
4565
+ ...CreatedTasksQuery.parse(queryObject(url))
4566
+ };
4567
+ case "createTasks": {
4568
+ const sent = await body();
4569
+ const tasks = sent?.tasks;
4570
+ if (Array.isArray(tasks) && tasks.length > 100) throw batchTooLarge(tasks.length, 100);
4571
+ return CreateTasksBody.parse(sent);
4572
+ }
4573
+ case "claimReadyTask": return ClaimReadyTaskBody.parse(await body());
4574
+ case "claimTask": return {
4575
+ id,
4576
+ ...ClaimTaskBody.parse(await body()) ?? {}
4577
+ };
4578
+ case "renewTask": return {
4579
+ id,
4580
+ ...RenewTaskBody.parse(await body())
4581
+ };
4582
+ case "releaseTask": return {
4583
+ id,
4584
+ ...ReleaseTaskBody.parse(await body())
4585
+ };
4586
+ case "completeTask": return {
4587
+ id,
4588
+ ...CompleteTaskBody.parse(await body())
4589
+ };
4590
+ case "failTask": return {
4591
+ id,
4592
+ ...FailTaskBody.parse(await body())
4593
+ };
4594
+ case "blockTask": return {
4595
+ id,
4596
+ ...BlockTaskBody.parse(await body())
4597
+ };
4598
+ case "assignTask": return {
4599
+ id,
4600
+ ...AssignTaskBody.parse(await body())
4601
+ };
4602
+ case "setTaskNeeds": return {
4603
+ id,
4604
+ ...TaskNeedsBody.parse(await body())
4605
+ };
4606
+ case "cancelTask": return {
4607
+ id,
4608
+ ...CancelTaskBody.parse(await body())
4609
+ };
3578
4610
  case "createGrant": return GrantBody.parse(await body());
3579
4611
  case "updateGrant": return {
3580
4612
  id,
@@ -3828,6 +4860,77 @@ async function createServe(context) {
3828
4860
  * then the backend's refusal is the answer, not what the text says. A message board() can't find
3829
4861
  * for the caller is still checked, since one written without reading is its author's to edit.
3830
4862
  */
4863
+ /**
4864
+ * Settles the `@handle`s of a caller's texts: a mention is `@[actor-id]`, so a handle that names
4865
+ * exactly one of the actors the caller can see is written as that, and one that names none or
4866
+ * several stays as typed, a mention of no one. Of several, it's the one who wrote in `thread`, if
4867
+ * exactly one did. The actors are read once, for the first text that has a handle. A board behind
4868
+ * this one settles them itself, and a schedule's send goes as it was settled when it was made: a
4869
+ * handle that mentioned no one then mentions no one later. An ID is longer than a handle, so where
4870
+ * settling would take a text past what a message holds, it stays as typed, each handle's actor a
4871
+ * candidate: the writer is never refused for a length they didn't type.
4872
+ */
4873
+ function settler(caller, signal) {
4874
+ let listed = null;
4875
+ const actors = () => listed ??= backend.actors(caller, {}, signal).then((answer) => answer.actors.map(({ id, handle, name }) => ({
4876
+ id,
4877
+ handle,
4878
+ name
4879
+ })), (error) => {
4880
+ if (error instanceof HttpError && (error.status === 403 || error.status === 404)) return [];
4881
+ throw error;
4882
+ });
4883
+ return async (text, thread) => {
4884
+ if (backend.settlesMentions || caller.origin.via?.kind === "schedule" || !extractMentions(text).some((token) => token.kind === "handle")) return {
4885
+ text,
4886
+ mentions: []
4887
+ };
4888
+ const fitting = (settled) => settled.text.length <= 1e4 || text.length > 1e4 ? settled : {
4889
+ text,
4890
+ mentions: settled.mentions.map(unsettled)
4891
+ };
4892
+ const settled = settleMentions(text, await actors());
4893
+ if (!settled.mentions.some((mention) => mention.candidates.length > 1)) return fitting(settled);
4894
+ const id = await thread();
4895
+ const writers = /* @__PURE__ */ new Set();
4896
+ if (id !== void 0) try {
4897
+ const { message, replies } = await backend.message(caller, { id }, signal);
4898
+ for (const written of [message, ...replies]) writers.add(written.by.actor);
4899
+ } catch (error) {
4900
+ if (!(error instanceof HttpError && error.status === 404)) throw error;
4901
+ }
4902
+ return fitting(settleMentions(text, await actors(), (candidates) => {
4903
+ const wrote = candidates.filter((actor) => writers.has(actor.id));
4904
+ return wrote.length === 1 ? wrote[0] : null;
4905
+ }));
4906
+ };
4907
+ }
4908
+ /** A handle that would have mentioned an actor, said as one that didn't: still text, and they're who it could have meant. */
4909
+ const unsettled = (mention) => mention.actor ? {
4910
+ written: mention.written,
4911
+ actor: null,
4912
+ candidates: [mention.actor]
4913
+ } : mention;
4914
+ /**
4915
+ * Hands `write` a text with its `@handle`s settled, as `settler` does, and adds what became of each
4916
+ * to its answer. `kept` is the text the answer came back with: where that isn't the one written, a
4917
+ * retry got the message its first try made, and a handle is said to mention only who that text does.
4918
+ */
4919
+ async function settling(caller, text, thread, signal, write, kept) {
4920
+ const settled = await settler(caller, signal)(text, thread);
4921
+ const answer = await write(settled.text);
4922
+ if (settled.mentions.length === 0) return answer;
4923
+ const stored = kept?.(answer) ?? settled.text;
4924
+ if (stored === settled.text) return {
4925
+ ...answer,
4926
+ mentions: settled.mentions
4927
+ };
4928
+ const mentioned = new Set(extractMentions(stored).flatMap((token) => token.kind === "actor" ? [token.actor] : []));
4929
+ return {
4930
+ ...answer,
4931
+ mentions: settled.mentions.map((mention) => mention.actor && !mentioned.has(mention.actor.id) ? unsettled(mention) : mention)
4932
+ };
4933
+ }
3831
4934
  async function checkWrite(caller, text, where, signal) {
3832
4935
  if (!text.includes("json#")) return;
3833
4936
  const access = accessOf(caller);
@@ -3844,7 +4947,10 @@ async function createServe(context) {
3844
4947
  author,
3845
4948
  source,
3846
4949
  board: () => middlewareBoard ??= handleOf(MIDDLEWARE, null)
3847
- }, commit);
4950
+ }, (passed) => {
4951
+ if (passed.kind === "post") ownLabels(passed.labels);
4952
+ return commit(passed);
4953
+ });
3848
4954
  /** Whether a lookup found what it looked for: a 404 says it didn't. */
3849
4955
  async function found(lookup) {
3850
4956
  try {
@@ -3903,6 +5009,60 @@ async function createServe(context) {
3903
5009
  }));
3904
5010
  }
3905
5011
  /**
5012
+ * A digest of what a batch asks for, as it was given: its channel and its tasks, as many, in the
5013
+ * same order, each with the same key, text, labels, `noSync`, files, needs, and assignee. A field
5014
+ * left out is its empty value. A batch made under an `id` is that `id`'s only for the same one.
5015
+ */
5016
+ async function batchRequest(body) {
5017
+ const tasks = body.tasks.map((task) => [
5018
+ task.key ?? null,
5019
+ task.text,
5020
+ Object.entries(task.labels ?? {}).sort(([a], [b]) => a < b ? -1 : 1),
5021
+ task.noSync ?? false,
5022
+ task.attachments ?? [],
5023
+ task.needs ?? [],
5024
+ task.for ?? null
5025
+ ]);
5026
+ return (await sha256(JSON.stringify([body.channel, tasks]))).slice(0, 32);
5027
+ }
5028
+ /**
5029
+ * A batch's roots through the middleware, each as the post it is, in order, then `send` with what
5030
+ * it passed on: every one before any is written, so a root it drops makes none of them. A batch
5031
+ * that wouldn't land goes as it came, for the backend to say why. One that landed already never
5032
+ * gets here: its retry is answered before.
5033
+ */
5034
+ async function screenTasks(caller, input, signal, send) {
5035
+ const source = sourceOf(caller);
5036
+ if (middleware.length === 0 || source === null) return send(input.tasks);
5037
+ const { channel } = input;
5038
+ const access = accessOf(caller);
5039
+ const labels = input.tasks.some((task) => Object.keys(task.labels ?? {}).length > 0);
5040
+ if (access && (!access.can("post", channel) || labels && !access.can("label", channel))) return send(input.tasks);
5041
+ const { actor } = await whoIs(caller, signal);
5042
+ const passed = [];
5043
+ const from = async (at) => {
5044
+ const task = input.tasks[at];
5045
+ if (!task) return send(passed);
5046
+ const attachments = await attachmentsOf(caller, task.attachments, signal);
5047
+ return screen({
5048
+ kind: "post",
5049
+ channel,
5050
+ re: null,
5051
+ text: task.text,
5052
+ labels: task.labels ?? {},
5053
+ attachments
5054
+ }, actor, source, (write) => {
5055
+ passed.push({
5056
+ ...task,
5057
+ text: write.text,
5058
+ ...task.labels || Object.keys(write.labels).length > 0 ? { labels: write.labels } : {}
5059
+ });
5060
+ return from(at + 1);
5061
+ });
5062
+ };
5063
+ return from(0);
5064
+ }
5065
+ /**
3906
5066
  * A schedule, on a backend whose sends post elsewhere: its message through the middleware once,
3907
5067
  * as the caller's post of it, since its text and labels never change and no send comes back here.
3908
5068
  */
@@ -3917,11 +5077,11 @@ async function createServe(context) {
3917
5077
  ...attachments ? { attachments } : {}
3918
5078
  }, signal, async (screened) => {
3919
5079
  if (screened.text !== text) await checkBlocks(screened.text);
3920
- return backend.schedule(caller, {
5080
+ return settling(caller, screened.text, async () => re, signal, (settled) => backend.schedule(caller, {
3921
5081
  ...input,
3922
- text: screened.text,
5082
+ text: settled,
3923
5083
  ...screened.labels ? { labels: screened.labels } : {}
3924
- }, signal);
5084
+ }, signal));
3925
5085
  });
3926
5086
  }
3927
5087
  /**
@@ -3988,16 +5148,32 @@ async function createServe(context) {
3988
5148
  return id === null ? null : lookup(caller, id, signal);
3989
5149
  }
3990
5150
  /**
5151
+ * An import with only the platform users its text mentions, as it lands: one the sync function or
5152
+ * the middleware wrote out of it isn't introduced to the board.
5153
+ */
5154
+ function introducing(body) {
5155
+ if (body.op !== "post" && body.op !== "edit" || !body.mentioned?.length) return body;
5156
+ const named = new Set(extractMentions(body.text).flatMap((token) => token.kind === "actor" ? [token.actor] : []));
5157
+ const { mentioned: all, ...rest } = body;
5158
+ const mentioned = all.filter((user) => named.has(user.id));
5159
+ return mentioned.length ? {
5160
+ ...rest,
5161
+ mentioned
5162
+ } : rest;
5163
+ }
5164
+ /**
3991
5165
  * An import, through the middleware when it's a post or an edit that would land: what the
3992
5166
  * middleware passed on, or what it responded when it dropped it, for sync to tell the author on
3993
5167
  * the platform. A retry of one that landed stands.
3994
5168
  */
3995
5169
  async function syncImport(caller, body, signal) {
5170
+ if (body.op === "post") ownLabels(body.labels);
5171
+ if (body.op === "labels") ownLabels(body.set, body.unset);
3996
5172
  const written = (body.op === "post" || body.op === "edit") && body.from === null ? body.text : null;
3997
5173
  if (written !== null) await checkBlocks(written);
3998
5174
  const send = async (patched) => {
3999
5175
  if (written !== null && (patched.op === "post" || patched.op === "edit") && patched.text !== written) await checkBlocks(patched.text);
4000
- return backend.syncImport(caller, patched, signal);
5176
+ return backend.syncImport(caller, introducing(patched), signal);
4001
5177
  };
4002
5178
  if (middleware.length === 0 || caller.origin.via?.kind === "middleware" || body.op !== "post" && body.op !== "edit") return send(body);
4003
5179
  const access = accessOf(caller);
@@ -4074,7 +5250,10 @@ async function createServe(context) {
4074
5250
  await checkWrite(caller, input.text, input.channel !== void 0 ? { channel: input.channel } : { message: input.re }, signal);
4075
5251
  const send = (poster, body) => screenPost(poster, body, signal, async (patched) => {
4076
5252
  if (patched.text !== input.text) await checkBlocks(patched.text);
4077
- return backend.post(poster, patched, signal);
5253
+ return settling(poster, patched.text, async () => patched.re, signal, (text) => backend.post(poster, {
5254
+ ...patched,
5255
+ text
5256
+ }, signal), (answer) => answer.message.text);
4078
5257
  });
4079
5258
  if (!engine) return send(caller, input.sync?.length ? {
4080
5259
  ...input,
@@ -4210,20 +5389,98 @@ async function createServe(context) {
4210
5389
  /** The protocol method `name`, as board() serves it: what it posts, edits, and imports goes through the middleware. */
4211
5390
  async function invoke(name, caller, input, signal) {
4212
5391
  switch (name) {
4213
- case "post": return post(caller, input, signal);
5392
+ case "post":
5393
+ ownLabels(input.labels);
5394
+ return post(caller, input, signal);
5395
+ case "label": {
5396
+ const { set, unset } = input;
5397
+ ownLabels(set, unset);
5398
+ return backend.label(caller, input, signal);
5399
+ }
5400
+ case "createTask": {
5401
+ const body = input;
5402
+ ownLabels(body.labels);
5403
+ if (body.channel === void 0) return backend.createTask(caller, body, signal);
5404
+ const { channel, labels, noSync, attachments, id } = body;
5405
+ const sent = body.text ?? "";
5406
+ await checkWrite(caller, sent, { channel }, signal);
5407
+ return screenPost(caller, {
5408
+ channel,
5409
+ text: sent,
5410
+ ...labels ? { labels } : {},
5411
+ ...noSync !== void 0 ? { noSync } : {},
5412
+ ...attachments ? { attachments } : {},
5413
+ ...id !== void 0 ? { id } : {}
5414
+ }, signal, async (screened) => {
5415
+ if (screened.text !== sent) await checkBlocks(screened.text);
5416
+ return settling(caller, screened.text, async () => void 0, signal, (text) => backend.createTask(caller, {
5417
+ ...body,
5418
+ text,
5419
+ ...screened.labels ? { labels: screened.labels } : {}
5420
+ }, signal), (answer) => answer.task.text);
5421
+ });
5422
+ }
5423
+ case "createTasks": {
5424
+ const body = input;
5425
+ for (const task of body.tasks) ownLabels(task.labels);
5426
+ const request = body.id !== void 0 ? body.request ?? await batchRequest(body) : void 0;
5427
+ if (body.id !== void 0) try {
5428
+ return await backend.createdTasks(caller, {
5429
+ id: body.id,
5430
+ request
5431
+ }, signal);
5432
+ } catch (error) {
5433
+ if (!(error instanceof HttpError && error.status === 404 && error.code === "batch_not_found")) throw error;
5434
+ }
5435
+ for (const task of body.tasks) await checkWrite(caller, task.text, { channel: body.channel }, signal);
5436
+ return screenTasks(caller, body, signal, async (tasks) => {
5437
+ for (const [at, task] of tasks.entries()) if (task.text !== body.tasks[at].text) await checkBlocks(task.text);
5438
+ const settle = settler(caller, signal);
5439
+ const mentions = [];
5440
+ const settled = [];
5441
+ for (const task of tasks) {
5442
+ const root = await settle(task.text, async () => void 0);
5443
+ settled.push(root.text === task.text ? task : {
5444
+ ...task,
5445
+ text: root.text
5446
+ });
5447
+ for (const mention of root.mentions) if (!mentions.some((said) => said.written === mention.written)) mentions.push(mention);
5448
+ }
5449
+ const answer = await backend.createTasks(caller, {
5450
+ ...body,
5451
+ tasks: settled,
5452
+ request
5453
+ }, signal);
5454
+ return mentions.length > 0 ? {
5455
+ ...answer,
5456
+ mentions
5457
+ } : answer;
5458
+ });
5459
+ }
4214
5460
  case "edit": {
4215
5461
  const edit = input;
4216
5462
  await checkWrite(caller, edit.text, { message: edit.id }, signal);
4217
5463
  return screenEdit(caller, edit, signal, async (patched) => {
4218
5464
  if (patched.text !== edit.text) await checkBlocks(patched.text);
4219
- return backend.edit(caller, patched, signal);
5465
+ const thread = async () => {
5466
+ const edited = await lookup(caller, edit.id, signal);
5467
+ return edited ? edited.re ?? edited.id : void 0;
5468
+ };
5469
+ return settling(caller, patched.text, thread, signal, (text) => backend.edit(caller, {
5470
+ ...patched,
5471
+ text
5472
+ }, signal));
4220
5473
  });
4221
5474
  }
4222
5475
  case "syncImport": return syncImport(caller, input, signal);
4223
5476
  case "schedule": {
4224
5477
  const body = input;
5478
+ ownLabels(body.labels);
4225
5479
  await checkWrite(caller, body.text, body.channel !== void 0 ? { channel: body.channel } : { message: body.re }, signal);
4226
- return backend.sendsSchedulesHere === false ? screenSchedule(caller, body, signal) : backend.schedule(caller, body, signal);
5480
+ return backend.sendsSchedulesHere === false ? screenSchedule(caller, body, signal) : settling(caller, body.text, async () => body.re, signal, (text) => backend.schedule(caller, {
5481
+ ...body,
5482
+ text
5483
+ }, signal));
4227
5484
  }
4228
5485
  case "inbox": {
4229
5486
  const query = input;
@@ -4412,9 +5669,10 @@ async function createServe(context) {
4412
5669
  return {
4413
5670
  dispatch,
4414
5671
  async inject(request, caller, trigger, writes) {
4415
- if (trigger !== null && request.method === "POST" && new URL(request.url).pathname.endsWith("/messages")) {
5672
+ const pathname = new URL(request.url).pathname;
5673
+ if (trigger !== null && request.method === "POST" && (pathname.endsWith("/messages") || pathname.endsWith("/tasks") || pathname.endsWith("/tasks/batch"))) {
4416
5674
  const body = await request.json() ?? {};
4417
- body.id ??= await derivedId("board-inbound", trigger, "client", String(writes.made++));
5675
+ if (pathname.endsWith("/messages") || body.channel !== void 0) body.id ??= await derivedId("board-inbound", trigger, "client", String(writes.made++));
4418
5676
  request = new Request(request.url, {
4419
5677
  method: "POST",
4420
5678
  headers: request.headers,
@@ -4672,6 +5930,11 @@ function createBoard(options, runtime) {
4672
5930
  post: async (channel, input) => client.post(channel, await owned(input)),
4673
5931
  reply: async (re, input) => client.reply(re, await owned(input)),
4674
5932
  posted: async (given) => client.posted(await id(given)),
5933
+ tasks: {
5934
+ ...client.tasks,
5935
+ create: (async (target, input) => typeof target === "string" ? client.tasks.create(target, await owned(input)) : client.tasks.create(target, input)),
5936
+ createMany: async (channel, tasks, opts = {}) => client.tasks.createMany(channel, tasks, opts.id !== void 0 ? { id: await id(opts.id) } : opts)
5937
+ },
4675
5938
  request: (path, init = {}) => {
4676
5939
  const { as: profile, ...rest } = init;
4677
5940
  return profile !== void 0 ? asFrom(caller, stop)(profile).request(path, rest) : client.request(path, rest);
@@ -4755,6 +6018,7 @@ function createBoard(options, runtime) {
4755
6018
  accessNow: (principal, grants) => policy.accessNow(principal, grants),
4756
6019
  explain: (principal, channel) => policy.explain(principal, channel),
4757
6020
  project: () => policy.project(),
6021
+ logins: policy.logins,
4758
6022
  handle: (caller) => handleOf(caller, null),
4759
6023
  url: ownUrl
4760
6024
  };
@@ -4807,4 +6071,73 @@ async function* events(client, query = {}, opts = {}) {
4807
6071
  }
4808
6072
  }
4809
6073
  //#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 };
6074
+ //#region src/client/chunks.ts
6075
+ /**
6076
+ * A chunk failed, with the chunks before it made: `code`, `status`, and `message` are the failure's
6077
+ * own, and `created` holds the tasks that were made, each at its task's place in the `tasks` given,
6078
+ * with `undefined` for the ones that weren't.
6079
+ */
6080
+ var TasksInChunksError = class extends BoardError {
6081
+ created;
6082
+ constructor(cause, created) {
6083
+ const failed = cause instanceof BoardError ? cause : null;
6084
+ super(failed?.code ?? "chunk_failed", cause instanceof Error ? cause.message : String(cause), failed?.status ?? 0, {
6085
+ ...failed?.hint !== void 0 ? { hint: failed.hint } : {},
6086
+ origin: failed?.origin ?? "handle"
6087
+ });
6088
+ this.name = "TasksInChunksError";
6089
+ this.cause = cause;
6090
+ this.created = created;
6091
+ }
6092
+ };
6093
+ /**
6094
+ * Makes `tasks` in `channel` with as many `tasks.createMany` calls as it takes, and answers their
6095
+ * roots in the order given. It makes each task after the ones it waits for by `key`, names a task
6096
+ * an earlier chunk made by the ID it got, and sends fewer when a board answers `batch_too_large`:
6097
+ * 50, then 25, down to one. With `id`, each chunk goes under an ID made from it and where the
6098
+ * chunk starts, and the plan's last task says the plan ends with it. So calling again with the
6099
+ * same `id` and tasks answers the chunks that landed and makes the rest. What landed can't change
6100
+ * and a plan that finished takes no more, wherever its chunks ended: both are a 409
6101
+ * `duplicate_id`, with nothing new made. What a call that stopped midway didn't make can still
6102
+ * change.
6103
+ *
6104
+ * It isn't one write. Each chunk is all or nothing, and the chunks land one after another: a task
6105
+ * of an earlier chunk that's ready can be claimed before a later chunk lands. When a chunk fails
6106
+ * it stops and throws a `TasksInChunksError`, whose `created` has what the chunks before it made.
6107
+ * A plan that must not start early waits for a task of the caller's own, which it completes once
6108
+ * this returns.
6109
+ */
6110
+ async function createTasksInChunks(board, channel, tasks, options = {}) {
6111
+ const plan = batchPlan(tasks);
6112
+ if ("problem" in plan) throw new BoardError("invalid_needs", `needs: ${plan.problem}`, 400);
6113
+ const { order } = plan;
6114
+ const places = new Map(tasks.flatMap((task, at) => task.key !== void 0 ? [[task.key, at]] : []));
6115
+ const created = tasks.map(() => void 0);
6116
+ let size = 100;
6117
+ for (let from = 0; from < order.length;) {
6118
+ const picked = order.slice(from, from + size);
6119
+ const names = new Map(picked.map((at, n) => [at, from + n === order.length - 1 ? "end" : String(n)]));
6120
+ const chunk = picked.map((at) => {
6121
+ const { needs, ...task } = tasks[at];
6122
+ const waits = needs?.map((need) => typeof need === "string" ? need : created[places.get(need.key)]?.id ?? { key: names.get(places.get(need.key)) });
6123
+ return {
6124
+ ...task,
6125
+ key: names.get(at),
6126
+ ...waits ? { needs: waits } : {}
6127
+ };
6128
+ });
6129
+ try {
6130
+ const made = await board.tasks.createMany(channel, chunk, options.id !== void 0 ? { id: `${options.id}/${from}` } : {});
6131
+ for (const [n, at] of picked.entries()) created[at] = made[n];
6132
+ from += picked.length;
6133
+ } catch (error) {
6134
+ 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);
6135
+ do
6136
+ size = Math.ceil(size / 2);
6137
+ while (size >= picked.length);
6138
+ }
6139
+ }
6140
+ return created;
6141
+ }
6142
+ //#endregion
6143
+ 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 };