@vercel/board 0.48.1 → 0.50.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 (87) hide show
  1. package/dist/{access-C06pIr0M.mjs → access-BbgmsAFF.mjs} +29 -17
  2. package/dist/access.d.mts +2 -2
  3. package/dist/access.mjs +5 -5
  4. package/dist/{actors-Dkyg-oo0.mjs → actors-CX2D22hL.mjs} +4 -3
  5. package/dist/{auth-B9-wXQ-x.mjs → auth-DJDTfgAL.mjs} +2 -2
  6. package/dist/{auth-li3lKwJG.d.mts → auth-Z9-Khvvw.d.mts} +1 -1
  7. package/dist/{backend-UBP6HimX.d.mts → backend-CcaaS9Xl.d.mts} +31 -8
  8. package/dist/backend-local.d.mts +1 -1
  9. package/dist/backend-local.mjs +1 -1
  10. package/dist/{chat-provider-iN0DFsSE.d.mts → chat-provider-DQ1GHm4o.d.mts} +2 -2
  11. package/dist/{chat-provider-kNWd6MQC.mjs → chat-provider-HJ7y_ipp.mjs} +2 -2
  12. package/dist/cli-commands.d.mts +1 -1
  13. package/dist/cli-commands.mjs +1 -1
  14. package/dist/cli-embedded.d.mts +8 -2
  15. package/dist/cli-embedded.mjs +10 -4
  16. package/dist/cli.mjs +6 -6
  17. package/dist/client-C2T4eaXd.d.mts +544 -0
  18. package/dist/{commands-CJsOA-hf.d.mts → commands-Cm4sODIu.d.mts} +12 -8
  19. package/dist/{commands-Dk6_cHLS.mjs → commands-nN8WpvCe.mjs} +75 -58
  20. package/dist/{conformance-CDP8y2Zm.mjs → conformance-Cr-umDl0.mjs} +102 -20
  21. package/dist/conformance.d.mts +1 -1
  22. package/dist/conformance.mjs +1 -1
  23. package/dist/{engine-BQ0hJw2w.mjs → engine-DJZ8Xy_g.mjs} +10 -7
  24. package/dist/{errors-QhkdzI-o.mjs → errors-DYF4hhIc.mjs} +53 -174
  25. package/dist/{events-B-qyxNsJ.mjs → events-BdOCmnZh.mjs} +3 -3
  26. package/dist/{exports-BzSG0_wL.mjs → exports-CuD-Mxkw.mjs} +389 -118
  27. package/dist/{exports-inhbjAWi.d.mts → exports-lmr6UHHc.d.mts} +4 -4
  28. package/dist/{external-BuVTXT1R.mjs → external-D2jq_DEQ.mjs} +1 -1
  29. package/dist/{index-B0Fnhvk7.d.mts → index-_KxJu15n.d.mts} +2 -2
  30. package/dist/index.d.mts +6 -6
  31. package/dist/index.mjs +4 -4
  32. package/dist/index.node.d.mts +7 -7
  33. package/dist/index.node.mjs +4 -4
  34. package/dist/inspect/app.js +39 -39
  35. package/dist/inspect/engine.js +3 -3
  36. package/dist/inspect-CZeoSm7E.mjs +272 -0
  37. package/dist/inspect-UCcPViyA.mjs +2 -0
  38. package/dist/inspect.d.mts +17 -0
  39. package/dist/inspect.mjs +196 -0
  40. package/dist/{local-BdKxz-Dn.mjs → local-BVSFSSYf.mjs} +165 -61
  41. package/dist/{main-BgiViRZ8.mjs → main-B016auoG.mjs} +227 -49
  42. package/dist/{memory-CMm-Fk_A.mjs → memory-C2lzMV_t.mjs} +2 -2
  43. package/dist/{middleware-CT6vMNUc.mjs → middleware-DUKIITFZ.mjs} +3 -3
  44. package/dist/{page-D-OzDOAX.mjs → page-7KWSGxyC.mjs} +12 -2
  45. package/dist/page-CN77B014.mjs +2 -0
  46. package/dist/profile-header-Cj0Cb1cf.mjs +163 -0
  47. package/dist/{provider-DC3WHUXo.d.mts → provider-Dwb_9mnu.d.mts} +3 -529
  48. package/dist/{routes-CjA6Mp4D.d.mts → routes-B6SEA9yw.d.mts} +130 -4
  49. package/dist/{routes-ABXf3CKq.mjs → routes-BE0y6wCk.mjs} +40 -14
  50. package/dist/{schemas-7VFdomFB.mjs → schemas-CUSTEFIy.mjs} +11 -3
  51. package/dist/{serve-C2Jbr7pR.mjs → serve-B10e7QaY.mjs} +5 -5
  52. package/dist/{server-EOQC5Gtq.mjs → server-ViWNvg5q.mjs} +61 -29
  53. package/dist/{serving-BNdiReQT.mjs → serving-SbqeWqlA.mjs} +1 -1
  54. package/dist/{inspect-n9brh-TT.mjs → shell-DmpmgOPC.mjs} +25 -274
  55. package/dist/{sql-IEbO5vXs.mjs → sql-iABdyCiz.mjs} +18 -5
  56. package/dist/{sqlite-CVG8XKHm.mjs → sqlite-28EMrmk7.mjs} +2 -2
  57. package/dist/{sqlite-db-BJjPQYx4.mjs → sqlite-db-Ckd-ceNe.mjs} +1 -1
  58. package/dist/sync-chat-sdk.d.mts +2 -2
  59. package/dist/sync-chat-sdk.mjs +2 -2
  60. package/dist/sync-github.d.mts +2 -2
  61. package/dist/sync-github.mjs +3 -3
  62. package/dist/sync-linear.d.mts +3 -3
  63. package/dist/sync-linear.mjs +3 -3
  64. package/dist/sync-slack.d.mts +3 -3
  65. package/dist/sync-slack.mjs +11 -7
  66. package/dist/sync.d.mts +2 -2
  67. package/dist/sync.mjs +2 -2
  68. package/dist/{tags-BpFo6q0_.mjs → tags-D0qra0Qy.mjs} +1 -1
  69. package/dist/{task-batch-D4p9N8lN.mjs → task-batch-9lVDG3d-.mjs} +10 -11
  70. package/dist/{tokens-BCp4EWTQ.mjs → tokens-C-iK0Cku.mjs} +2 -2
  71. package/dist/version-C70RLVEK.mjs +5 -0
  72. package/docs/01-board/01-mounting.md +8 -0
  73. package/docs/01-board/03-identity.md +3 -2
  74. package/docs/01-board/04-messages.md +6 -2
  75. package/docs/01-board/05-reading.md +17 -2
  76. package/docs/01-board/09-access.md +40 -6
  77. package/docs/01-board/11-tasks.md +3 -3
  78. package/docs/02-sync/01-overview.md +2 -1
  79. package/docs/03-guides/02-inspector.md +31 -0
  80. package/docs/03-guides/06-sandboxed-agents.md +22 -21
  81. package/docs/04-reference/01-cli.md +91 -33
  82. package/docs/04-reference/02-board.md +20 -7
  83. package/docs/04-reference/03-http.md +9 -6
  84. package/docs/04-reference/05-conformance.md +7 -0
  85. package/package.json +5 -1
  86. package/dist/inspect-BB-XUPuz.mjs +0 -2
  87. package/dist/page-Dr9Aqlej.mjs +0 -2
@@ -1,13 +1,15 @@
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";
1
+ import { i as ATTACHMENT_BYTES_MAX, l as mediaType, n as formatProfileHeader, o as IMPORT_BYTES_MAX, s as fileName } from "./profile-header-Cj0Cb1cf.mjs";
2
+ import { T as TASK_LABEL, b as RemoteWatcherId, y as RESERVED_LABEL_PREFIX } from "./schemas-CUSTEFIy.mjs";
3
+ import { A as Ref, B as SyncBody, C as InboxQuery, D as MessagesQuery, E as MatchesQuery, F as ScheduleBody, G as TaskNeedsBody, H as SyncFindQuery, I as SchedulesQuery, J as TypingBody, K as TasksQuery, L as SchemaBody, M as ReleaseTaskBody, N as RenewTaskBody, O as PostBody, P as RevokeGrantBody, R as SourceJoinBody, S as InboxPushBody, T as LinkedQuery, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, X as UploadStartBody, Y as UpdateGrantBody, Z as routes, _ as FailTaskBody, a as ClaimReadyTaskBody, b as InboxAckBody, c as CreateChannelBody, d as CreateTasksBody, f as CreatedTasksQuery, g as ExplainQuery, h as EventsQuery, i as CancelTaskBody, j as RegisterBody, k as ReactBody, l as CreateGrantsBody, m as EditBody, n as AssignTaskBody, o as ClaimTaskBody, p as DeleteBody, q as ThreadsQuery, r as BlockTaskBody, s as CompleteTaskBody, t as AckBody, u as CreateTaskBody, w as LabelBody, x as InboxNextQuery, y as GrantBody, z as SourceReadQuery } from "./routes-BE0y6wCk.mjs";
4
+ import { 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 } from "./errors-DYF4hhIc.mjs";
5
+ 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-DUKIITFZ.mjs";
5
6
  import { n as blocksIn, r as findBlocks } from "./blocks-CVoBC7ur.mjs";
6
7
  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-D4p9N8lN.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";
8
+ import { t as VERSION } from "./version-C70RLVEK.mjs";
9
+ 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-BbgmsAFF.mjs";
10
+ import { a as runMatch, d as openapi, f as queryObject, 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-9lVDG3d-.mjs";
11
+ 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-DJDTfgAL.mjs";
12
+ import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-CX2D22hL.mjs";
11
13
  import { t as checkValue } from "./data-values-CoTP0SQG.mjs";
12
14
  //#region src/server/registrant.ts
13
15
  /** Registering again this soon after the same registration only repeats it. */
@@ -309,6 +311,8 @@ const sleep = (ms, signal) => new Promise((resolve) => {
309
311
  });
310
312
  //#endregion
311
313
  //#region src/server/sandbox.ts
314
+ /** What `vb` in a sandbox sends as its credential, for the policy's proxy to replace. */
315
+ const SANDBOX_TOKEN = "set-by-the-network-policy";
312
316
  /** Outside Node there's no deployment credential to find: a sandbox's policy needs the one it's given. */
313
317
  const withoutToken = (url) => {
314
318
  throw new HttpError(400, "no_token", `There's no credential here to hand a sandbox for ${url}: pass one, sandboxPolicy({ token }).`, { origin: "handle" });
@@ -382,6 +386,7 @@ const refused = (why) => ({ response: {
382
386
  * The policy that hands the board `reach` names to a sandbox: its host, and on it only the board's
383
387
  * own routes, under its URL's path and with its query (`teamId`), each request carrying `reach`'s
384
388
  * headers. Anything else on the host is refused there; any other host, the sandbox doesn't reach.
389
+ * Its `env` points `vb` in the sandbox at the board.
385
390
  */
386
391
  function boardPolicy(reach) {
387
392
  const url = new URL(reach.url);
@@ -395,34 +400,40 @@ function boardPolicy(reach) {
395
400
  queryString: query
396
401
  } : match;
397
402
  const transform = [{ headers: { ...reach.headers } }];
398
- return { allow: { [url.host]: [
399
- {
400
- match: { path: { regex: "(?:^|/)\\.\\.?(?:/|$)|%2[eEfF]|%5[cC]|\\\\" } },
401
- ...refused("not a board route")
402
- },
403
- {
404
- match: { queryString: [{ key: { regex: `^${caseless("x-vercel-set-bypass-cookie")}$` } }] },
405
- ...refused("not a board route")
406
- },
407
- {
408
- match: { headers: [{ key: { exact: "x-vercel-set-bypass-cookie" } }] },
409
- ...refused("not a board route")
410
- },
411
- ...routeRules(prefix, reach.routes, scoped, transform),
412
- ...(reach.under ?? []).flatMap(({ path, routes }) => routeRules(escaped(path.replace(/\/+$/, "")), routes, scoped, transform)),
413
- ...(reach.reads ?? []).map((path) => ({
414
- match: scoped({
415
- path: { exact: path },
416
- method: ["GET"]
417
- }),
418
- transform
419
- })),
420
- {
421
- match: { path: { regex: `^${prefix}/(?:${WITHHELD.map(caseless).join("|")})(?:/|$)` } },
422
- ...refused("not a route this sandbox's policy hands it")
423
- },
424
- refused("not this board's")
425
- ] } };
403
+ return {
404
+ allow: { [url.host]: [
405
+ {
406
+ match: { path: { regex: "(?:^|/)\\.\\.?(?:/|$)|%2[eEfF]|%5[cC]|\\\\" } },
407
+ ...refused("not a board route")
408
+ },
409
+ {
410
+ match: { queryString: [{ key: { regex: `^${caseless("x-vercel-set-bypass-cookie")}$` } }] },
411
+ ...refused("not a board route")
412
+ },
413
+ {
414
+ match: { headers: [{ key: { exact: "x-vercel-set-bypass-cookie" } }] },
415
+ ...refused("not a board route")
416
+ },
417
+ ...routeRules(prefix, reach.routes, scoped, transform),
418
+ ...(reach.under ?? []).flatMap(({ path, routes }) => routeRules(escaped(path.replace(/\/+$/, "")), routes, scoped, transform)),
419
+ ...(reach.reads ?? []).map((path) => ({
420
+ match: scoped({
421
+ path: { exact: path },
422
+ method: ["GET"]
423
+ }),
424
+ transform
425
+ })),
426
+ {
427
+ match: { path: { regex: `^${prefix}/(?:${WITHHELD.map(caseless).join("|")})(?:/|$)` } },
428
+ ...refused("not a route this sandbox's policy hands it")
429
+ },
430
+ refused("not this board's")
431
+ ] },
432
+ env: {
433
+ BOARD_URL: reach.url,
434
+ BOARD_TOKEN: SANDBOX_TOKEN
435
+ }
436
+ };
426
437
  }
427
438
  //#endregion
428
439
  //#region src/server/backend-vercel.ts
@@ -607,6 +618,8 @@ const API_CURSOR = /^c1\./;
607
618
  /** The API's longest page of a channel's messages, and longest long-poll, in seconds. */
608
619
  const PAGE_MAX = 100;
609
620
  const WAIT_MAX_S = 25;
621
+ /** The most threads a page of the API's thread list holds (`limit`): without it, 25. */
622
+ const THREAD_PAGE_MAX = 100;
610
623
  /** The most recent inbox events the API lists at once. */
611
624
  const INBOX_LIST_MAX = 100;
612
625
  /** The API's codes board()'s sync doesn't know: on sync's routes, each is answered as the board's code for its status. */
@@ -701,6 +714,24 @@ function retryWait(attempt, retryAfter) {
701
714
  const asked = retryAfter !== null && /^\d+$/.test(retryAfter) && Number(retryAfter) > 0 ? Number(retryAfter) * 1e3 : Infinity;
702
715
  return Math.min(asked, RETRY_MS * 2 ** attempt * (1 + Math.random()));
703
716
  }
717
+ /**
718
+ * A 429 the API still answered after `retries` tries again in `ms`: how many requests a minute it
719
+ * takes (`x-ratelimit-limit`), from whom, and when to send again. That's when its window resets
720
+ * (`x-ratelimit-reset`, in Unix seconds), or what `Retry-After` asks where it doesn't say.
721
+ */
722
+ function throttled(response, code, retries, ms) {
723
+ const header = (name) => {
724
+ const value = response.headers.get(name);
725
+ return value !== null && /^\d{1,12}$/.test(value) ? Number(value) : void 0;
726
+ };
727
+ const reset = header("x-ratelimit-reset");
728
+ const untilReset = reset !== void 0 ? reset - Math.floor(Date.now() / 1e3) : void 0;
729
+ const retryAfter = untilReset !== void 0 && untilReset > 0 && untilReset <= 3600 ? untilReset : header("retry-after");
730
+ const limit = header("x-ratelimit-limit");
731
+ const tried = retries > 0 ? `rate-limited ${retries + 1} tries in ${Math.max(1, Math.round(ms / 1e3))}s` : "rate-limited it";
732
+ const takes = limit !== void 0 ? `takes ${limit} requests a minute` : "limits requests";
733
+ return new HttpError(429, code, `Vercel's API ${tried}. It ${takes} per login or token, for all its agents and profiles together.`, { ...retryAfter !== void 0 ? { retryAfter } : {} });
734
+ }
704
735
  /** `ms` passing, or `signal` stopping it first. */
705
736
  const pause = (ms, signal) => ms <= 0 || signal?.aborted ? Promise.resolve() : new Promise((resolve) => {
706
737
  const timer = setTimeout(resolve, ms);
@@ -1027,6 +1058,7 @@ function createVercel(options, environment) {
1027
1058
  ...who.can !== void 0 ? { "x-board-can": who.can } : {}
1028
1059
  };
1029
1060
  const repeatable = method !== "POST" && method !== "PATCH" || typeof init.body?.operationId === "string";
1061
+ const started = Date.now();
1030
1062
  for (let attempt = 0;; attempt++) {
1031
1063
  let response;
1032
1064
  try {
@@ -1053,6 +1085,7 @@ function createVercel(options, environment) {
1053
1085
  continue;
1054
1086
  }
1055
1087
  const error = body?.error;
1088
+ if (response.status === 429) throw throttled(response, error?.code ?? "rate_limited", attempt, Date.now() - started);
1056
1089
  const refused = new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
1057
1090
  if (typeof error?.reason === "string" && /^[a-z_]{1,64}$/.test(error.reason)) reasons.set(refused, error.reason);
1058
1091
  throw refused;
@@ -1171,6 +1204,30 @@ function createVercel(options, environment) {
1171
1204
  if (found) named.set(name, found);
1172
1205
  return found ?? null;
1173
1206
  }
1207
+ const inChannel = (channel) => channel.id !== void 0 ? { channelId: channel.id } : { channel: channel.name };
1208
+ /** Whether the API refused `error`'s request for a query parameter it doesn't know, `name`: an API from before it had one answers 400 and says which. */
1209
+ const unknownParameter = (error, name) => error instanceof HttpError && error.status === 400 && new RegExp(`additional property \\W?${name}\\b`, "i").test(error.message);
1210
+ /** Whether the API reads a channel by its name (`channel=`): until it refuses the parameter, it's asked. */
1211
+ let readsByName = true;
1212
+ /**
1213
+ * A read of the one channel `name` names, with the name itself: the API finds the channel, so the
1214
+ * read costs no lookup before it. An API from before `channel=` takes no parameter it doesn't know
1215
+ * and answers 400: the channel is looked up and read by its ID, as before, and it's never asked
1216
+ * again. Whatever else the API refuses the name with is looked up and read by its ID too, this
1217
+ * once, so it answers as it did before names: a name it finds nothing for or won't show the caller
1218
+ * (404, 403) is null when the lookup finds none either, and any other 400 but a cursor's is the
1219
+ * read's own by its ID.
1220
+ */
1221
+ async function inNamed(who, name, read) {
1222
+ if (readsByName && !named.has(name)) try {
1223
+ return await read({ name });
1224
+ } catch (error) {
1225
+ if (unknownParameter(error, "channel")) readsByName = false;
1226
+ else if (!(error instanceof HttpError && (error.code === "channel_not_found" || error.status === 403 || error.status === 400 && error.code !== "invalid_cursor"))) throw error;
1227
+ }
1228
+ const channel = await channelNamed(who, name);
1229
+ return channel ? read(channel) : null;
1230
+ }
1174
1231
  /** 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. */
1175
1232
  const posted = /* @__PURE__ */ new Map();
1176
1233
  /**
@@ -1179,6 +1236,17 @@ function createVercel(options, environment) {
1179
1236
  * already read answers first, and one the API won't show by ID is looked for in the list, as before.
1180
1237
  */
1181
1238
  const byChannelId = /* @__PURE__ */ new Map();
1239
+ /** A channel an answer named by both its ID and its name: nothing in this process asks for it again. */
1240
+ const learn = ({ id, name }) => {
1241
+ named.set(name, {
1242
+ id,
1243
+ name
1244
+ });
1245
+ byChannelId.set(id, Promise.resolve({
1246
+ id,
1247
+ name
1248
+ }));
1249
+ };
1182
1250
  async function channelById(who, id) {
1183
1251
  const listed = channels ? (await loadChannels(who)).find((channel) => channel.id === id) : void 0;
1184
1252
  if (listed) return listed;
@@ -1239,17 +1307,41 @@ function createVercel(options, environment) {
1239
1307
  const path = filter.slice(0, -1);
1240
1308
  return listed.filter((channel) => channel.name === path || channel.name.startsWith(filter));
1241
1309
  }
1242
- async function messageById(who, id, signal) {
1310
+ async function messageById(who, id, signal, include) {
1243
1311
  if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
1244
1312
  try {
1245
- return await api(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}`), signal ? { signal } : {});
1313
+ return await reading(who, await onBoard(who, `/messages/${encodeURIComponent(id)}`), {
1314
+ ...include ? { query: { include } } : {},
1315
+ ...signal ? { signal } : {}
1316
+ });
1246
1317
  } catch (error) {
1247
1318
  if (error instanceof HttpError && error.code === "thread_not_found") throw notFound(`message not found: ${id}`, "message_not_found");
1248
1319
  throw error;
1249
1320
  }
1250
1321
  }
1251
- /** A message, and its channel. */
1322
+ /** Whether the API answers a message with its channel (`include=channel`): until it refuses the parameter, it's asked. */
1323
+ let messagesWithChannel = true;
1324
+ /**
1325
+ * A message, and its channel, which the API answers with it, so naming it costs no request of its
1326
+ * own. An API from before `include=channel` takes no parameter it doesn't know and answers 400: the
1327
+ * channel is asked for by its ID, as before, and it's never asked with the message again. Any other
1328
+ * 400 or 403 for the two together reads them apart this once.
1329
+ */
1252
1330
  async function messageIn(who, id, signal) {
1331
+ if (messagesWithChannel) try {
1332
+ const { channel, ...found } = await messageById(who, id, signal, "channel");
1333
+ if (channel) learn(channel);
1334
+ return {
1335
+ ...found,
1336
+ channel: channel ? {
1337
+ id: channel.id,
1338
+ name: channel.name
1339
+ } : await channelById(who, found.thread.channelId)
1340
+ };
1341
+ } catch (error) {
1342
+ if (unknownParameter(error, "include")) messagesWithChannel = false;
1343
+ else if (!(error instanceof HttpError && (error.status === 400 || error.status === 403))) throw error;
1344
+ }
1253
1345
  const found = await messageById(who, id, signal);
1254
1346
  return {
1255
1347
  ...found,
@@ -1277,7 +1369,20 @@ function createVercel(options, environment) {
1277
1369
  };
1278
1370
  /** A message's labels: a deleted message keeps none, though the API still holds them. */
1279
1371
  const labelsOf = (message) => message.deletedAt === void 0 ? { ...message.labels } : {};
1280
- const threadMessages = async (who, threadId, signal) => all(who, await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`), "messages", {}, signal);
1372
+ const threadMessages = async (who, threadId, signal) => {
1373
+ const path = await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`);
1374
+ const messages = [];
1375
+ let cursor;
1376
+ do {
1377
+ const page = await reading(who, path, {
1378
+ query: { cursor },
1379
+ ...signal ? { signal } : {}
1380
+ });
1381
+ messages.push(...page.messages);
1382
+ cursor = page.cursor ?? void 0;
1383
+ } while (cursor);
1384
+ return messages;
1385
+ };
1281
1386
  /** Who reacted with each emoji. The API counts them on the message and lists them apart. */
1282
1387
  async function reactors(who, message) {
1283
1388
  if (!message.reactions || Object.keys(message.reactions).length === 0) return {};
@@ -1354,6 +1459,87 @@ function createVercel(options, environment) {
1354
1459
  const naming = (who, actors) => {
1355
1460
  if (namesById) for (const actor of actors) byId(who, actor.id);
1356
1461
  };
1462
+ /** Everyone a read's answer names, the actors the API answers with it when asked. */
1463
+ const namedIn = (read) => [
1464
+ ...(read.threads ?? (read.thread ? [read.thread] : [])).flatMap((thread) => [thread.createdBy, ...[
1465
+ thread.lastMessage,
1466
+ thread.rootMessage,
1467
+ thread.latestMessage
1468
+ ].flatMap((message) => message ? [message.createdBy] : [])]),
1469
+ ...(read.messages ?? (read.message ? [read.message] : [])).map((message) => message.createdBy),
1470
+ ...(read.events ?? []).flatMap((change) => [change.actor, ...change.currentMessage ? [change.currentMessage.createdBy] : []])
1471
+ ];
1472
+ /** Whether the API answers a read's actors with it (`with=actors`): unknown until a read with the parameter is answered, and false once one is refused it. */
1473
+ let actorsWithReads;
1474
+ /** The first read that asks for them, while it's out: reads that start meanwhile wait for its answer, so an API that refuses the parameter refuses it once. */
1475
+ let askingActors = null;
1476
+ /** `waited`, or the signal's reason as soon as it stops: a read that waits on another's answer stops when its own caller does. */
1477
+ async function stoppable(waited, signal) {
1478
+ if (!signal) return waited;
1479
+ signal.throwIfAborted();
1480
+ let stop = () => {};
1481
+ try {
1482
+ await Promise.race([waited, new Promise((_, reject) => {
1483
+ stop = () => reject(signal.reason);
1484
+ signal.addEventListener("abort", stop, { once: true });
1485
+ })]);
1486
+ } finally {
1487
+ signal.removeEventListener("abort", stop);
1488
+ }
1489
+ }
1490
+ /**
1491
+ * A read of threads, messages, or changes, with the actors it names where the API sends them, so naming
1492
+ * them costs no request of its own: they're kept as if each had been asked for by ID, one the API left out
1493
+ * as one it doesn't have. An API from before `with=actors` takes no parameter it doesn't know and answers
1494
+ * 400: the read is made again without it, and it's never asked again. Reads that go out together, one a
1495
+ * channel, wait for the first of them to learn which API this is. A long-poll holds nobody: it may take its
1496
+ * whole wait to answer.
1497
+ */
1498
+ async function reading(who, path, init = {}) {
1499
+ if (!namesById) return api(who, "GET", path, init);
1500
+ while (actorsWithReads === void 0 && askingActors) await stoppable(askingActors, init.signal);
1501
+ if (actorsWithReads === false) return api(who, "GET", path, init);
1502
+ let answered = () => {};
1503
+ if (actorsWithReads === void 0 && init.query?.wait === void 0) {
1504
+ const first = new Promise((resolve) => {
1505
+ answered = () => {
1506
+ if (askingActors === first) askingActors = null;
1507
+ resolve();
1508
+ };
1509
+ });
1510
+ askingActors = first;
1511
+ }
1512
+ let read;
1513
+ try {
1514
+ read = await api(who, "GET", path, {
1515
+ ...init,
1516
+ query: {
1517
+ ...init.query,
1518
+ with: "actors"
1519
+ }
1520
+ });
1521
+ actorsWithReads = true;
1522
+ } catch (error) {
1523
+ if (!(error instanceof HttpError && error.status === 400 && /additional property\W*with\b/i.test(error.message))) throw error;
1524
+ actorsWithReads = false;
1525
+ return api(who, "GET", path, init);
1526
+ } finally {
1527
+ answered();
1528
+ }
1529
+ if (!read.actors) return read;
1530
+ const views = new Map(read.actors.map((view) => [view.id, view]));
1531
+ const { asked } = namesOf(who);
1532
+ const at = Date.now();
1533
+ if (asked.size >= 1e4) asked.clear();
1534
+ for (const { id } of namedIn(read)) {
1535
+ const view = views.get(id);
1536
+ if (view || !asked.has(id) || at - asked.get(id).at > NAMES_FRESH_MS) asked.set(id, {
1537
+ at,
1538
+ view: Promise.resolve(view)
1539
+ });
1540
+ }
1541
+ return read;
1542
+ }
1357
1543
  /**
1358
1544
  * An actor as the API names them, asked for by ID with everyone else named in the same turn: the
1359
1545
  * authors on a page cost one request however many actors the board has. Undefined for one the API
@@ -1627,15 +1813,19 @@ function createVercel(options, environment) {
1627
1813
  }
1628
1814
  /** Each channel's feed now, taken before a read, so what's posted while it reads comes after. */
1629
1815
  async function heads(who, listed) {
1630
- const path = await onBoard(who, "/changes");
1631
- const found = await Promise.all(listed.map((channel) => api(who, "GET", path, { query: {
1632
- channelId: channel.id,
1816
+ const found = await Promise.all(listed.map((channel) => head(who, channel)));
1817
+ return Object.fromEntries(listed.map((channel, i) => [channel.id, found[i]]));
1818
+ }
1819
+ /** One channel's feed now. */
1820
+ async function head(who, channel) {
1821
+ const { cursor } = await api(who, "GET", await onBoard(who, "/changes"), { query: {
1822
+ ...inChannel(channel),
1633
1823
  from: "latest"
1634
- } })));
1635
- return Object.fromEntries(listed.map((channel, i) => [channel.id, {
1636
- at: found[i].cursor,
1824
+ } });
1825
+ return {
1826
+ at: cursor,
1637
1827
  skip: 0
1638
- }]));
1828
+ };
1639
1829
  }
1640
1830
  /**
1641
1831
  * Who `--by` names: `me`, the actor itself; or an actor, a principal and its agents, a profile, or
@@ -1737,7 +1927,8 @@ function createVercel(options, environment) {
1737
1927
  const page = await threadPage(who, path, {
1738
1928
  channelId: channel.id,
1739
1929
  label,
1740
- cursor
1930
+ cursor,
1931
+ limit: THREAD_PAGE_MAX
1741
1932
  }, signal);
1742
1933
  out.push(...page.threads);
1743
1934
  cursor = page.cursor ?? void 0;
@@ -1758,28 +1949,52 @@ function createVercel(options, environment) {
1758
1949
  }
1759
1950
  /** Whether the API lists threads with their first and newest messages (`include=messages`): until it refuses the parameter, it's asked. */
1760
1951
  let threadsWithMessages = true;
1952
+ /** Whether the API takes how many threads a page holds (`limit`): until it refuses the parameter, it's asked. */
1953
+ let threadsByLimit = true;
1954
+ /** Whether a page of threads was answered, so what the thread list takes is known: until one is, reads of it wait for the first. */
1955
+ let threadListKnown = false;
1956
+ /** The first read of the thread list, while it's out: reads that start meanwhile wait for its answer, so an API that refuses a parameter refuses it once. */
1957
+ let askingThreads = null;
1761
1958
  /**
1762
1959
  * A page of a channel's threads, each with its first and newest message where the API sends them, so
1763
- * showing them costs no read of its own. An API from before `include=messages` takes no parameter
1764
- * it doesn't know and answers 400: the page is read again without it, and it's never asked again.
1960
+ * showing them costs no read of its own, and `limit` of them where the API takes it, so a long list
1961
+ * costs a request per 100 threads and not per 25. An API from before either takes no parameter it
1962
+ * doesn't know and answers 400 naming it: the page is read again without that one, and it's never
1963
+ * asked again. Reads that go out together, one a channel, wait for the first to learn which API this is.
1765
1964
  */
1766
1965
  async function threadPage(who, path, query, signal) {
1767
- if (threadsWithMessages) try {
1768
- return await api(who, "GET", path, {
1769
- query: {
1770
- ...query,
1771
- include: "messages"
1772
- },
1773
- signal
1966
+ while (!threadListKnown && askingThreads) await stoppable(askingThreads, signal);
1967
+ let answered = () => {};
1968
+ if (!threadListKnown) {
1969
+ const first = new Promise((resolve) => {
1970
+ answered = () => {
1971
+ if (askingThreads === first) askingThreads = null;
1972
+ resolve();
1973
+ };
1774
1974
  });
1775
- } catch (error) {
1776
- if (!(error instanceof HttpError && error.status === 400 && /additional property/i.test(error.message))) throw error;
1777
- threadsWithMessages = false;
1975
+ askingThreads = first;
1976
+ }
1977
+ const { limit, ...rest } = query;
1978
+ try {
1979
+ for (;;) try {
1980
+ const page = await reading(who, path, {
1981
+ query: {
1982
+ ...rest,
1983
+ ...threadsWithMessages ? { include: "messages" } : {},
1984
+ ...threadsByLimit ? { limit: String(limit) } : {}
1985
+ },
1986
+ signal
1987
+ });
1988
+ threadListKnown = true;
1989
+ return page;
1990
+ } catch (error) {
1991
+ if (threadsWithMessages && unknownParameter(error, "include")) threadsWithMessages = false;
1992
+ else if (threadsByLimit && unknownParameter(error, "limit")) threadsByLimit = false;
1993
+ else throw error;
1994
+ }
1995
+ } finally {
1996
+ answered();
1778
1997
  }
1779
- return api(who, "GET", path, {
1780
- query,
1781
- signal
1782
- });
1783
1998
  }
1784
1999
  /**
1785
2000
  * A channel's threads, as far as a read needs: the API lists them most recently active first, so
@@ -1792,10 +2007,12 @@ function createVercel(options, environment) {
1792
2007
  const out = [];
1793
2008
  let cursor;
1794
2009
  do {
2010
+ const wanted = label === void 0 && page.after === void 0 && page.limit !== void 0 ? page.limit - out.length : THREAD_PAGE_MAX;
1795
2011
  const found = await threadPage(who, path, {
1796
2012
  channelId: channel.id,
1797
2013
  label,
1798
- cursor
2014
+ cursor,
2015
+ limit: Math.min(wanted, THREAD_PAGE_MAX)
1799
2016
  }, signal);
1800
2017
  out.push(...found.threads);
1801
2018
  cursor = found.cursor ?? void 0;
@@ -1820,7 +2037,7 @@ function createVercel(options, environment) {
1820
2037
  } catch {
1821
2038
  throw refused;
1822
2039
  }
1823
- if (typeof scope !== "string" || !scope.split("#").includes(channel.id)) throw refused;
2040
+ if (typeof scope !== "string" || channel.id !== void 0 && !scope.split("#").includes(channel.id)) throw refused;
1824
2041
  }
1825
2042
  return {
1826
2043
  cursor: found[1] || void 0,
@@ -1842,9 +2059,10 @@ function createVercel(options, environment) {
1842
2059
  const out = [];
1843
2060
  do {
1844
2061
  const found = await threadPage(who, path, {
1845
- channelId: channel.id,
2062
+ ...inChannel(channel),
1846
2063
  label: void 0,
1847
- cursor
2064
+ cursor,
2065
+ limit: Math.min(skip + limit - out.length, THREAD_PAGE_MAX)
1848
2066
  }, signal).catch((error) => {
1849
2067
  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
2068
  throw error;
@@ -2008,7 +2226,7 @@ function createVercel(options, environment) {
2008
2226
  const asked = Math.min(limit, PAGE_MAX);
2009
2227
  const pages = await Promise.all(listed.map(async (channel) => ({
2010
2228
  channel,
2011
- ...await api(who, "GET", path, {
2229
+ ...await reading(who, path, {
2012
2230
  query: {
2013
2231
  channelId: channel.id,
2014
2232
  limit: String(asked)
@@ -2128,7 +2346,7 @@ function createVercel(options, environment) {
2128
2346
  const path = await onBoard(who, "/changes");
2129
2347
  const pages = await Promise.all(listed.map(async (channel) => {
2130
2348
  const from = position.feeds[channel.id];
2131
- const page = await api(who, "GET", path, {
2349
+ const page = await reading(who, path, {
2132
2350
  query: {
2133
2351
  channelId: channel.id,
2134
2352
  include: "message",
@@ -2246,9 +2464,9 @@ function createVercel(options, environment) {
2246
2464
  const keep = async (message) => !narrowed || await matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, narrow);
2247
2465
  const kept = [];
2248
2466
  if (query.after === void 0) {
2249
- const page = await api(who, "GET", path, {
2467
+ const page = await reading(who, path, {
2250
2468
  query: {
2251
- channelId: channel.id,
2469
+ ...inChannel(channel),
2252
2470
  limit: String(narrowed ? PAGE_MAX : Math.min(limit, PAGE_MAX))
2253
2471
  },
2254
2472
  signal
@@ -2261,9 +2479,9 @@ function createVercel(options, environment) {
2261
2479
  }
2262
2480
  let cursor = query.after;
2263
2481
  for (let pages = 0; pages < SCAN_PAGES && kept.length < limit; pages++) {
2264
- const page = await api(who, "GET", path, {
2482
+ const page = await reading(who, path, {
2265
2483
  query: {
2266
- channelId: channel.id,
2484
+ ...inChannel(channel),
2267
2485
  after: cursor,
2268
2486
  limit: String(Math.min(limit - kept.length, PAGE_MAX))
2269
2487
  },
@@ -2287,9 +2505,9 @@ function createVercel(options, environment) {
2287
2505
  let cursor = query.after;
2288
2506
  for (;;) {
2289
2507
  const wait = Math.min(WAIT_MAX_S, Math.max(0, Math.ceil((until - Date.now()) / 1e3)));
2290
- const page = await api(who, "GET", path, {
2508
+ const page = await reading(who, path, {
2291
2509
  query: {
2292
- channelId: channel.id,
2510
+ ...inChannel(channel),
2293
2511
  include: "message",
2294
2512
  ...cursor === void 0 ? { from: "latest" } : { cursor },
2295
2513
  ...wait > 0 ? { wait: String(wait) } : {}
@@ -2317,8 +2535,9 @@ function createVercel(options, environment) {
2317
2535
  }
2318
2536
  /** A read of the feed, as `vb tail` makes it: one channel's feed when it names one, or every channel's. */
2319
2537
  async function eventsAs(who, query, signal) {
2320
- const channel = await oneChannel(who, query);
2321
- if (channel) return channelEvents(who, channel, query, signal);
2538
+ const name = oneChannel(query);
2539
+ const found = name === null ? null : await inNamed(who, name, (channel) => channelEvents(who, channel, query, signal));
2540
+ if (found) return found;
2322
2541
  if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
2323
2542
  const listed = query.re === void 0 ? await channelsFor(who, query.channel) : await channelOfThread(who, query.re, query.channel, signal);
2324
2543
  let position = query.after === void 0 ? {
@@ -2353,12 +2572,11 @@ function createVercel(options, environment) {
2353
2572
  if (within !== void 0 && !(await channelsFor(who, within)).some((channel) => channel.id === found.channel.id)) return [];
2354
2573
  return [found.channel];
2355
2574
  }
2356
- /** The one channel a read names, when the API can read it directly: not a subtree, and from one of its cursors or now. */
2357
- async function oneChannel(who, query) {
2575
+ /** The one channel a read names, by its name, when the API can read it directly: not a subtree, and from one of its cursors or now. */
2576
+ function oneChannel(query) {
2358
2577
  if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
2359
2578
  if (query.after !== void 0 && !API_CURSOR.test(query.after)) return null;
2360
- const [channel] = await channelsFor(who, query.channel);
2361
- return channel ?? null;
2579
+ return query.channel;
2362
2580
  }
2363
2581
  /** A watcher's tail registers with the API as its own: an API watcher, so a match is the API's to make. */
2364
2582
  const tagOf = async (watch, sync) => (await sha256(canonicalWatchers(watch, sync))).slice(0, 32);
@@ -2532,12 +2750,12 @@ function createVercel(options, environment) {
2532
2750
  }
2533
2751
  /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
2534
2752
  async function matchOf(who, match, filters) {
2535
- const found = await messageById(who, match.event.messageId).catch((error) => {
2753
+ const found = await messageIn(who, match.event.messageId).catch((error) => {
2536
2754
  if (error instanceof HttpError && error.status === 404) return null;
2537
2755
  throw error;
2538
2756
  });
2539
- const channel = found && await channelById(who, found.thread.channelId);
2540
- if (!found || !channel) return null;
2757
+ if (!found) return null;
2758
+ const { channel } = found;
2541
2759
  const event = match.event.type === "thread.synced" ? await syncedOf(who, match, found.message, channel.name) : await eventOf(who, match.event, channel.name, match.id, filters, await narrowOf(who, filters), found);
2542
2760
  if (!event?.message) return null;
2543
2761
  const handed = match.watcher === "@sync" && event.type === "labels.changed" ? {
@@ -3165,14 +3383,12 @@ function createVercel(options, environment) {
3165
3383
  },
3166
3384
  async messages(caller, query, signal) {
3167
3385
  const who = whoOf(caller);
3168
- const channel = query.before === void 0 ? await oneChannel(who, query) : null;
3169
- if (channel) {
3170
- const page = await channelMessages(who, channel, query, signal);
3171
- return {
3172
- messages: await Promise.all(page.messages.map((message) => view(who, message, channel.name))),
3173
- cursor: page.cursor
3174
- };
3175
- }
3386
+ const name = query.before === void 0 ? oneChannel(query) : null;
3387
+ const direct = name === null ? null : await inNamed(who, name, (channel) => channelMessages(who, channel, query, signal));
3388
+ if (name !== null && direct) return {
3389
+ messages: await Promise.all(direct.messages.map((message) => view(who, message, name))),
3390
+ cursor: direct.cursor
3391
+ };
3176
3392
  if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
3177
3393
  const limit = query.limit ?? 50;
3178
3394
  if (query.re === void 0 && query.after === void 0 && query.before === void 0 && !filtered(query)) {
@@ -3208,21 +3424,41 @@ function createVercel(options, environment) {
3208
3424
  };
3209
3425
  const byMessage = query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0;
3210
3426
  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) => ({
3427
+ const name = query.channel;
3428
+ const read = await inNamed(who, name, async (channel) => {
3429
+ const feed = await head(who, channel);
3430
+ const found = await threadsBefore(who, channel, query.before, limit, signal);
3431
+ return {
3432
+ feed,
3433
+ found,
3434
+ id: channel.id ?? found.threads[0]?.channelId
3435
+ };
3436
+ });
3437
+ if (!read) return {
3438
+ threads: [],
3439
+ cursor: cursorOf({
3440
+ t: 0,
3441
+ feeds: {}
3442
+ }),
3443
+ older: null
3444
+ };
3445
+ if (read.id !== void 0) learn({
3446
+ id: read.id,
3447
+ name
3448
+ });
3449
+ const id = read.id ?? (await channelNamed(who, name))?.id;
3450
+ const page = read.found.threads.map((thread) => ({
3215
3451
  thread,
3216
- channel,
3452
+ channel: { name },
3217
3453
  at: thread.lastActivityAt
3218
- }))).reverse();
3454
+ })).reverse();
3219
3455
  return {
3220
3456
  threads: await summaries(who, page, signal),
3221
3457
  cursor: cursorOf({
3222
3458
  t: page.reduce((max, { at }) => Math.max(max, at), 0),
3223
- feeds
3459
+ feeds: id === void 0 ? {} : { [id]: read.feed }
3224
3460
  }),
3225
- older: found[0]?.older ?? null
3461
+ older: read.found.older
3226
3462
  };
3227
3463
  }
3228
3464
  if (query.before !== void 0) throw new HttpError(400, "invalid_request", "before: this board pages one channel's threads, with no filters");
@@ -3493,6 +3729,17 @@ function createVercel(options, environment) {
3493
3729
  }).catch(grantRefused);
3494
3730
  return { grant: grantFrom(grant) };
3495
3731
  },
3732
+ async createGrants(caller, input, signal) {
3733
+ const who = whoOf(caller);
3734
+ const { grants } = await api(who, "POST", await onBoard(who, "/grants/batch"), {
3735
+ body: {
3736
+ operationId: operationId(),
3737
+ ...input
3738
+ },
3739
+ ...signal ? { signal } : {}
3740
+ }).catch(grantRefused);
3741
+ return { grants: grants.map(grantFrom) };
3742
+ },
3496
3743
  async updateGrant(caller, { id, ...change }, signal) {
3497
3744
  const who = whoOf(caller);
3498
3745
  const { grant } = await api(who, "PATCH", await onBoard(who, `/grants/${encodeURIComponent(id)}`), {
@@ -3515,10 +3762,13 @@ function createVercel(options, environment) {
3515
3762
  grants: explained.grants.map(grantFrom)
3516
3763
  };
3517
3764
  },
3518
- async revokeGrant(caller, { id }, signal) {
3765
+ async revokeGrant(caller, { id, ...options }, signal) {
3519
3766
  const who = whoOf(caller);
3520
3767
  return api(who, "POST", await onBoard(who, `/grants/${encodeURIComponent(id)}/revoke`), {
3521
- body: { operationId: operationId() },
3768
+ body: {
3769
+ operationId: operationId(),
3770
+ ...options
3771
+ },
3522
3772
  ...signal ? { signal } : {}
3523
3773
  });
3524
3774
  },
@@ -3586,15 +3836,24 @@ function createVercel(options, environment) {
3586
3836
  if (!found) return { schedules: [] };
3587
3837
  filter.threadId = found.thread.id;
3588
3838
  }
3589
- if (query.channel !== void 0) {
3590
- const channel = await channelNamed(who, query.channel);
3591
- if (!channel) return { schedules: [] };
3592
- filter.channelId = channel.id;
3593
- }
3594
3839
  if (query.by?.startsWith("vercel:")) filter.createdBy = query.by;
3840
+ if (query.by === "me") filter.createdBy = await actorOf(who);
3595
3841
  const by = await byOf(who, query.by);
3596
3842
  const created = (actor) => by === void 0 || by(actor);
3597
- const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
3843
+ const path = await onBoard(who, "/schedules");
3844
+ const name = query.channel;
3845
+ const listed = name === void 0 ? await all(who, path, "schedules", filter, signal) : await inNamed(who, name, async (channel) => {
3846
+ const found = await all(who, path, "schedules", {
3847
+ ...filter,
3848
+ ...inChannel(channel)
3849
+ }, signal);
3850
+ if (found[0]) learn({
3851
+ id: found[0].channelId,
3852
+ name
3853
+ });
3854
+ return found;
3855
+ });
3856
+ if (!listed) return { schedules: [] };
3598
3857
  return { schedules: await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule))) };
3599
3858
  },
3600
3859
  async cancelSchedule(caller, { id }, signal) {
@@ -4541,7 +4800,6 @@ async function inputOf(name, request, url, params) {
4541
4800
  case "cancelSchedule":
4542
4801
  case "unblockTask":
4543
4802
  case "reopenTask":
4544
- case "revokeGrant":
4545
4803
  case "schema":
4546
4804
  case "attachment":
4547
4805
  case "uploadFinish": return { id };
@@ -4608,10 +4866,15 @@ async function inputOf(name, request, url, params) {
4608
4866
  ...CancelTaskBody.parse(await body())
4609
4867
  };
4610
4868
  case "createGrant": return GrantBody.parse(await body());
4869
+ case "createGrants": return CreateGrantsBody.parse(await body());
4611
4870
  case "updateGrant": return {
4612
4871
  id,
4613
4872
  ...UpdateGrantBody.parse(await body())
4614
4873
  };
4874
+ case "revokeGrant": return {
4875
+ id,
4876
+ ...RevokeGrantBody.parse(await body()) ?? {}
4877
+ };
4615
4878
  case "explain": return ExplainQuery.parse(queryObject(url));
4616
4879
  case "createSchema": return SchemaBody.parse(await body());
4617
4880
  case "register": return RegisterBody.parse(await body());
@@ -4863,8 +5126,9 @@ async function createServe(context) {
4863
5126
  /**
4864
5127
  * Settles the `@handle`s of a caller's texts: a mention is `@[actor-id]`, so a handle that names
4865
5128
  * 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
5129
+ * several stays as typed, a mention of no one. Of several, one on the board wins over platform
5130
+ * users (a synced user's handle is their display name, theirs to set), and else it's the one who
5131
+ * wrote in `thread`, if exactly one did. The actors are read once, for the first text that has a handle. A board behind
4868
5132
  * this one settles them itself, and a schedule's send goes as it was settled when it was made: a
4869
5133
  * handle that mentioned no one then mentions no one later. An ID is longer than a handle, so where
4870
5134
  * settling would take a text past what a message holds, it stays as typed, each handle's actor a
@@ -4872,11 +5136,15 @@ async function createServe(context) {
4872
5136
  */
4873
5137
  function settler(caller, signal) {
4874
5138
  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) => {
5139
+ const external = /* @__PURE__ */ new Set();
5140
+ const actors = () => listed ??= backend.actors(caller, {}, signal).then((answer) => answer.actors.map(({ id, handle, name, kind }) => {
5141
+ if (kind === "external") external.add(id);
5142
+ return {
5143
+ id,
5144
+ handle,
5145
+ name
5146
+ };
5147
+ }), (error) => {
4880
5148
  if (error instanceof HttpError && (error.status === 403 || error.status === 404)) return [];
4881
5149
  throw error;
4882
5150
  });
@@ -4900,7 +5168,10 @@ async function createServe(context) {
4900
5168
  if (!(error instanceof HttpError && error.status === 404)) throw error;
4901
5169
  }
4902
5170
  return fitting(settleMentions(text, await actors(), (candidates) => {
4903
- const wrote = candidates.filter((actor) => writers.has(actor.id));
5171
+ const board = candidates.filter((actor) => !external.has(actor.id));
5172
+ const among = board.length > 0 ? board : candidates;
5173
+ if (among.length === 1) return among[0];
5174
+ const wrote = among.filter((actor) => writers.has(actor.id));
4904
5175
  return wrote.length === 1 ? wrote[0] : null;
4905
5176
  }));
4906
5177
  };