@vercel/board 0.36.0 → 0.38.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 (85) hide show
  1. package/dist/{access-BsP0hvcC.mjs → access-CVkjSfxj.mjs} +12 -12
  2. package/dist/access.d.mts +3 -3
  3. package/dist/access.mjs +6 -5
  4. package/dist/{actors-DFOpTw89.mjs → actors-kfMejhaw.mjs} +6 -4
  5. package/dist/{auth-CrjXLgOb.mjs → auth-B3bBYOqf.mjs} +2 -2
  6. package/dist/{auth-C21V0EK1.d.mts → auth-BXLCkeB0.d.mts} +3 -3
  7. package/dist/{backend-D21q8mdm.d.mts → backend-BkQlF1LQ.d.mts} +3 -9
  8. package/dist/backend-local.d.mts +1 -1
  9. package/dist/backend-local.mjs +1 -1
  10. package/dist/{chat-provider-Bb-jeJLY.mjs → chat-provider-1WKsLEnM.mjs} +2 -2
  11. package/dist/{chat-provider-DmZCmBkb.d.mts → chat-provider-DyNy5xdC.d.mts} +2 -2
  12. package/dist/cli-commands.d.mts +1 -1
  13. package/dist/cli-commands.mjs +1 -1
  14. package/dist/cli-embedded.d.mts +18 -2
  15. package/dist/cli-embedded.mjs +22 -4
  16. package/dist/cli.mjs +50 -676
  17. package/dist/{commands-DGID-4Z2.d.mts → commands-B5d-lmNN.d.mts} +1 -1
  18. package/dist/{commands-BLtqSwha.mjs → commands-BLS7erNu.mjs} +12 -1
  19. package/dist/{conformance-CKrwglzA.mjs → conformance-qJF96jZI.mjs} +164 -23
  20. package/dist/conformance.d.mts +10 -2
  21. package/dist/conformance.mjs +1 -1
  22. package/dist/digest-DAxy9Ula.mjs +4 -0
  23. package/dist/{engine-B_prP0b8.mjs → engine-eUgO5jTM.mjs} +18 -14
  24. package/dist/{events-AEKh9tJm.mjs → events-C6HwB046.mjs} +23 -9
  25. package/dist/exports-BJ3wmEMY.d.mts +4 -0
  26. package/dist/{exports-Ck4Xu3OV.mjs → exports-BsfcChdp.mjs} +805 -193
  27. package/dist/{external-BA2aCC_3.mjs → external-CHDxWIVf.mjs} +1 -1
  28. package/dist/{index-LREsSZb2.d.mts → index-DpVyZa9b.d.mts} +2 -2
  29. package/dist/index.d.mts +5 -5
  30. package/dist/index.mjs +3 -3
  31. package/dist/index.node.d.mts +5 -5
  32. package/dist/index.node.mjs +2 -2
  33. package/dist/inspect/app.js +44 -44
  34. package/dist/inspect/engine.js +5 -5
  35. package/dist/inspect-5mkjJYMS.mjs +2 -0
  36. package/dist/inspect-DtCbBtOW.mjs +643 -0
  37. package/dist/{local-DJ_qI9q7.mjs → local-Bo3XzEKB.mjs} +29 -84
  38. package/dist/{main-Jz4nbNJi.mjs → main-0nvLgajF.mjs} +45 -37
  39. package/dist/{memory-DqwXlyK4.mjs → memory-DkoqhxIH.mjs} +2 -2
  40. package/dist/{middleware-BxgizazV.mjs → middleware-CPqAuRtp.mjs} +10 -2
  41. package/dist/page-R0RoE_gM.mjs +2 -0
  42. package/dist/page-UsfvSIWc.mjs +30 -0
  43. package/dist/{provider-DEOfc4Ls.d.mts → provider-D5yVFisj.d.mts} +5 -3
  44. package/dist/{routes-BpKdMvgX.d.mts → routes-BffuaoTX.d.mts} +11 -18
  45. package/dist/{schemas-BG205xds.mjs → schemas-AZkxk06N.mjs} +3 -3
  46. package/dist/{serve-Puf3I-oI.mjs → serve-D7I3KisQ.mjs} +3 -3
  47. package/dist/{server-CS-1aeTl.mjs → server-Cc3nYq3H.mjs} +23 -13
  48. package/dist/{serving-6_bhBNAW.mjs → serving-DJMcG0dT.mjs} +1 -1
  49. package/dist/{sql-aetuEBZC.mjs → sql-l3ysn4O5.mjs} +2 -2
  50. package/dist/{sqlite-DvsB8ENQ.mjs → sqlite-CAwNHbQD.mjs} +2 -2
  51. package/dist/{sqlite-db-BPwRoDI7.mjs → sqlite-db-cm5yhrD-.mjs} +1 -1
  52. package/dist/sync-chat-sdk.d.mts +2 -2
  53. package/dist/sync-chat-sdk.mjs +2 -2
  54. package/dist/sync-github.d.mts +2 -2
  55. package/dist/sync-github.mjs +2 -2
  56. package/dist/sync-linear.d.mts +3 -3
  57. package/dist/sync-linear.mjs +2 -2
  58. package/dist/sync-slack.d.mts +3 -3
  59. package/dist/sync-slack.mjs +4 -4
  60. package/dist/sync.d.mts +2 -2
  61. package/dist/sync.mjs +2 -2
  62. package/dist/{targets-Dk_xgS9q.mjs → targets-B4Uikw0J.mjs} +66 -21
  63. package/dist/{tokens-Dn4cPZIr.mjs → tokens-DA9ipsZ-.mjs} +1 -1
  64. package/docs/01-board/01-mounting.md +12 -9
  65. package/docs/01-board/03-identity.md +2 -1
  66. package/docs/01-board/06-watchers.md +71 -40
  67. package/docs/01-board/09-access.md +10 -5
  68. package/docs/01-quickstart.md +1 -1
  69. package/docs/02-sync/01-overview.md +7 -7
  70. package/docs/02-sync/02-functions.md +5 -8
  71. package/docs/02-sync/03-slack.md +0 -8
  72. package/docs/02-sync/04-github.md +0 -8
  73. package/docs/02-sync/07-linear.md +0 -6
  74. package/docs/03-guides/01-coding-agents.md +1 -0
  75. package/docs/03-guides/02-inspector.md +3 -2
  76. package/docs/03-guides/03-ci.md +10 -4
  77. package/docs/03-guides/04-triage.md +8 -13
  78. package/docs/04-reference/01-cli.md +51 -13
  79. package/docs/04-reference/02-board.md +2 -1
  80. package/docs/04-reference/03-http.md +4 -4
  81. package/docs/04-reference/05-conformance.md +10 -3
  82. package/docs/index.md +3 -10
  83. package/package.json +2 -1
  84. package/dist/attempts-HXcskN1w.mjs +0 -10
  85. package/dist/exports-BxljH73E.d.mts +0 -4
@@ -1,10 +1,10 @@
1
1
  import { a as forbidden, c as toErrorResponse, d as createBoardClient, f as duration, g as fileName, h as IMPORT_BYTES_MAX, l as unauthorized, n as RejectedError, o as json, p as ATTACHMENT_BYTES_MAX, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as mediaType } from "./errors-rYDxZEuN.mjs";
2
- import { m as RemoteWatcherId } from "./schemas-BG205xds.mjs";
3
- import { A as MessagesQuery, B as SyncCopiesQuery, C as InboxAckBody, D as LabelBody, E as InboxQuery, F as ScheduleBody, G as TokenBody, H as SyncImportBody, I as SchedulesQuery, J as UploadStartBody, K as TypingBody, L as SourceJoinBody, M as ReactBody, N as Ref, O as LinkedQuery, P as RegisterBody, R as SourceReadQuery, S as GrantBody, T as InboxPushBody, U as SyncReceiptBody, V as SyncFindQuery, W as ThreadsQuery, _ as CreateChannelBody, a as compileWatcher, b as EventsQuery, c as METHODS, d as queryObject, f as readCapped, g as AckBody, h as VERSION, i as canonicalWatchers, j as PostBody, k as MatchesQuery, l as createRouter, m as SYNC, n as syncTarget, p as readJson, q as UpdateGrantBody, r as withEmailMentions, t as mentionsEmails, u as openapi, v as DeleteBody, w as InboxNextQuery, x as ExplainQuery, y as EditBody, z as SyncBody } from "./targets-Dk_xgS9q.mjs";
4
- import { i as waitUntil, l as sha256, o as derivedId, r as runMiddleware, t as DroppedError } from "./middleware-BxgizazV.mjs";
5
- import { d as scopeOf, l as parsePattern, r as PERMISSIONS, s as compileAccess, u as parseScope } from "./access-BsP0hvcC.mjs";
6
- import { S as verifiesTokens, T as explainGrants, a as VERCEL_ISSUER, d as fromTokens, f as grantIssuers, p as hostPrincipal, u as createAuthority, x as verifiedIssuers, y as tokenHash } from "./auth-CrjXLgOb.mjs";
7
- import { i as resolveActor, r as claimsOf, t as KNOWN_AGENTS } from "./actors-DFOpTw89.mjs";
2
+ import { h as RemoteWatcherId } from "./schemas-AZkxk06N.mjs";
3
+ import { A as MatchesQuery, B as SyncBody, C as GrantBody, D as InboxQuery, E as InboxPushBody, F as RegisterBody, G as ThreadsQuery, H as SyncFindQuery, I as ScheduleBody, J as UpdateGrantBody, K as TokenBody, L as SchedulesQuery, M as PostBody, N as ReactBody, O as LabelBody, P as Ref, R as SourceJoinBody, S as ExplainQuery, T as InboxNextQuery, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, Y as UploadStartBody, _ as AckBody, a as runMatch, b as EditBody, d as openapi, f as queryObject, g as VERSION, h as SYNC, i as canonicalWatchers, j as MessagesQuery, k as LinkedQuery, l as METHODS, m as readJson, n as syncTarget, o as compileWatcher, p as readCapped, q as TypingBody, r as withEmailMentions, t as mentionsEmails, u as createRouter, v as CreateChannelBody, w as InboxAckBody, x as EventsQuery, y as DeleteBody, z as SourceReadQuery } from "./targets-B4Uikw0J.mjs";
4
+ import { a as waitUntil, r as runMiddleware, s as derivedId, t as DroppedError, u as sha256 } from "./middleware-CPqAuRtp.mjs";
5
+ import { a as canText, c as compileAccess, d as parsePattern, r as PERMISSIONS, u as parseCan } from "./access-CVkjSfxj.mjs";
6
+ import { S as verifiesTokens, T as explainGrants, a as VERCEL_ISSUER, d as fromTokens, f as grantIssuers, p as hostPrincipal, u as createAuthority, x as verifiedIssuers, y as tokenHash } from "./auth-B3bBYOqf.mjs";
7
+ import { i as resolveActor, r as claimsOf, t as KNOWN_AGENTS } from "./actors-kfMejhaw.mjs";
8
8
  //#region src/server/registrant.ts
9
9
  /** Registering again this soon after the same registration only repeats it. */
10
10
  const REGISTER_EVERY_MS = 1e4;
@@ -14,19 +14,25 @@ const DRAIN_MS = 24e4;
14
14
  const WAKE_ANSWER_MS = 2e3;
15
15
  /** A pull with nothing to hand out holds this long, when the board pulls on its own. */
16
16
  const POLL_WAIT_S = 25;
17
- const describe = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
17
+ const describe$1 = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
18
18
  /** Only an https URL can be woken; anything else pulls on its own. */
19
19
  const wakeable = (here) => here?.startsWith("https://") ? here : null;
20
+ /** Whether a registration is woken at all: one with neither a URL nor a path pulls on its own, off Vercel. */
21
+ const pulls = (registration) => registration.url === null && registration.path === void 0;
22
+ /**
23
+ * Whether this is a deployment on Vercel, whose function doesn't outlive its request: `VERCEL` is 1,
24
+ * outside development. `vercel env pull` and `vercel dev` set both for a dev server, which stays up.
25
+ */
26
+ const deployedOnVercel = () => typeof process !== "undefined" && process.env.VERCEL === "1" && process.env.VERCEL_ENV !== "development";
20
27
  /**
21
- * A path on this Vercel project for a board that wakes by path, from `here`, this board's URL:
22
- * from production, or from a preview of a branch, which it names. Null anywhere else (off Vercel,
23
- * development, a custom environment), where only a URL wakes it.
28
+ * A path on this Vercel project for a board that wakes by path, from `here`, this board's URL: from
29
+ * every deployment on Vercel, whose environment the board that wakes it finds from its token. A
30
+ * preview of a branch names it. Null anywhere else, a dev server included, where only a URL wakes it.
24
31
  */
25
32
  function wakePath(here) {
26
- const env = typeof process !== "undefined" && process.env.VERCEL === "1" ? process.env : null;
27
- const environment = env?.VERCEL_TARGET_ENV || env?.VERCEL_ENV;
28
- const branch = environment === "preview" ? env?.VERCEL_GIT_COMMIT_REF || null : null;
29
- if (!here || environment !== "production" && !branch) return null;
33
+ if (!here || !deployedOnVercel()) return null;
34
+ const env = process.env;
35
+ const branch = (env.VERCEL_TARGET_ENV || env.VERCEL_ENV) === "preview" ? env.VERCEL_GIT_COMMIT_REF || null : null;
30
36
  return {
31
37
  path: new URL(here).pathname,
32
38
  ...branch ? { branch } : {}
@@ -35,8 +41,9 @@ function wakePath(here) {
35
41
  /**
36
42
  * Runs a board's watchers on another board that matches them: it registers them there, is woken
37
43
  * when one matches, with nothing in the wake-up but a hash, and pulls what matched with its own
38
- * credentials, runs it, and acks it. When it can't be woken (no https URL of its own: a dev
39
- * server, say), it pulls on its own. http() and vercel() run their watchers this way.
44
+ * credentials, runs it, and acks it. When it can't be woken (no https URL of its own, a dev
45
+ * server say, or no path on a board that wakes only paths), it pulls on its own. http() and a
46
+ * deployment's vercel() run their watchers this way.
40
47
  */
41
48
  function registrant(options) {
42
49
  const { registry, rethrow } = options;
@@ -70,12 +77,12 @@ function registrant(options) {
70
77
  });
71
78
  } catch (error) {
72
79
  console.error(`[board] watcher ${match.watcher} failed:`, error);
73
- outcome = { error: describe(error) };
80
+ outcome = { error: describe$1(error) };
74
81
  }
75
82
  await registry.ack(match.id, {
76
83
  lease: match.lease,
77
84
  ...outcome
78
- }).catch((error) => console.error(`[board] couldn't ack a match:`, describe(error)));
85
+ }).catch((error) => console.error(`[board] couldn't ack a match:`, describe$1(error)));
79
86
  }
80
87
  /**
81
88
  * Pulls and runs what's matched until nothing's left, or this run's time is up, and what sync
@@ -95,7 +102,7 @@ function registrant(options) {
95
102
  let polling = null;
96
103
  /** For a board that can't be woken: pulls on its own, each pull held open until something matches. */
97
104
  function poll() {
98
- if (polling) return;
105
+ if (polling || deployedOnVercel()) return;
99
106
  const controller = polling = new AbortController();
100
107
  (async () => {
101
108
  for (let pause = 1e3; !controller.signal.aborted;) try {
@@ -110,7 +117,7 @@ function registrant(options) {
110
117
  pause = 1e3;
111
118
  } catch (error) {
112
119
  if (controller.signal.aborted) break;
113
- console.error(`[board] couldn't pull matches from ${options.remote}:`, describe(error));
120
+ console.error(`[board] couldn't pull matches from ${options.remote}:`, describe$1(error));
114
121
  await new Promise((resolve) => setTimeout(resolve, pause));
115
122
  pause = Math.min(pause * 2, 6e4);
116
123
  }
@@ -129,11 +136,13 @@ function registrant(options) {
129
136
  if (started) return started;
130
137
  if (!options.hasWork() || Date.now() - failedAt < REGISTER_EVERY_MS) return Promise.resolve();
131
138
  const here = wakeable(bound().url());
132
- if (!here && typeof process !== "undefined" && process.env.VERCEL === "1") return Promise.resolve();
133
- started = register(here).then(() => {}, (error) => {
139
+ if (!here && deployedOnVercel()) return Promise.resolve();
140
+ started = register(here).then((registration) => {
141
+ if (pulls(registration)) poll();
142
+ }, (error) => {
134
143
  started = null;
135
144
  failedAt = Date.now();
136
- console.error(`[board] couldn't register with ${options.remote}:`, describe(error));
145
+ console.error(`[board] couldn't register with ${options.remote}:`, describe$1(error));
137
146
  });
138
147
  if (!here) poll();
139
148
  return started;
@@ -150,7 +159,7 @@ function registrant(options) {
150
159
  if (stale) await register(wakeable(bound().url()));
151
160
  return drain();
152
161
  })();
153
- waitUntil(running.catch((error) => console.error(`[board] couldn't run what woke it:`, describe(error))));
162
+ waitUntil(running.catch((error) => console.error(`[board] couldn't run what woke it:`, describe$1(error))));
154
163
  let timer;
155
164
  const waited = new Promise((resolve) => timer = setTimeout(() => resolve(null), WAKE_ANSWER_MS));
156
165
  try {
@@ -168,7 +177,7 @@ function registrant(options) {
168
177
  started ??= Promise.resolve();
169
178
  const here = wakeable(bound().url());
170
179
  const registration = await register(here).catch(rethrow);
171
- if (!here) poll();
180
+ if (!here || pulls(registration)) poll();
172
181
  return json(registration);
173
182
  }
174
183
  }],
@@ -182,6 +191,115 @@ function registrant(options) {
182
191
  };
183
192
  }
184
193
  //#endregion
194
+ //#region src/server/tails.ts
195
+ /** A pull with nothing to hand out holds this long: the same long-poll `vb tail` holds. */
196
+ const WAIT_S = 25;
197
+ /** A run that throws waits this long, doubling to `RETRY_MAX_MS`, as on a local board. */
198
+ const RETRY_MS = 1e3;
199
+ const RETRY_MAX_MS = 3e4;
200
+ /** A feed that fails is read again after this long, doubling to a minute. */
201
+ const READ_AGAIN_MS = 1e3;
202
+ const READ_AGAIN_MAX_MS = 6e4;
203
+ const describe = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
204
+ /**
205
+ * Watchers run as tails in this process, for a board nothing can wake: each follows the feed from
206
+ * the head, as `vb tail` does, and runs what it prints. A watcher sees a thread's events in order,
207
+ * threads run side by side, and a `run` that throws waits 1 second, doubling to 30, until
208
+ * `runMatch` gives up on it.
209
+ */
210
+ function tailWatchers(options) {
211
+ let controller = null;
212
+ const boot = crypto.randomUUID();
213
+ let matched = 0;
214
+ async function follow(id, filters, all, signal) {
215
+ let own;
216
+ /** Each thread's runs, one after another. */
217
+ const lanes = /* @__PURE__ */ new Map();
218
+ const query = {
219
+ ...filters,
220
+ ...all ? { all: true } : {}
221
+ };
222
+ let after;
223
+ for (let pause = READ_AGAIN_MS; !signal.aborted;) {
224
+ let page;
225
+ try {
226
+ own ??= await options.actorOf(id);
227
+ page = await options.events(after === void 0 ? {
228
+ ...query,
229
+ wait: 0
230
+ } : {
231
+ ...query,
232
+ after,
233
+ wait: WAIT_S
234
+ }, signal);
235
+ pause = READ_AGAIN_MS;
236
+ } catch (error) {
237
+ if (signal.aborted) return;
238
+ console.error(`[board] watcher ${id} couldn't read the board:`, describe(error));
239
+ await sleep(pause, signal);
240
+ pause = Math.min(pause * 2, READ_AGAIN_MAX_MS);
241
+ continue;
242
+ }
243
+ after = page.cursor;
244
+ for (const event of page.events) {
245
+ if (event.actor?.id === own) continue;
246
+ const thread = event.message?.thread ?? "";
247
+ const match = {
248
+ id: `${boot}:${matched++}`,
249
+ payload: {
250
+ thread,
251
+ event
252
+ }
253
+ };
254
+ const lane = (lanes.get(thread) ?? Promise.resolve()).then(() => attempts(id, match, signal));
255
+ lanes.set(thread, lane);
256
+ lane.then(() => {
257
+ if (lanes.get(thread) === lane) lanes.delete(thread);
258
+ });
259
+ }
260
+ }
261
+ }
262
+ async function attempts(id, match, signal) {
263
+ const trigger = `watch:${id}:${match.id}`;
264
+ for (let attempt = 1, wait = RETRY_MS; !signal.aborted; attempt++, wait = Math.min(wait * 2, RETRY_MAX_MS)) try {
265
+ await runMatch({
266
+ watcher: {
267
+ id,
268
+ run: (event) => options.run(id, event, {
269
+ trigger,
270
+ attempt
271
+ })
272
+ },
273
+ match,
274
+ attempt,
275
+ record: async () => {}
276
+ });
277
+ return;
278
+ } catch (error) {
279
+ console.error(`[board] watcher ${id} failed:`, error);
280
+ await sleep(wait, signal);
281
+ }
282
+ }
283
+ return {
284
+ /** Starts every watcher's tail, once. */
285
+ start() {
286
+ if (controller) return;
287
+ const { signal } = controller = new AbortController();
288
+ for (const [id, { filters, all }] of Object.entries(options.watchers)) follow(id, filters, all, signal);
289
+ },
290
+ /** Stops every tail, and the retries waiting. */
291
+ close() {
292
+ controller?.abort();
293
+ controller = null;
294
+ }
295
+ };
296
+ }
297
+ const sleep = (ms, signal) => new Promise((resolve) => {
298
+ if (signal.aborted) return resolve();
299
+ const timer = setTimeout(resolve, ms);
300
+ signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
301
+ });
302
+ //#endregion
185
303
  //#region src/server/backend-vercel.ts
186
304
  const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
187
305
  const SESSION = /^[A-Za-z0-9_.:-]{1,128}$/;
@@ -196,8 +314,37 @@ const API_CURSOR = /^c1\./;
196
314
  /** The API's longest page of a channel's messages, and longest long-poll, in seconds. */
197
315
  const PAGE_MAX = 100;
198
316
  const WAIT_MAX_S = 25;
317
+ /** The most recent inbox events the API lists at once. */
318
+ const INBOX_LIST_MAX = 100;
319
+ /** 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. */
320
+ const API_ONLY_CODES = /* @__PURE__ */ new Set([
321
+ "board_only",
322
+ "duplicate_sync_key",
323
+ "event_too_large",
324
+ "foreign_author",
325
+ "invalid_find",
326
+ "invalid_import",
327
+ "invalid_inbox_event",
328
+ "invalid_receipt",
329
+ "message_not_owned",
330
+ "mutation_too_large",
331
+ "operation_conflict",
332
+ "operation_expired_or_unknown",
333
+ "sync_key_not_owned",
334
+ "sync_needs_project",
335
+ "too_many_targets"
336
+ ]);
337
+ const BOARD_CODES = {
338
+ 400: "invalid_request",
339
+ 403: "forbidden",
340
+ 404: "not_found",
341
+ 409: "conflict",
342
+ 413: "too_large"
343
+ };
199
344
  /** Pages a filtered read of one channel scans for matches before it answers with what it found. */
200
345
  const SCAN_PAGES = 10;
346
+ /** How long after it couldn't tell who its credentials are a board waits to ask again. */
347
+ const WHO_AGAIN_MS = 1e4;
201
348
  /** A file as the board names it. */
202
349
  const fileOf = ({ id, name, type, size }) => ({
203
350
  id,
@@ -280,6 +427,7 @@ function locate(id) {
280
427
  }
281
428
  /** A principal as board names it: `vercel:user:<id>`, `vercel:app:<id>`, `vercel:project:<id>:<env>`. */
282
429
  function principalId(principal) {
430
+ if (principal.type === "external") return principal.id;
283
431
  if (principal.type === "user") return `vercel:user:${principal.userId}`;
284
432
  if (principal.type === "app") return `vercel:app:${principal.clientId}`;
285
433
  return `vercel:project:${principal.projectId}:${principal.environment}`;
@@ -300,6 +448,13 @@ const SCHEDULER = {
300
448
  /** The API names nobody, so an actor's handle is its profile, or a short form of its principal. */
301
449
  function actorView(actor) {
302
450
  const { principal } = actor;
451
+ if (principal.type === "external") return {
452
+ id: actor.id,
453
+ kind: "external",
454
+ handle: principal.id.slice(principal.id.lastIndexOf(":") + 1),
455
+ name: principal.id,
456
+ avatar: null
457
+ };
303
458
  const base = principal.type === "user" ? `user-${principal.userId.slice(0, 6).toLowerCase()}` : principal.type === "app" ? `app-${principal.clientId.slice(0, 6).toLowerCase()}` : principal.environment === "production" ? principal.projectId : `${principal.projectId}@${principal.environment}`;
304
459
  const handle = actor.profile?.name ?? base;
305
460
  const kind = actor.profile ? "agent" : principal.type === "user" ? "person" : principal.type === "project" ? "deployment" : "workflow";
@@ -311,10 +466,26 @@ function actorView(actor) {
311
466
  avatar: actor.profile?.avatar ?? null
312
467
  };
313
468
  }
469
+ /** A message's labels just before a change, from what they are after it and what it changed. */
470
+ function labelsBefore(after, changed = {}) {
471
+ const before = { ...after };
472
+ for (const [key, { from }] of Object.entries(changed)) if (from === void 0) delete before[key];
473
+ else before[key] = from;
474
+ return before;
475
+ }
476
+ /** A platform location as board shows one, its optional parts null. */
477
+ const originOf = (origin) => origin ? {
478
+ ...origin.channel !== void 0 ? { channel: origin.channel } : {},
479
+ thread: origin.thread,
480
+ subthread: origin.subthread ?? null,
481
+ message: origin.message,
482
+ context: origin.context ?? null
483
+ } : null;
314
484
  /**
315
485
  * Vercel's board for your team, in Vercel's API: this deployment keeps nothing and reads and writes
316
486
  * it as itself, its people as themselves. Messages, threads, reactions, labels, a channel's
317
- * changes, schedules, files, and watchers work; what the API keeps none of yet (sync) answers 501.
487
+ * changes, schedules, files, watchers, and sync's records work: the API keeps sync's state, and
488
+ * the platforms stay with board()'s sync.
318
489
  */
319
490
  function createVercel(options, environment) {
320
491
  const origin = (options.api ?? "https://api.vercel.com").replace(/\/+$/, "");
@@ -337,7 +508,11 @@ function createVercel(options, environment) {
337
508
  const url = new URL(`${origin}/v1/messageboard${path}`);
338
509
  const id = await teamId();
339
510
  if (id) url.searchParams.set(id.startsWith("team_") ? "teamId" : "slug", id);
340
- for (const [name, value] of Object.entries(init.query ?? {})) if (value !== void 0) url.searchParams.set(name, value);
511
+ for (const [name, value] of Object.entries(init.query ?? {})) {
512
+ if (value === void 0) continue;
513
+ if (typeof value === "string") url.searchParams.set(name, value);
514
+ else for (const one of value) url.searchParams.append(name, one);
515
+ }
341
516
  const headers = { "content-type": "application/json" };
342
517
  if (who.profile) headers["x-board-profile"] = who.profile.name;
343
518
  if (who.profile?.avatar?.startsWith("https://")) headers["x-board-avatar"] = who.profile.avatar;
@@ -368,6 +543,19 @@ function createVercel(options, environment) {
368
543
  });
369
544
  throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
370
545
  }
546
+ /** A request on sync's routes, whose refusals board()'s sync knows only by the board's codes. */
547
+ async function syncApi(...args) {
548
+ try {
549
+ return await api(...args).catch(async (error) => {
550
+ if (!(error instanceof HttpError && error.code === "sync_key_not_owned" && (binding?.sync.length ?? 0) > 0)) throw error;
551
+ await runner.registerNow();
552
+ return api(...args);
553
+ });
554
+ } catch (error) {
555
+ if (error instanceof HttpError && API_ONLY_CODES.has(error.code)) throw new HttpError(error.status, BOARD_CODES[error.status] ?? error.code, error.message);
556
+ throw error;
557
+ }
558
+ }
371
559
  /** Every page of a list, in order. */
372
560
  async function all(who, path, key, query = {}, signal) {
373
561
  const out = [];
@@ -468,6 +656,8 @@ function createVercel(options, environment) {
468
656
  if (found) named.set(name, found);
469
657
  return found ?? null;
470
658
  }
659
+ /** 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. */
660
+ const posted = /* @__PURE__ */ new Map();
471
661
  async function channelById(who, id) {
472
662
  const found = (await loadChannels(who)).find((channel) => channel.id === id) ?? (await loadChannels(who, true)).find((channel) => channel.id === id);
473
663
  if (!found) throw new HttpError(502, "remote_error", `Vercel's API names a channel it doesn't list: ${id}`);
@@ -600,7 +790,7 @@ function createVercel(options, environment) {
600
790
  if (!found && await again.views.then(() => true, () => false)) unlisted.add(actor.id);
601
791
  }
602
792
  const kind = found && apiKind(found.kind);
603
- if (!found || !(kind === "person" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
793
+ if (!found || !(kind === "person" || kind === "external" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
604
794
  return {
605
795
  id: actor.id,
606
796
  kind,
@@ -622,15 +812,20 @@ function createVercel(options, environment) {
622
812
  reactions: message.deletedAt === void 0 ? await reactors(who, message) : {},
623
813
  mentions: [],
624
814
  by: authorOf(message.createdBy),
625
- noSync: false,
626
- origin: null,
627
- from: null,
815
+ noSync: message.noSync ?? false,
816
+ origin: originOf(message.origin),
817
+ from: message.from ?? null,
628
818
  createdAt: iso(message.createdAt),
629
819
  editedAt: message.editedAt === void 0 ? null : iso(message.editedAt),
630
820
  deleted: message.deletedAt !== void 0,
631
821
  undelivered: {},
632
822
  attachments: message.attachments ?? [],
633
- links: [],
823
+ links: (message.links ?? []).map((link) => ({
824
+ url: link.url,
825
+ message: link.message ?? null,
826
+ snapshot: link.snapshot ?? null,
827
+ unavailable: link.unavailable ?? null
828
+ })),
634
829
  version: message.version,
635
830
  revision: message.revision,
636
831
  author: await nameOf(who, message.createdBy),
@@ -640,6 +835,31 @@ function createVercel(options, environment) {
640
835
  } } : {}
641
836
  };
642
837
  }
838
+ /**
839
+ * The message a post made, from what it sent, when the API answers with its IDs only: the caller
840
+ * may post there but not read it back. It's by the caller, as its credentials and profile name it.
841
+ */
842
+ async function sent(who, ids, input) {
843
+ const { actor } = await self(who);
844
+ const by = {
845
+ id: await actorOf(who),
846
+ principal: actor.principal,
847
+ ...who.profile ? { profile: who.profile } : {},
848
+ ...who.session ? { session: who.session } : {}
849
+ };
850
+ const attachments = (await Promise.all((input.attachments ?? []).map(async (id) => api(who, "GET", await onBoard(who, `/attachments/${encodeURIComponent(id)}`)).then(({ attachment }) => fileOf(attachment), () => null)))).filter((file) => file !== null);
851
+ return {
852
+ ...ids,
853
+ text: input.text,
854
+ version: 1,
855
+ revision: 1,
856
+ createdAt: Date.now(),
857
+ createdBy: by,
858
+ ...input.labels && Object.keys(input.labels).length ? { labels: { ...input.labels } } : {},
859
+ ...input.noSync ? { noSync: true } : {},
860
+ ...attachments.length ? { attachments } : {}
861
+ };
862
+ }
643
863
  async function scheduleView(who, schedule) {
644
864
  const { canceled } = schedule;
645
865
  return {
@@ -648,7 +868,7 @@ function createVercel(options, environment) {
648
868
  re: schedule.threadId === void 0 ? null : idAt(schedule.threadId, 1),
649
869
  text: schedule.text,
650
870
  labels: { ...schedule.labels },
651
- noSync: false,
871
+ noSync: schedule.noSync ?? false,
652
872
  attachments: [],
653
873
  first: iso(schedule.firstAt),
654
874
  every: schedule.every ?? null,
@@ -700,23 +920,43 @@ function createVercel(options, environment) {
700
920
  skip: 0
701
921
  }]));
702
922
  }
923
+ /** Handles a fresh read of the names didn't have, by when: `--by` doesn't read again for them for a while. */
924
+ const unhandled = /* @__PURE__ */ new Map();
925
+ /**
926
+ * Who `--by` names: `me`, the actor itself; or an actor, a principal and its agents, a profile, or
927
+ * a handle as the board shows it (`julian`, `julian/claude`), a person's covering their agents.
928
+ */
929
+ async function byOf(who, by) {
930
+ if (by === void 0) return void 0;
931
+ if (by === "me") {
932
+ const me = await actorOf(who);
933
+ return (actor) => actor.id === me;
934
+ }
935
+ const named = /* @__PURE__ */ new Set([by]);
936
+ if (!by.startsWith("vercel:")) {
937
+ const handle = by.toLowerCase();
938
+ const find = async (read) => [...await read.views].filter(([, view]) => view.handle.toLowerCase() === handle).map(([id]) => id);
939
+ const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
940
+ let ids = await find(kept ?? readNames(who));
941
+ const missed = unhandled.get(handle);
942
+ if (ids.length === 0 && kept && !(missed !== void 0 && Date.now() - missed <= NAMES_FRESH_MS)) ids = await find(readNames(who));
943
+ if (ids.length === 0) {
944
+ if (unhandled.size >= 1e3) unhandled.clear();
945
+ if (!kept || missed === void 0 || Date.now() - missed > NAMES_FRESH_MS) unhandled.set(handle, Date.now());
946
+ }
947
+ for (const id of ids) named.add(id);
948
+ }
949
+ return (actor) => named.has(actor.id) || named.has(principalId(actor.principal)) || actor.profile !== void 0 && named.has(actor.profile.name);
950
+ }
703
951
  /**
704
952
  * Whether a message matches a read's filters. A label matches on the message or its thread's root:
705
953
  * `thread`'s labels, as `labeledBy` gives them when the read filters on labels.
706
954
  */
707
- function matches(filters, message, thread, me) {
955
+ function matches(filters, message, thread, by) {
708
956
  if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
709
- if (filters.by !== void 0) {
710
- const { createdBy } = message;
711
- const names = [
712
- createdBy.id,
713
- principalId(createdBy.principal),
714
- createdBy.profile?.name
715
- ];
716
- if (!(filters.by === "me" ? createdBy.id === me : names.includes(filters.by))) return false;
717
- }
957
+ if (by && !by(message.createdBy)) return false;
718
958
  if (filters.mentions !== void 0) return false;
719
- if (filters.from !== void 0 && filters.from !== "board") return false;
959
+ if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
720
960
  if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
721
961
  for (const [key, values] of filters.label ?? []) {
722
962
  const on = (labels) => labels !== void 0 && Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
@@ -846,7 +1086,7 @@ function createVercel(options, environment) {
846
1086
  }))))).flat();
847
1087
  }
848
1088
  const feeds = await heads(who, listed);
849
- const mine = await actorOf(who);
1089
+ const by = await byOf(who, filters.by);
850
1090
  let newest = 0;
851
1091
  const messages = [];
852
1092
  for (const { thread, channel } of threads) {
@@ -854,7 +1094,7 @@ function createVercel(options, environment) {
854
1094
  const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
855
1095
  for (const message of all) {
856
1096
  newest = Math.max(newest, message.createdAt);
857
- if (matches(filters, message, labeled, mine)) messages.push({
1097
+ if (matches(filters, message, labeled, by)) messages.push({
858
1098
  message,
859
1099
  thread,
860
1100
  channel
@@ -905,7 +1145,7 @@ function createVercel(options, environment) {
905
1145
  };
906
1146
  }
907
1147
  /** 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. */
908
- async function eventOf(who, change, channel, cursor, filters, me, given, threads = threadReader(who)) {
1148
+ async function eventOf(who, change, channel, cursor, filters, authors, given, threads = threadReader(who)) {
909
1149
  if (!change.messageId || !change.type.startsWith("message.")) return null;
910
1150
  let found = given ?? await messageById(who, change.messageId).catch((error) => {
911
1151
  if (error instanceof HttpError && error.status === 404) return null;
@@ -915,9 +1155,10 @@ function createVercel(options, environment) {
915
1155
  ...found,
916
1156
  thread: found.message.sequence === 1 ? labeledBy(found.thread, found.message) : await threads(found.thread.id)
917
1157
  };
918
- if (!found || !matches(filters, found.message, found.thread, me)) return null;
1158
+ if (!found || !matches(filters, found.message, found.thread, authors)) return null;
919
1159
  const message = await view(who, found.message, channel);
920
1160
  const by = authorOf(change.actor);
1161
+ const from = change.from ?? null;
921
1162
  const base = {
922
1163
  id: message.id,
923
1164
  thread: message.thread
@@ -934,13 +1175,13 @@ function createVercel(options, environment) {
934
1175
  replyTo: message.replyTo,
935
1176
  thread: message.thread,
936
1177
  labels: message.labels,
937
- noSync: false,
1178
+ noSync: message.noSync,
938
1179
  mentions: [],
939
1180
  by,
940
- origin: null,
941
- from: null,
1181
+ origin: message.origin,
1182
+ from: message.from,
942
1183
  attachments: message.attachments,
943
- links: []
1184
+ links: message.links
944
1185
  };
945
1186
  break;
946
1187
  case "message.edited":
@@ -950,7 +1191,7 @@ function createVercel(options, environment) {
950
1191
  text: message.text,
951
1192
  mentions: [],
952
1193
  by,
953
- from: null
1194
+ from
954
1195
  };
955
1196
  break;
956
1197
  case "message.deleted":
@@ -958,7 +1199,7 @@ function createVercel(options, environment) {
958
1199
  payload = {
959
1200
  ...base,
960
1201
  by,
961
- from: null
1202
+ from
962
1203
  };
963
1204
  break;
964
1205
  case "message.reaction_added":
@@ -968,7 +1209,7 @@ function createVercel(options, environment) {
968
1209
  ...base,
969
1210
  emoji: change.emoji,
970
1211
  by,
971
- from: null
1212
+ from
972
1213
  };
973
1214
  break;
974
1215
  case "message.labeled": {
@@ -984,15 +1225,16 @@ function createVercel(options, environment) {
984
1225
  }
985
1226
  default: return null;
986
1227
  }
987
- return {
988
- cursor,
989
- type,
990
- createdAt: iso(change.createdAt),
991
- payload,
992
- message,
993
- actor: await nameOf(who, change.actor)
994
- };
995
- }
1228
+ return boardEvent(who, change, cursor, type, payload, message);
1229
+ }
1230
+ const boardEvent = async (who, change, cursor, type, payload, message) => ({
1231
+ cursor,
1232
+ type,
1233
+ createdAt: iso(change.createdAt),
1234
+ payload,
1235
+ message,
1236
+ actor: await nameOf(who, change.actor)
1237
+ });
996
1238
  /**
997
1239
  * One read of every channel's feed from `position`: its events, merged by time, each with the
998
1240
  * position right after it, and the position after them all.
@@ -1020,7 +1262,7 @@ function createVercel(options, environment) {
1020
1262
  events
1021
1263
  };
1022
1264
  }));
1023
- const mine = await actorOf(who);
1265
+ const by = await byOf(who, filters.by);
1024
1266
  const threads = threadReader(who, signal);
1025
1267
  const running = { ...position.feeds };
1026
1268
  const merged = pages.flatMap((page) => page.events.map((event) => ({
@@ -1036,7 +1278,7 @@ function createVercel(options, environment) {
1036
1278
  const event = await eventOf(who, change, page.channel.name, cursorOf({
1037
1279
  t: change.createdAt,
1038
1280
  feeds: { ...running }
1039
- }), filters, mine, void 0, threads);
1281
+ }), filters, by, void 0, threads);
1040
1282
  if (event) events.push(event);
1041
1283
  }
1042
1284
  const after = { ...position.feeds };
@@ -1107,8 +1349,8 @@ function createVercel(options, environment) {
1107
1349
  const limit = query.limit ?? 50;
1108
1350
  const thread = threadReader(who, signal);
1109
1351
  const narrowed = filtered(query);
1110
- const me = narrowed ? await actorOf(who) : null;
1111
- const keep = async (message) => !narrowed || matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, me);
1352
+ const by = narrowed ? await byOf(who, query.by) : void 0;
1353
+ const keep = async (message) => !narrowed || matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, by);
1112
1354
  const kept = [];
1113
1355
  if (query.after === void 0) {
1114
1356
  const page = await api(who, "GET", path, {
@@ -1147,7 +1389,7 @@ function createVercel(options, environment) {
1147
1389
  async function channelEvents(who, channel, query, signal) {
1148
1390
  const path = await onBoard(who, "/changes");
1149
1391
  const thread = threadReader(who, signal);
1150
- const me = await actorOf(who);
1392
+ const by = await byOf(who, query.by);
1151
1393
  const until = Date.now() + (query.wait ?? 0) * 1e3;
1152
1394
  let cursor = query.after;
1153
1395
  for (;;) {
@@ -1170,7 +1412,7 @@ function createVercel(options, environment) {
1170
1412
  thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
1171
1413
  } : null;
1172
1414
  if (!found) continue;
1173
- const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, me, found);
1415
+ const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, by, found);
1174
1416
  if (event) events.push(event);
1175
1417
  }
1176
1418
  if (events.length > 0 || Date.now() >= until || signal.aborted) return {
@@ -1179,6 +1421,33 @@ function createVercel(options, environment) {
1179
1421
  };
1180
1422
  }
1181
1423
  }
1424
+ /** A read of the feed, as `vb tail` makes it: one channel's feed when it names one, or every channel's. */
1425
+ async function eventsAs(who, query, signal) {
1426
+ const channel = await oneChannel(who, query);
1427
+ if (channel) return channelEvents(who, channel, query, signal);
1428
+ 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`);
1429
+ const listed = await channelsFor(who, query.channel);
1430
+ let position = query.after === void 0 ? {
1431
+ t: Date.now(),
1432
+ feeds: await heads(who, listed)
1433
+ } : locate(query.after) ? {
1434
+ t: await timeOf(who, query.after),
1435
+ feeds: {}
1436
+ } : positionOf(query.after);
1437
+ const until = Date.now() + (query.wait ?? 0) * 1e3;
1438
+ let busy = false;
1439
+ for (;;) {
1440
+ const started = Date.now();
1441
+ const page = await read(who, listed, position, query, signal);
1442
+ position = page.position;
1443
+ if (page.events.length > 0 || Date.now() >= until || signal.aborted) return {
1444
+ events: page.events,
1445
+ cursor: cursorOf(position)
1446
+ };
1447
+ if (!busy) busy = await changed(who, listed, position, until, signal) && Date.now() - started < 1e3;
1448
+ await pause(Math.min(started + 1e3, until) - Date.now(), signal);
1449
+ }
1450
+ }
1182
1451
  /** The one channel a read names, when the API can read it directly: not a subtree, and from one of its cursors or now. */
1183
1452
  async function oneChannel(who, query) {
1184
1453
  if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
@@ -1187,7 +1456,7 @@ function createVercel(options, environment) {
1187
1456
  return channel ?? null;
1188
1457
  }
1189
1458
  /** A watcher's tail registers with the API as its own: an API watcher, so a match is the API's to make. */
1190
- const tagOf = async (watch) => (await sha256(canonicalWatchers(watch))).slice(0, 32);
1459
+ const tagOf = async (watch, sync) => (await sha256(canonicalWatchers(watch, sync))).slice(0, 32);
1191
1460
  /** Who `--by` names, as the API's authors: an actor, a principal, or everyone here with that handle or profile, as of now. */
1192
1461
  async function authorsOf(who, by) {
1193
1462
  if (by === "me") return [await actorOf(who)];
@@ -1198,20 +1467,24 @@ function createVercel(options, environment) {
1198
1467
  }
1199
1468
  /**
1200
1469
  * A tail as the filter the API matches. The API reads no tails: channels, people, and threads are
1201
- * looked up here, now, and what it can't match (mentions, other sources) is refused rather than
1202
- * left to match nothing.
1470
+ * looked up here, now, and what it can't match (mentions) is refused rather than left to match
1471
+ * nothing. It matches no `--source` either: that's filtered here, where `fromHere` says it is.
1203
1472
  */
1204
- async function filterOf(who, id, spec) {
1473
+ function checkedTail(id, spec, fromHere) {
1205
1474
  const bad = (message) => new HttpError(400, "bad_watcher", `watch ${id}: ${message}`);
1206
1475
  if (!RemoteWatcherId.safeParse(id).success) throw bad("ids start with a letter and use up to 32 letters, numbers, and hyphens");
1207
- let filters;
1476
+ let compiled;
1208
1477
  try {
1209
- ({filters} = compileWatcher(id, spec));
1478
+ compiled = compileWatcher(id, spec);
1210
1479
  } catch (error) {
1211
1480
  throw new HttpError(400, "bad_watcher", error.message);
1212
1481
  }
1213
- if (filters.mentions !== void 0) throw bad("Vercel's boards can't match mentions yet");
1214
- if (filters.from !== void 0 && filters.from !== "board") throw bad(`nothing comes from ${filters.from} here: every message is written on the board`);
1482
+ if (compiled.filters.mentions !== void 0) throw bad("Vercel's boards can't match mentions yet");
1483
+ if (compiled.filters.from !== void 0 && !fromHere) throw bad("Vercel's API can't match --source: put the watcher in the board's config, which filters its matches itself");
1484
+ return compiled;
1485
+ }
1486
+ async function filterOf(who, id, spec, fromHere) {
1487
+ const { filters } = checkedTail(id, spec, fromHere);
1215
1488
  const filter = {};
1216
1489
  if (filters.channel !== void 0) {
1217
1490
  if (filters.channel.endsWith("/")) filter.channelTree = filters.channel.slice(0, -1);
@@ -1223,7 +1496,7 @@ function createVercel(options, environment) {
1223
1496
  }
1224
1497
  if (filters.re !== void 0) {
1225
1498
  const at = locate(filters.re);
1226
- if (!at) throw bad(`--re ${filters.re} names no message here`);
1499
+ if (!at) throw new HttpError(400, "bad_watcher", `watch ${id}: --re ${filters.re} names no message here`);
1227
1500
  filter.threadId = at.threadId;
1228
1501
  }
1229
1502
  if (filters.by !== void 0) filter.authors = await authorsOf(who, filters.by);
@@ -1232,10 +1505,7 @@ function createVercel(options, environment) {
1232
1505
  key,
1233
1506
  values: [...values]
1234
1507
  });
1235
- return {
1236
- filter,
1237
- when: spec.when ?? "matches"
1238
- };
1508
+ return { filter };
1239
1509
  }
1240
1510
  /** A filter shown as a tail again, for listing: what it matches, if not always as it was written. */
1241
1511
  async function tailOf(who, { filter }) {
@@ -1249,75 +1519,118 @@ function createVercel(options, environment) {
1249
1519
  return parts.join(" ");
1250
1520
  }
1251
1521
  /** Where a registration is woken, as board shows it: its URL, or a path on its project (and a preview's branch). */
1522
+ const syncOf = (found) => (found.sync ?? []).map(({ key, platform }) => ({
1523
+ key,
1524
+ platform
1525
+ }));
1252
1526
  const whereOf = (found) => found.path ? {
1253
1527
  url: null,
1254
1528
  path: found.path,
1255
1529
  ...found.branch ? { branch: found.branch } : {}
1256
1530
  } : { url: found.url };
1257
- async function registerAs(who, where, watch) {
1258
- const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, {
1259
- tail: spec.tail,
1260
- when: spec.when ?? "matches"
1261
- }]));
1262
- const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec)])));
1531
+ /**
1532
+ * Vercel's API takes watchers only from a deployment's own credentials: never a person's, an app's,
1533
+ * or a board token's, whoever made it. Anyone else's registration, pull, or ack is its 403
1534
+ * `watchers_need_project`.
1535
+ */
1536
+ const notADeployment = () => new HttpError(403, "watchers_need_project", "Vercel's API takes watchers only from a deployment's own credentials.", {
1537
+ hint: "Register them from the project's deployment, with no board token. Watchers in board()'s config run in this process instead.",
1538
+ origin: "handle"
1539
+ });
1540
+ const needsProject = (error) => error instanceof HttpError && error.code === "watchers_need_project" ? notADeployment() : error;
1541
+ async function watchersApi(...args) {
1542
+ try {
1543
+ return await api(...args);
1544
+ } catch (error) {
1545
+ throw needsProject(error);
1546
+ }
1547
+ }
1548
+ async function registerAs(who, where, watch, sync, fromHere) {
1549
+ const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, { tail: spec.tail }]));
1550
+ const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec, fromHere)])));
1551
+ const entries = sync.map(({ key, platform }) => ({
1552
+ key,
1553
+ platform
1554
+ }));
1263
1555
  let made;
1264
1556
  try {
1265
- made = await api(who, "PUT", await onBoard(who, "/watchers"), { body: {
1557
+ made = await syncApi(who, "PUT", await onBoard(who, "/watchers"), { body: {
1266
1558
  ...where,
1267
1559
  watch: filters,
1268
- tag: await tagOf(specs)
1560
+ tag: await tagOf(specs, entries),
1561
+ ...entries.length ? { sync: entries } : {}
1269
1562
  } });
1270
1563
  } catch (error) {
1271
- if (error instanceof HttpError && error.code === "board_token_unsupported") throw new HttpError(403, "board_token_unsupported", "a board token can't register watchers yet.", {
1272
- hint: "Register them with a person's or a deployment's own credentials.",
1273
- origin: "handle"
1274
- });
1275
- throw error;
1564
+ throw needsProject(error);
1276
1565
  }
1277
1566
  return {
1278
1567
  owner: made.owner,
1279
1568
  ...whereOf(made),
1280
1569
  watch: specs,
1281
- sync: [],
1570
+ sync: syncOf(made),
1282
1571
  hash: made.hash
1283
1572
  };
1284
1573
  }
1285
1574
  /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
1286
- async function matchOf(who, match, me) {
1575
+ async function matchOf(who, match, filters) {
1287
1576
  const found = await messageById(who, match.event.messageId).catch((error) => {
1288
1577
  if (error instanceof HttpError && error.status === 404) return null;
1289
1578
  throw error;
1290
1579
  });
1291
1580
  const channel = found && await channelById(who, found.thread.channelId);
1292
- const event = found && channel && await eventOf(who, match.event, channel.name, match.id, {}, me, found);
1581
+ if (!found || !channel) return null;
1582
+ 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, void 0, found);
1293
1583
  if (!event?.message) return null;
1584
+ const handed = match.watcher === "@sync" && event.type === "labels.changed" ? {
1585
+ ...event,
1586
+ before: {
1587
+ ...event.message,
1588
+ labels: labelsBefore(event.message.labels, match.event.labels)
1589
+ }
1590
+ } : event;
1294
1591
  return {
1295
1592
  id: match.id,
1296
1593
  watcher: match.watcher,
1297
1594
  thread: event.message.thread,
1298
1595
  lease: match.lease,
1299
1596
  attempt: match.attempt,
1300
- event
1597
+ event: handed
1301
1598
  };
1302
1599
  }
1303
- async function pullAs(who, query, signal) {
1304
- const { matches } = await api(who, "GET", await onBoard(who, "/watchers/matches"), {
1600
+ /** A thread bound to a target, as the event that has the sync owning its key backfill a channel: about the thread's root. */
1601
+ async function syncedOf(who, match, root, channel) {
1602
+ const { binding } = match.event;
1603
+ if (!binding) return null;
1604
+ const message = await view(who, root, channel);
1605
+ return boardEvent(who, match.event, match.id, "thread.synced", {
1606
+ thread: message.thread,
1607
+ target: binding.target,
1608
+ cause: binding.cause,
1609
+ kind: binding.targetKind,
1610
+ by: authorOf(match.event.actor)
1611
+ }, message);
1612
+ }
1613
+ async function pullAs(who, query, signal, specs = {}) {
1614
+ const { matches } = await watchersApi(who, "GET", await onBoard(who, "/watchers/matches"), {
1305
1615
  query: {
1306
1616
  limit: query.limit?.toString(),
1307
1617
  wait: query.wait?.toString()
1308
1618
  },
1309
1619
  ...signal ? { signal } : {}
1310
1620
  });
1311
- const me = await actorOf(who);
1312
- const shown = await Promise.all(matches.map((match) => matchOf(who, match, me)));
1313
- await Promise.all(matches.map((match, i) => shown[i] ? null : ackAs(who, match.id, {
1621
+ const sources = new Map(Object.entries(specs).map(([id, spec]) => [id, compileWatcher(id, spec).filters.from]));
1622
+ const handed = await Promise.all(matches.map((match) => {
1623
+ const from = sources.get(match.watcher);
1624
+ return matchOf(who, match, from === void 0 ? {} : { from });
1625
+ }));
1626
+ await Promise.all(matches.map((match, i) => handed[i] ? null : ackAs(who, match.id, {
1314
1627
  lease: match.lease,
1315
1628
  skip: true
1316
1629
  }).catch(() => {})));
1317
- return shown.filter((match) => match !== null);
1630
+ return handed.filter((match) => match !== null);
1318
1631
  }
1319
1632
  async function ackAs(who, id, body) {
1320
- await api(who, "POST", await onBoard(who, `/watchers/matches/${encodeURIComponent(id)}/ack`), { body: {
1633
+ await watchersApi(who, "POST", await onBoard(who, `/watchers/matches/${encodeURIComponent(id)}/ack`), { body: {
1321
1634
  lease: body.lease,
1322
1635
  ...body.error !== void 0 ? { error: body.error } : {},
1323
1636
  ...body.skip ? { skip: true } : {}
@@ -1337,19 +1650,194 @@ function createVercel(options, environment) {
1337
1650
  const runner = registrant({
1338
1651
  remote: "Vercel's API",
1339
1652
  registry: {
1340
- register: (where) => registerAs(deployment, where, tails),
1341
- matches: ({ signal, ...query }) => pullAs(deployment, query, signal),
1653
+ register: (where) => registerAs(deployment, where, tails, bound().sync, true).catch((error) => {
1654
+ if (error instanceof HttpError && error.code === "watchers_need_project") {
1655
+ refused = true;
1656
+ runner.close();
1657
+ runHere();
1658
+ }
1659
+ throw error;
1660
+ }),
1661
+ matches: ({ signal, ...query }) => pullAs(deployment, query, signal, tails),
1342
1662
  ack: (id, body) => ackAs(deployment, id, body)
1343
1663
  },
1344
- wakeAt: async (here) => wakePath(here) ?? { url: here },
1664
+ wakeAt: async (here) => wakePath(here) ?? { url: null },
1345
1665
  binding: bound,
1346
- hash: () => tagOf(tails),
1347
- hasWork: () => Object.keys(tails).length > 0,
1666
+ hash: () => tagOf(tails, bound().sync),
1667
+ hasWork: () => Object.keys(tails).length > 0 || bound().sync.length > 0,
1348
1668
  rethrow: (error) => {
1349
1669
  throw error;
1350
1670
  },
1351
1671
  registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
1352
1672
  });
1673
+ let deployed = null;
1674
+ /** Whether Vercel's API refused to register this board's watchers: its credentials aren't a deployment's own. */
1675
+ let refused = false;
1676
+ /**
1677
+ * Whether this board's own credentials are a deployment's own: a project's, and no board token. A
1678
+ * board token you set says so; one in a `fetch` passed in says so when the API refuses it.
1679
+ */
1680
+ const isDeployment = async () => {
1681
+ if (refused || !options.fetch && environment?.boardToken()) return false;
1682
+ return (deployed ??= self(deployment).then((found) => found.actor.principal.type === "project")).catch((error) => {
1683
+ deployed = null;
1684
+ throw error;
1685
+ });
1686
+ };
1687
+ let here = null;
1688
+ let deployedElse = false;
1689
+ /** Anyone else's watchers run in this process, as tails: nothing wakes a person. */
1690
+ function runHere() {
1691
+ if (here || deployedElse) return;
1692
+ if (deployedOnVercel()) {
1693
+ deployedElse = true;
1694
+ console.error("[board] watchers on a deployment need its own OIDC token: with a board token or another Vercel token, none run here");
1695
+ return;
1696
+ }
1697
+ const { sync, run } = bound();
1698
+ if (sync.length > 0) console.error("[board] sync doesn't run on Vercel's board as anyone but a deployment: run it from the project's deployment");
1699
+ const watchers = {};
1700
+ for (const [id, spec] of Object.entries(tails)) try {
1701
+ watchers[id] = checkedTail(id, spec, true);
1702
+ } catch (error) {
1703
+ console.error(`[board] watcher ${id} doesn't run:`, error.message);
1704
+ }
1705
+ here = tailWatchers({
1706
+ watchers,
1707
+ events: (query, signal) => eventsAs(deployment, query, signal),
1708
+ actorOf: (id) => actorOf({
1709
+ profile: { name: id },
1710
+ session: null
1711
+ }),
1712
+ run
1713
+ });
1714
+ here.start();
1715
+ }
1716
+ let failedAt = 0;
1717
+ /** On first use, a deployment registers its watchers with the API, and anyone else runs them here. */
1718
+ async function start() {
1719
+ if (here || Object.keys(tails).length === 0 && bound().sync.length === 0 || Date.now() - failedAt < WHO_AGAIN_MS) return;
1720
+ let project;
1721
+ try {
1722
+ project = await isDeployment();
1723
+ } catch (error) {
1724
+ failedAt = Date.now();
1725
+ console.error("[board] couldn't tell whether this board runs as a deployment:", error instanceof Error ? error.message : String(error));
1726
+ return;
1727
+ }
1728
+ if (project) await runner.start();
1729
+ else runHere();
1730
+ }
1731
+ /** The routes to register and wake: only a deployment's board is woken or registers. */
1732
+ const routes = runner.routes.map((route) => ({
1733
+ ...route,
1734
+ async handle(request, context) {
1735
+ if (context.caller || await isDeployment().catch(() => true)) return route.handle(request, context);
1736
+ waitUntil(start());
1737
+ if (route.path === "/wake") return json({ ran: 0 });
1738
+ throw notADeployment();
1739
+ }
1740
+ }));
1741
+ const platformUser = ({ id, handle, name, avatar, isBot }) => ({
1742
+ id,
1743
+ handle,
1744
+ name,
1745
+ avatar,
1746
+ isBot
1747
+ });
1748
+ /** An import as the API takes it: a channel by its ID, and a reply's `after` as its sequence in the thread. */
1749
+ async function importBody(who, body) {
1750
+ if (body.op === "seen") return {
1751
+ op: "seen",
1752
+ operationId: operationId(),
1753
+ author: platformUser(body.author)
1754
+ };
1755
+ const base = {
1756
+ op: body.op,
1757
+ operationId: operationId(),
1758
+ author: platformUser(body.author),
1759
+ ...body.from !== void 0 ? { from: body.from } : {}
1760
+ };
1761
+ if (body.op === "post") {
1762
+ if (body.attachments?.length) throw notSupported("files on imports");
1763
+ let after;
1764
+ if (body.after !== void 0) {
1765
+ const at = locate(body.after);
1766
+ const re = body.re === void 0 ? null : locate(body.re);
1767
+ if (!at || !re || at.threadId !== re.threadId) throw badRequest(`after: ${body.after} isn't in ${body.re ?? "the thread"}'s thread`, "invalid_after");
1768
+ after = at.sequence;
1769
+ }
1770
+ return {
1771
+ ...base,
1772
+ origin: body.origin === null ? null : originOf(body.origin),
1773
+ ...body.source ? { source: body.source } : {},
1774
+ ...body.channel !== void 0 ? { channelId: (await channelToPost(who, body.channel)).id } : {},
1775
+ ...body.re !== void 0 ? { re: body.re } : {},
1776
+ text: body.text,
1777
+ ...body.labels && Object.keys(body.labels).length ? { labels: body.labels } : {},
1778
+ ...body.noSync ? { noSync: true } : {},
1779
+ ...body.links?.length ? { links: body.links } : {},
1780
+ ...body.id !== void 0 ? { id: body.id } : {},
1781
+ ...after !== void 0 ? { after } : {}
1782
+ };
1783
+ }
1784
+ const changed = {
1785
+ ...base,
1786
+ ...body.origin !== void 0 ? { origin: body.origin } : {},
1787
+ ...body.message !== void 0 ? { message: body.message } : {}
1788
+ };
1789
+ if (body.op === "edit") return {
1790
+ ...changed,
1791
+ text: body.text,
1792
+ ...body.source ? { source: body.source } : {},
1793
+ ...body.revision !== void 0 ? { revision: body.revision } : {}
1794
+ };
1795
+ if (body.op === "delete") return {
1796
+ ...changed,
1797
+ ...body.revision !== void 0 ? { revision: body.revision } : {}
1798
+ };
1799
+ if (body.op === "react") return {
1800
+ ...changed,
1801
+ emoji: body.emoji,
1802
+ ...body.remove ? { remove: true } : {}
1803
+ };
1804
+ if (body.op === "labels") return {
1805
+ ...changed,
1806
+ ...body.set ? { set: body.set } : {},
1807
+ ...body.unset ? { unset: body.unset } : {},
1808
+ ...body.if && Object.keys(body.if).length ? { if: body.if } : {}
1809
+ };
1810
+ return {
1811
+ ...changed,
1812
+ links: body.links
1813
+ };
1814
+ }
1815
+ /** A sync key's inbox, under the board. */
1816
+ const inboxPath = (who, key, rest = "") => onBoard(who, `/sync/inbox/${encodeURIComponent(key)}${rest}`);
1817
+ /** A grant Vercel's API won't keep: one naming a GitHub run or an OIDC issuer, which an app stands in for. */
1818
+ const grantRefused = (error) => {
1819
+ if (error instanceof HttpError && error.code === "unsupported_principal") throw new HttpError(400, "unsupported_principal", "Vercel's board takes no GitHub or OIDC principals in a grant.", {
1820
+ hint: "Grant an app that an OIDC exchange policy issues tokens for: --app <slug>.",
1821
+ origin: "handle"
1822
+ });
1823
+ throw error;
1824
+ };
1825
+ /** An explain Vercel's API won't answer: for a GitHub run or an OIDC issuer, which no grant there names. */
1826
+ const explainRefused = (error) => {
1827
+ if (error instanceof HttpError && error.code === "unsupported_principal") throw new HttpError(400, "unsupported_principal", "Vercel's board explains no GitHub or OIDC caller: no grant names one.", {
1828
+ hint: "Explain the app an OIDC exchange policy issues tokens for: --app <slug>.",
1829
+ origin: "handle"
1830
+ });
1831
+ throw error;
1832
+ };
1833
+ /** A mint Vercel's API won't make: only a deployment mints board tokens there, and a board token mints from itself. */
1834
+ const mintRefused = (error) => {
1835
+ if (error instanceof HttpError && error.code === "unsupported_principal") throw new HttpError(403, "unsupported_principal", "Vercel's board mints board tokens only for a deployment.", {
1836
+ hint: "Mint it from a deployment, with its OIDC token, or from a board token.",
1837
+ origin: "handle"
1838
+ });
1839
+ throw error;
1840
+ };
1353
1841
  const methods = {
1354
1842
  ...Object.fromEntries(METHODS.map((method) => [method, async () => {
1355
1843
  throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
@@ -1368,7 +1856,10 @@ function createVercel(options, environment) {
1368
1856
  audience: origin,
1369
1857
  team_id: id,
1370
1858
  project_id: null,
1371
- sync: [],
1859
+ sync: (binding?.sync ?? []).map(({ key, platform }) => ({
1860
+ key,
1861
+ platform
1862
+ })),
1372
1863
  wake_by_path: true
1373
1864
  };
1374
1865
  },
@@ -1469,7 +1960,7 @@ function createVercel(options, environment) {
1469
1960
  const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
1470
1961
  return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
1471
1962
  };
1472
- if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0 && query.from !== "board") {
1963
+ if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0) {
1473
1964
  const { messages, feeds, newest } = await collect(who, query, signal);
1474
1965
  const latest = /* @__PURE__ */ new Map();
1475
1966
  for (const { message, thread, channel } of messages) latest.set(thread.id, {
@@ -1538,6 +2029,7 @@ function createVercel(options, environment) {
1538
2029
  },
1539
2030
  async upload(caller, { data, name, type }) {
1540
2031
  const who = whoOf(caller);
2032
+ if ("self" in caller && caller.self === "sync") throw new HttpError(501, "no_files", "Vercel's board takes no files from sync yet");
1541
2033
  if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
1542
2034
  if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
1543
2035
  const bytes = new Uint8Array(data);
@@ -1599,35 +2091,39 @@ function createVercel(options, environment) {
1599
2091
  const who = whoOf(caller);
1600
2092
  const clientId = input.id !== void 0 ? await clientIdOf(input.id) : void 0;
1601
2093
  let made;
2094
+ let channelName;
1602
2095
  if (input.channel !== void 0) {
1603
- const channel = await channelToPost(who, input.channel);
2096
+ channelName = input.channel;
1604
2097
  made = await api(who, "POST", await onBoard(who, "/threads"), {
1605
2098
  body: {
1606
2099
  operationId: operationId(),
1607
- channelId: channel.id,
2100
+ channel: input.channel,
1608
2101
  text: input.text,
1609
2102
  ...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
1610
2103
  ...clientId ? { clientId } : {},
1611
- ...input.attachments?.length ? { attachments: input.attachments } : {}
2104
+ ...input.attachments?.length ? { attachments: input.attachments } : {},
2105
+ ...input.noSync ? { noSync: true } : {}
1612
2106
  },
1613
2107
  signal
1614
2108
  });
1615
2109
  } else {
1616
2110
  const { thread, message: to, channel } = await messageIn(who, input.re, signal);
2111
+ channelName = channel.name;
1617
2112
  const after = input.after === void 0 ? void 0 : locate(input.after);
1618
2113
  if (after !== void 0 && after?.threadId !== thread.id) {
1619
2114
  const landed = clientId ? await api(who, "GET", await onBoard(who, `/posts/${encodeURIComponent(clientId)}`), { signal }).catch(() => null) : null;
1620
2115
  if (landed?.thread.id === thread.id) return { message: await view(who, landed.message, channel.name) };
1621
2116
  throw badRequest(`after: ${input.after} isn't in ${input.re}'s thread`, "invalid_after");
1622
2117
  }
1623
- made = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages`), {
2118
+ const reply = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages`), {
1624
2119
  body: {
1625
2120
  operationId: operationId(),
1626
2121
  text: input.text,
1627
2122
  ...to.sequence > 1 ? { replyTo: to.sequence } : {},
1628
2123
  ...clientId ? { clientId } : {},
1629
2124
  ...input.attachments?.length ? { attachments: input.attachments } : {},
1630
- ...after ? { after: after.sequence } : {}
2125
+ ...after ? { after: after.sequence } : {},
2126
+ ...input.noSync ? { noSync: true } : {}
1631
2127
  },
1632
2128
  signal
1633
2129
  }).catch((error) => {
@@ -1635,25 +2131,27 @@ function createVercel(options, environment) {
1635
2131
  throw error;
1636
2132
  });
1637
2133
  if (input.labels && Object.keys(input.labels).length) {
1638
- const labeled = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages/${made.message.sequence}/labels`), {
2134
+ const labeled = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages/${reply.message.sequence}/labels`), {
1639
2135
  body: {
1640
2136
  operationId: operationId(),
1641
2137
  set: input.labels
1642
2138
  },
1643
2139
  signal
1644
2140
  });
1645
- made = {
1646
- ...made,
1647
- message: {
1648
- ...made.message,
1649
- ...labeled.meta.labels ? { labels: labeled.meta.labels } : {},
1650
- version: labeled.meta.version
1651
- }
2141
+ reply.message = {
2142
+ ...reply.message,
2143
+ ...labeled.meta.labels ? { labels: labeled.meta.labels } : {},
2144
+ version: labeled.meta.version
1652
2145
  };
1653
2146
  }
2147
+ made = reply;
1654
2148
  }
1655
- const channel = await channelById(who, made.thread.channelId);
1656
- return { message: await view(who, made.message, channel.name) };
2149
+ const channelId = made.thread.channelId;
2150
+ if (channelId !== void 0) {
2151
+ if (clientId !== void 0 && posted.get(channelId) !== channelName) channelName = await channelById(who, channelId).then((channel) => (posted.set(channelId, channel.name), channel.name), () => channelName);
2152
+ else posted.set(channelId, channelName);
2153
+ }
2154
+ return { message: await view(who, "text" in made.message ? made.message : await sent(who, made.message, input), channelName) };
1657
2155
  },
1658
2156
  async posted(caller, { id }, signal) {
1659
2157
  const who = whoOf(caller);
@@ -1730,7 +2228,7 @@ function createVercel(options, environment) {
1730
2228
  ...input
1731
2229
  },
1732
2230
  ...signal ? { signal } : {}
1733
- });
2231
+ }).catch(grantRefused);
1734
2232
  return { grant: grantFrom(grant) };
1735
2233
  },
1736
2234
  async updateGrant(caller, { id, ...change }, signal) {
@@ -1741,7 +2239,7 @@ function createVercel(options, environment) {
1741
2239
  ...change
1742
2240
  },
1743
2241
  ...signal ? { signal } : {}
1744
- });
2242
+ }).catch(grantRefused);
1745
2243
  return { grant: grantFrom(grant) };
1746
2244
  },
1747
2245
  async explain(caller, { claim, ...query }, signal) {
@@ -1749,7 +2247,7 @@ function createVercel(options, environment) {
1749
2247
  const params = new URLSearchParams();
1750
2248
  for (const [name, value] of Object.entries(query)) if (value !== void 0) params.set(name, value);
1751
2249
  for (const pair of claim ?? []) params.append("claim", pair);
1752
- const explained = await api(who, "GET", await onBoard(who, `/grants/explain?${params}`), signal ? { signal } : {});
2250
+ const explained = await api(who, "GET", await onBoard(who, `/grants/explain?${params}`), signal ? { signal } : {}).catch(explainRefused);
1753
2251
  return {
1754
2252
  ...explained,
1755
2253
  grants: explained.grants.map(grantFrom)
@@ -1775,7 +2273,7 @@ function createVercel(options, environment) {
1775
2273
  ...input
1776
2274
  },
1777
2275
  ...signal ? { signal } : {}
1778
- });
2276
+ }).catch(mintRefused);
1779
2277
  return {
1780
2278
  ...created,
1781
2279
  token: tokenFrom(created.token)
@@ -1808,6 +2306,7 @@ function createVercel(options, environment) {
1808
2306
  ...target,
1809
2307
  text: input.text,
1810
2308
  ...labels ? { labels } : {},
2309
+ ...input.noSync ? { noSync: true } : {},
1811
2310
  firstAt,
1812
2311
  ...input.every !== void 0 ? { every: ms(input.every) } : {},
1813
2312
  ...until !== void 0 ? { until } : {},
@@ -1833,14 +2332,9 @@ function createVercel(options, environment) {
1833
2332
  if (!channel) return { schedules: [] };
1834
2333
  filter.channelId = channel.id;
1835
2334
  }
1836
- const me = query.by === "me" ? await actorOf(who) : void 0;
1837
- const by = me ?? query.by;
1838
- if (by?.startsWith("vercel:")) filter.createdBy = by;
1839
- const created = (actor) => by === void 0 || (me ? actor.id === me : [
1840
- actor.id,
1841
- principalId(actor.principal),
1842
- actor.profile?.name
1843
- ].includes(by));
2335
+ if (query.by?.startsWith("vercel:")) filter.createdBy = query.by;
2336
+ const by = await byOf(who, query.by);
2337
+ const created = (actor) => by === void 0 || by(actor);
1844
2338
  const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
1845
2339
  return { schedules: await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule))) };
1846
2340
  },
@@ -1855,59 +2349,166 @@ function createVercel(options, environment) {
1855
2349
  canceled
1856
2350
  };
1857
2351
  },
1858
- async events(caller, query, signal) {
2352
+ events: (caller, query, signal) => eventsAs(whoOf(caller), query, signal),
2353
+ async typing(caller, { id, status }, signal) {
2354
+ if (!binding || binding.sync.length === 0) return { targets: [] };
2355
+ const { message, replies } = await methods.message(caller, { id }, signal);
2356
+ return { targets: await binding.typing([message, ...replies], status) };
2357
+ },
2358
+ async readSource(_caller, { key, target, limit, after }) {
2359
+ if (!binding?.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: read it where its sync runs`, "not_synced_here");
2360
+ return binding.readSource(key, target, limit ?? 50, after ?? null);
2361
+ },
2362
+ async joinSource(_caller, { key, target }) {
2363
+ if (!binding?.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: join it where its sync runs`, "not_synced_here");
2364
+ return binding.joinSource(key, target);
2365
+ },
2366
+ async syncImport(caller, body, signal) {
1859
2367
  const who = whoOf(caller);
1860
- const channel = await oneChannel(who, query);
1861
- if (channel) return channelEvents(who, channel, query, signal);
1862
- 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`);
1863
- const listed = await channelsFor(who, query.channel);
1864
- let position = query.after === void 0 ? {
1865
- t: Date.now(),
1866
- feeds: await heads(who, listed)
1867
- } : locate(query.after) ? {
1868
- t: await timeOf(who, query.after),
1869
- feeds: {}
1870
- } : positionOf(query.after);
1871
- const until = Date.now() + (query.wait ?? 0) * 1e3;
1872
- let busy = false;
1873
- for (;;) {
1874
- const started = Date.now();
1875
- const page = await read(who, listed, position, query, signal);
1876
- position = page.position;
1877
- if (page.events.length > 0 || Date.now() >= until || signal.aborted) return {
1878
- events: page.events,
1879
- cursor: cursorOf(position)
1880
- };
1881
- if (!busy) busy = await changed(who, listed, position, until, signal) && Date.now() - started < 1e3;
1882
- await pause(Math.min(started + 1e3, until) - Date.now(), signal);
2368
+ return { message: (await syncApi(who, "POST", await onBoard(who, "/sync/imports"), {
2369
+ body: await importBody(who, body),
2370
+ signal
2371
+ }).catch((error) => {
2372
+ if (error instanceof HttpError && error.code === "newer_message" && body.op === "post") throw new HttpError(409, "newer_message", `a message came after ${body.after}`);
2373
+ throw error;
2374
+ })).message };
2375
+ },
2376
+ async syncReceipt(caller, body, signal) {
2377
+ const who = whoOf(caller);
2378
+ return syncApi(who, "POST", await onBoard(who, "/sync/receipts"), {
2379
+ body,
2380
+ signal
2381
+ });
2382
+ },
2383
+ async syncFind(caller, query, signal) {
2384
+ const who = whoOf(caller);
2385
+ const { thread, message } = await syncApi(who, "GET", await onBoard(who, "/sync/find"), {
2386
+ query,
2387
+ signal
2388
+ });
2389
+ return {
2390
+ thread,
2391
+ message
2392
+ };
2393
+ },
2394
+ async syncThread(caller, { thread }, signal) {
2395
+ const who = whoOf(caller);
2396
+ const found = await syncApi(who, "GET", await onBoard(who, `/sync/threads/${encodeURIComponent(thread)}`), { signal });
2397
+ return {
2398
+ ...found,
2399
+ channel: (await channelById(who, found.channel)).name
2400
+ };
2401
+ },
2402
+ async syncCopies(caller, { message }, signal) {
2403
+ const who = whoOf(caller);
2404
+ return syncApi(who, "GET", await onBoard(who, "/sync/copies"), {
2405
+ query: { message },
2406
+ signal
2407
+ });
2408
+ },
2409
+ async synced(caller, { id }, signal) {
2410
+ const who = whoOf(caller);
2411
+ if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
2412
+ const { targets } = await syncApi(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}/synced`), { signal });
2413
+ return { targets: await Promise.all(targets.map(async (target) => ({
2414
+ ...target,
2415
+ url: binding && target.thread !== null && target.message !== null ? await binding.linkOf(target.key, target.thread, target.message) : null
2416
+ }))) };
2417
+ },
2418
+ async linked(caller, { url }, signal) {
2419
+ const who = whoOf(caller);
2420
+ const missing = () => notFound("no message on this board for that link", "message_not_found");
2421
+ for (const { platform, thread, message } of binding?.locate(url) ?? []) for (const key of /* @__PURE__ */ new Set([...(binding?.sync ?? []).filter((entry) => entry.platform === platform).map((entry) => entry.key), platform])) {
2422
+ const found = await syncApi(who, "GET", await onBoard(who, "/sync/linked"), {
2423
+ query: {
2424
+ thread: `${key}:${thread}`,
2425
+ ...message !== null ? { message } : {}
2426
+ },
2427
+ signal
2428
+ }).catch((error) => {
2429
+ if (error instanceof HttpError && error.status === 404) return null;
2430
+ throw error;
2431
+ });
2432
+ if (found) return methods.message(caller, { id: found.message }, signal).catch((error) => {
2433
+ if (error instanceof HttpError && (error.status === 403 || error.status === 404)) throw missing();
2434
+ throw error;
2435
+ });
1883
2436
  }
2437
+ throw missing();
1884
2438
  },
1885
- async typing() {
1886
- return { targets: [] };
2439
+ async inboxPush(caller, { key, events }, signal) {
2440
+ const who = whoOf(caller);
2441
+ await syncApi(who, "POST", await inboxPath(who, key), {
2442
+ body: { events: events.map(({ id, event, raw }) => ({
2443
+ id,
2444
+ thread: event.thread,
2445
+ event,
2446
+ ...raw !== void 0 ? { raw } : {}
2447
+ })) },
2448
+ signal
2449
+ });
2450
+ return { ok: true };
2451
+ },
2452
+ async inboxNext(caller, { key, limit }, signal) {
2453
+ const who = whoOf(caller);
2454
+ const { items } = await syncApi(who, "GET", await inboxPath(who, key, "/next"), {
2455
+ query: { limit: limit?.toString() },
2456
+ signal
2457
+ });
2458
+ return { items: items.map(({ raw, ...item }) => ({
2459
+ ...item,
2460
+ key,
2461
+ raw: raw ?? null
2462
+ })) };
1887
2463
  },
1888
- async readSource(_caller, { key }) {
1889
- throw notFound(`this board doesn't run sync entry ${key}`, "not_synced_here");
2464
+ async inboxAck(caller, { key, id, lease, error }, signal) {
2465
+ const who = whoOf(caller);
2466
+ await syncApi(who, "POST", await inboxPath(who, key, `/${encodeURIComponent(id)}/ack`), {
2467
+ body: {
2468
+ lease,
2469
+ ...error !== void 0 ? { error } : {}
2470
+ },
2471
+ signal
2472
+ });
2473
+ return { ok: true };
2474
+ },
2475
+ async inbox(caller, { key, channel, limit }, signal) {
2476
+ const who = whoOf(caller);
2477
+ const wanted = Math.min(limit ?? 50, INBOX_LIST_MAX);
2478
+ const { events } = await syncApi(who, "GET", await inboxPath(who, key), {
2479
+ query: { limit: String(channel === void 0 ? wanted : INBOX_LIST_MAX) },
2480
+ signal
2481
+ });
2482
+ const entries = events.flatMap(({ id, createdAt, event, raw }) => event ? [{
2483
+ id,
2484
+ channel: typeof event.channel === "string" ? event.channel : "",
2485
+ createdAt,
2486
+ sync: key,
2487
+ event,
2488
+ raw: raw ?? null
2489
+ }] : []);
2490
+ return { events: (channel === void 0 ? entries : entries.filter((entry) => entry.channel === channel)).slice(0, wanted) };
1890
2491
  },
1891
2492
  async watchers(caller) {
1892
2493
  const who = whoOf(caller);
1893
- const { watchers } = await api(who, "GET", await onBoard(who, "/watchers"));
2494
+ const { watchers } = await watchersApi(who, "GET", await onBoard(who, "/watchers"));
1894
2495
  return { watchers: await Promise.all(watchers.map(async (found) => ({
1895
2496
  owner: found.owner,
1896
2497
  ...whereOf(found),
1897
- watch: Object.fromEntries(await Promise.all(Object.entries(found.watch).map(async ([id, spec]) => [id, {
1898
- tail: await tailOf(who, spec),
1899
- when: spec.when
1900
- }]))),
1901
- sync: [],
2498
+ watch: Object.fromEntries(await Promise.all(Object.entries(found.watch).map(async ([id, spec]) => [id, { tail: await tailOf(who, spec) }]))),
2499
+ sync: syncOf(found),
1902
2500
  hash: found.hash
1903
2501
  }))) };
1904
2502
  },
1905
2503
  async register(caller, body) {
1906
- if ((body.sync?.length ?? 0) > 0) throw notSupported("sync");
2504
+ if (typeof body.url === "string") throw new HttpError(400, "invalid_request", "Vercel's API wakes a deployment only by its path.", {
2505
+ hint: "Register a path, or no url to pull its matches.",
2506
+ origin: "handle"
2507
+ });
1907
2508
  return registerAs(whoOf(caller), typeof body.path === "string" ? {
1908
2509
  path: body.path,
1909
2510
  ...body.branch ? { branch: body.branch } : {}
1910
- } : { url: body.url ?? null }, body.watch);
2511
+ } : { url: body.url ?? null }, body.watch, body.sync ?? [], false);
1911
2512
  },
1912
2513
  async matches(caller, query, signal) {
1913
2514
  return { matches: await pullAs(whoOf(caller), query, signal) };
@@ -1920,27 +2521,31 @@ function createVercel(options, environment) {
1920
2521
  return {
1921
2522
  ...Object.fromEntries(Object.entries(methods).map(([name, method]) => [name, (caller, ...args) => {
1922
2523
  if ("identity" in caller) throw servesNone();
1923
- if (binding) runner.start();
2524
+ if (binding) waitUntil(start());
1924
2525
  return method(caller, ...args);
1925
2526
  }])),
1926
- routes: runner.routes,
2527
+ routes,
1927
2528
  keeps: false,
1928
2529
  sendsSchedulesHere: false,
1929
2530
  bind(next) {
1930
2531
  if (binding) throw new Error("vercel: this backend already serves a board: create one vercel() per board()");
1931
- if (Object.values(next.subscriptions).map((subscription) => subscription.kind).includes("sync")) throw new Error("vercel: Vercel's boards don't run sync yet: leave `sync` out");
1932
2532
  if (options.team && next.team && options.team !== next.team) throw new Error(`vercel: board() names team ${next.team}, and vercel() team ${options.team}: name the team once`);
1933
2533
  for (const id of Object.keys(next.subscriptions)) own.add(id);
1934
- tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, {
1935
- tail: subscription.tail,
1936
- when: subscription.when
1937
- }]] : []));
2534
+ tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, { tail: subscription.tail }]] : []));
1938
2535
  binding = next;
1939
2536
  },
1940
- /** Registers this board's watchers with Vercel's API now, as `POST /watchers` does. */
1941
- registerWatchers: runner.registerNow,
1942
- /** Stops pulling, for a board that pulls on its own. */
1943
- close: runner.close
2537
+ /** Registers this board's watchers with Vercel's API now, as `POST /watchers` does: only a deployment's. */
2538
+ async registerWatchers() {
2539
+ if (await isDeployment()) return runner.registerNow();
2540
+ waitUntil(start());
2541
+ throw notADeployment();
2542
+ },
2543
+ /** Stops pulling, for a board that pulls on its own, and the tails of one that runs them here. */
2544
+ close() {
2545
+ runner.close();
2546
+ here?.close();
2547
+ here = null;
2548
+ }
1944
2549
  };
1945
2550
  }
1946
2551
  //#endregion
@@ -2081,7 +2686,7 @@ function createPolicy(options, keeps, serving, trust = null) {
2081
2686
  };
2082
2687
  throw error;
2083
2688
  }
2084
- const scope = principal.scope === void 0 ? null : compileAccess(parseScope(principal.scope));
2689
+ const scope = principal.scope === void 0 ? null : compileAccess(parseCan(principal.scope));
2085
2690
  const allowed = (permissions) => scope ? permissions.filter((permission) => scope.can(permission, channel)) : [...permissions];
2086
2691
  if ("fixed" in resolved) return {
2087
2692
  pattern: null,
@@ -2112,7 +2717,7 @@ function createPolicy(options, keeps, serving, trust = null) {
2112
2717
  async identify(request) {
2113
2718
  const found = await principalOf(request);
2114
2719
  const claims = found.pinned ? pinnedClaims(found.pinned, request.claims) : request.claims;
2115
- const scope = found.scope === void 0 ? claims.scope ?? void 0 : claims.scope === null ? found.scope : scopeOf(compileAccess(parseScope(found.scope)).narrow(parseScope(claims.scope)));
2720
+ const scope = found.scope === void 0 ? claims.scope ?? void 0 : claims.scope === null ? found.scope : canText(compileAccess(parseCan(found.scope)).narrow(parseCan(claims.scope)));
2116
2721
  const principal = scope === void 0 ? found : {
2117
2722
  ...found,
2118
2723
  scope
@@ -2174,6 +2779,13 @@ const LOGOS = {
2174
2779
  //#region src/server/avatars.ts
2175
2780
  /** Each known agent's mark on its color. */
2176
2781
  const STYLES = {
2782
+ fx: {
2783
+ background: "#000000",
2784
+ mark: {
2785
+ path: "M237.892 0C243.178 8.73262e-05 249.383 1.41857 253.025 3.07422L255.093 4.01367L250.076 18.6299L247.677 17.7461C244.901 16.7234 241.938 15.7998 238.491 15.7998C234.984 15.7998 232.787 16.5601 231.08 18.3213C229.231 20.2297 227.629 23.6395 226.229 29.7578L226.227 29.7617L226.228 29.7627L225.136 34.8506H241.669L260.432 34.9502L260.694 34.9512L260.842 35.1689L278.854 61.6328L296.736 34.9502H320.866L291.676 76.7402L322.102 119.75H299.331L299.182 119.546L241.144 40.4775L239.35 49.4004H222.069L205.688 127.208C203.927 135.709 201.185 142.838 196.777 147.866C192.27 153.008 186.201 155.75 178.342 155.75C174.181 155.75 170.746 155.109 167.909 154.107L166.241 153.519V137.182L166.899 137.4L169.531 138.278C172.182 139.162 174.414 139.8 177.142 139.8C178.528 139.8 179.703 139.526 180.732 138.98C181.764 138.434 182.677 137.6 183.52 136.442C185.304 133.989 186.716 130.135 187.897 124.672L203.76 49.4004H189.874L191.759 39.4375L192.039 39.3457L206.818 34.4668L208.154 28.6416C210.516 18.2065 213.772 10.9381 218.708 6.31836C223.737 1.61217 230.127 3.08752e-05 237.892 0ZM273.987 99.084L260.073 120.25H234.541L261.003 82.0215L273.987 99.084Z",
2786
+ transform: "scale(0.71111) translate(34 33.95) scale(0.7186) translate(-166.241 0)"
2787
+ }
2788
+ },
2177
2789
  claude: {
2178
2790
  background: "#D97757",
2179
2791
  mark: { path: LOGOS.claude }
@@ -2197,7 +2809,7 @@ function avatarSvg(name) {
2197
2809
  background: "#666666",
2198
2810
  mark: { glyph: name.slice(0, 1).toUpperCase() }
2199
2811
  };
2200
- const mark = "path" in style.mark ? `<path transform="translate(30 30) scale(2.8333)" fill="#ffffff" d="${style.mark.path}"/>` : `<text x="64" y="86" font-family="ui-sans-serif,system-ui,sans-serif" font-size="66" font-weight="600" text-anchor="middle" fill="#ffffff">${style.mark.glyph}</text>`;
2812
+ const mark = "path" in style.mark ? `<path transform="${style.mark.transform ?? "translate(30 30) scale(2.8333)"}" fill="#ffffff" d="${style.mark.path}"/>` : `<text x="64" y="86" font-family="ui-sans-serif,system-ui,sans-serif" font-size="66" font-weight="600" text-anchor="middle" fill="#ffffff">${style.mark.glyph}</text>`;
2201
2813
  return `<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><rect width="128" height="128" rx="28" fill="${style.background}"/>${mark}</svg>`;
2202
2814
  }
2203
2815
  //#endregion
@@ -3101,6 +3713,7 @@ async function createServe(context) {
3101
3713
  const made = CREATED.has(target.name) || target.name === "createChannel" && output.created;
3102
3714
  return json(output, made ? 201 : 200);
3103
3715
  } catch (error) {
3716
+ if (request.signal.aborted && error === request.signal.reason) return new Response(null, { status: 499 });
3104
3717
  return toErrorResponse(error);
3105
3718
  }
3106
3719
  }
@@ -3274,8 +3887,7 @@ function createBoard(options, runtime) {
3274
3887
  };
3275
3888
  const subscriptions = Object.fromEntries(Object.entries(watch).map(([id, watcher]) => [id, {
3276
3889
  kind: "tail",
3277
- tail: watcher.tail,
3278
- when: watcher.when ?? "matches"
3890
+ tail: watcher.tail
3279
3891
  }]));
3280
3892
  if (Object.keys(entries).length > 0) subscriptions[SYNC] = { kind: "sync" };
3281
3893
  /** This board's sync entries, as its sync and discovery see them. */