@vercel/board 0.36.0 → 0.37.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 (70) hide show
  1. package/dist/access.d.mts +2 -2
  2. package/dist/access.mjs +1 -1
  3. package/dist/{actors-DFOpTw89.mjs → actors-uoD62kiN.mjs} +1 -0
  4. package/dist/{auth-C21V0EK1.d.mts → auth-BHXgi696.d.mts} +1 -1
  5. package/dist/{backend-D21q8mdm.d.mts → backend-BIvl2z1z.d.mts} +3 -9
  6. package/dist/backend-local.d.mts +1 -1
  7. package/dist/backend-local.mjs +1 -1
  8. package/dist/{chat-provider-Bb-jeJLY.mjs → chat-provider-C0WUS3-G.mjs} +1 -1
  9. package/dist/{chat-provider-DmZCmBkb.d.mts → chat-provider-DFYEReZL.d.mts} +2 -2
  10. package/dist/cli-commands.mjs +1 -1
  11. package/dist/cli-embedded.d.mts +18 -2
  12. package/dist/cli-embedded.mjs +22 -4
  13. package/dist/cli.mjs +50 -676
  14. package/dist/{commands-BLtqSwha.mjs → commands-D2pFCMSh.mjs} +11 -0
  15. package/dist/{conformance-CKrwglzA.mjs → conformance-rCrc_mwi.mjs} +2 -3
  16. package/dist/conformance.d.mts +1 -1
  17. package/dist/conformance.mjs +1 -1
  18. package/dist/digest-CLGw7653.mjs +4 -0
  19. package/dist/{engine-B_prP0b8.mjs → engine-COa73McY.mjs} +16 -12
  20. package/dist/{events-AEKh9tJm.mjs → events-v8f7pF9f.mjs} +21 -7
  21. package/dist/exports-Bb0m03fT.d.mts +4 -0
  22. package/dist/{exports-Ck4Xu3OV.mjs → exports-DTezg4xR.mjs} +728 -171
  23. package/dist/{index-LREsSZb2.d.mts → index-B1TZrMMu.d.mts} +2 -2
  24. package/dist/index.d.mts +5 -5
  25. package/dist/index.mjs +3 -3
  26. package/dist/index.node.d.mts +5 -5
  27. package/dist/index.node.mjs +2 -2
  28. package/dist/inspect/app.js +35 -35
  29. package/dist/inspect/engine.js +5 -5
  30. package/dist/inspect-B8c0Wh5Z.mjs +2 -0
  31. package/dist/inspect-CoFk2Xj7.mjs +643 -0
  32. package/dist/{local-DJ_qI9q7.mjs → local-Cm7a7_Q0.mjs} +10 -65
  33. package/dist/{main-Jz4nbNJi.mjs → main-DoZ8IFPb.mjs} +9 -7
  34. package/dist/{middleware-BxgizazV.mjs → middleware-k_XKQ6f7.mjs} +9 -1
  35. package/dist/page-BAQpb-s-.mjs +2 -0
  36. package/dist/page-LysMGAl3.mjs +30 -0
  37. package/dist/{provider-DEOfc4Ls.d.mts → provider-7pOnK8Jw.d.mts} +5 -3
  38. package/dist/{routes-BpKdMvgX.d.mts → routes-BtsZzal-.d.mts} +0 -17
  39. package/dist/{serve-Puf3I-oI.mjs → serve-2U_JPJtS.mjs} +2 -2
  40. package/dist/{server-CS-1aeTl.mjs → server-Drul_uwj.mjs} +18 -10
  41. package/dist/sync-chat-sdk.d.mts +2 -2
  42. package/dist/sync-chat-sdk.mjs +2 -2
  43. package/dist/sync-github.d.mts +2 -2
  44. package/dist/sync-github.mjs +2 -2
  45. package/dist/sync-linear.d.mts +3 -3
  46. package/dist/sync-linear.mjs +2 -2
  47. package/dist/sync-slack.d.mts +3 -3
  48. package/dist/sync-slack.mjs +2 -2
  49. package/dist/sync.d.mts +2 -2
  50. package/dist/sync.mjs +1 -1
  51. package/dist/{targets-Dk_xgS9q.mjs → targets-B0D4tJDY.mjs} +63 -18
  52. package/docs/01-board/01-mounting.md +11 -8
  53. package/docs/01-board/03-identity.md +2 -1
  54. package/docs/01-board/06-watchers.md +71 -40
  55. package/docs/01-quickstart.md +1 -1
  56. package/docs/02-sync/01-overview.md +7 -7
  57. package/docs/02-sync/02-functions.md +5 -8
  58. package/docs/02-sync/03-slack.md +0 -8
  59. package/docs/02-sync/04-github.md +0 -8
  60. package/docs/02-sync/07-linear.md +0 -6
  61. package/docs/03-guides/01-coding-agents.md +1 -0
  62. package/docs/03-guides/02-inspector.md +3 -2
  63. package/docs/03-guides/04-triage.md +8 -13
  64. package/docs/04-reference/01-cli.md +28 -4
  65. package/docs/04-reference/03-http.md +1 -1
  66. package/docs/04-reference/05-conformance.md +1 -1
  67. package/docs/index.md +3 -10
  68. package/package.json +2 -1
  69. package/dist/attempts-HXcskN1w.mjs +0 -10
  70. 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
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";
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-B0D4tJDY.mjs";
4
+ import { a as waitUntil, r as runMiddleware, s as derivedId, t as DroppedError, u as sha256 } from "./middleware-k_XKQ6f7.mjs";
5
5
  import { d as scopeOf, l as parsePattern, r as PERMISSIONS, s as compileAccess, u as parseScope } from "./access-BsP0hvcC.mjs";
6
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";
7
+ import { i as resolveActor, r as claimsOf, t as KNOWN_AGENTS } from "./actors-uoD62kiN.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 = [];
@@ -600,7 +788,7 @@ function createVercel(options, environment) {
600
788
  if (!found && await again.views.then(() => true, () => false)) unlisted.add(actor.id);
601
789
  }
602
790
  const kind = found && apiKind(found.kind);
603
- if (!found || !(kind === "person" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
791
+ if (!found || !(kind === "person" || kind === "external" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
604
792
  return {
605
793
  id: actor.id,
606
794
  kind,
@@ -622,15 +810,20 @@ function createVercel(options, environment) {
622
810
  reactions: message.deletedAt === void 0 ? await reactors(who, message) : {},
623
811
  mentions: [],
624
812
  by: authorOf(message.createdBy),
625
- noSync: false,
626
- origin: null,
627
- from: null,
813
+ noSync: message.noSync ?? false,
814
+ origin: originOf(message.origin),
815
+ from: message.from ?? null,
628
816
  createdAt: iso(message.createdAt),
629
817
  editedAt: message.editedAt === void 0 ? null : iso(message.editedAt),
630
818
  deleted: message.deletedAt !== void 0,
631
819
  undelivered: {},
632
820
  attachments: message.attachments ?? [],
633
- links: [],
821
+ links: (message.links ?? []).map((link) => ({
822
+ url: link.url,
823
+ message: link.message ?? null,
824
+ snapshot: link.snapshot ?? null,
825
+ unavailable: link.unavailable ?? null
826
+ })),
634
827
  version: message.version,
635
828
  revision: message.revision,
636
829
  author: await nameOf(who, message.createdBy),
@@ -648,7 +841,7 @@ function createVercel(options, environment) {
648
841
  re: schedule.threadId === void 0 ? null : idAt(schedule.threadId, 1),
649
842
  text: schedule.text,
650
843
  labels: { ...schedule.labels },
651
- noSync: false,
844
+ noSync: schedule.noSync ?? false,
652
845
  attachments: [],
653
846
  first: iso(schedule.firstAt),
654
847
  every: schedule.every ?? null,
@@ -700,23 +893,43 @@ function createVercel(options, environment) {
700
893
  skip: 0
701
894
  }]));
702
895
  }
896
+ /** Handles a fresh read of the names didn't have, by when: `--by` doesn't read again for them for a while. */
897
+ const unhandled = /* @__PURE__ */ new Map();
898
+ /**
899
+ * Who `--by` names: `me`, the actor itself; or an actor, a principal and its agents, a profile, or
900
+ * a handle as the board shows it (`julian`, `julian/claude`), a person's covering their agents.
901
+ */
902
+ async function byOf(who, by) {
903
+ if (by === void 0) return void 0;
904
+ if (by === "me") {
905
+ const me = await actorOf(who);
906
+ return (actor) => actor.id === me;
907
+ }
908
+ const named = /* @__PURE__ */ new Set([by]);
909
+ if (!by.startsWith("vercel:")) {
910
+ const handle = by.toLowerCase();
911
+ const find = async (read) => [...await read.views].filter(([, view]) => view.handle.toLowerCase() === handle).map(([id]) => id);
912
+ const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
913
+ let ids = await find(kept ?? readNames(who));
914
+ const missed = unhandled.get(handle);
915
+ if (ids.length === 0 && kept && !(missed !== void 0 && Date.now() - missed <= NAMES_FRESH_MS)) ids = await find(readNames(who));
916
+ if (ids.length === 0) {
917
+ if (unhandled.size >= 1e3) unhandled.clear();
918
+ if (!kept || missed === void 0 || Date.now() - missed > NAMES_FRESH_MS) unhandled.set(handle, Date.now());
919
+ }
920
+ for (const id of ids) named.add(id);
921
+ }
922
+ return (actor) => named.has(actor.id) || named.has(principalId(actor.principal)) || actor.profile !== void 0 && named.has(actor.profile.name);
923
+ }
703
924
  /**
704
925
  * Whether a message matches a read's filters. A label matches on the message or its thread's root:
705
926
  * `thread`'s labels, as `labeledBy` gives them when the read filters on labels.
706
927
  */
707
- function matches(filters, message, thread, me) {
928
+ function matches(filters, message, thread, by) {
708
929
  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
- }
930
+ if (by && !by(message.createdBy)) return false;
718
931
  if (filters.mentions !== void 0) return false;
719
- if (filters.from !== void 0 && filters.from !== "board") return false;
932
+ if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
720
933
  if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
721
934
  for (const [key, values] of filters.label ?? []) {
722
935
  const on = (labels) => labels !== void 0 && Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
@@ -846,7 +1059,7 @@ function createVercel(options, environment) {
846
1059
  }))))).flat();
847
1060
  }
848
1061
  const feeds = await heads(who, listed);
849
- const mine = await actorOf(who);
1062
+ const by = await byOf(who, filters.by);
850
1063
  let newest = 0;
851
1064
  const messages = [];
852
1065
  for (const { thread, channel } of threads) {
@@ -854,7 +1067,7 @@ function createVercel(options, environment) {
854
1067
  const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
855
1068
  for (const message of all) {
856
1069
  newest = Math.max(newest, message.createdAt);
857
- if (matches(filters, message, labeled, mine)) messages.push({
1070
+ if (matches(filters, message, labeled, by)) messages.push({
858
1071
  message,
859
1072
  thread,
860
1073
  channel
@@ -905,7 +1118,7 @@ function createVercel(options, environment) {
905
1118
  };
906
1119
  }
907
1120
  /** 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)) {
1121
+ async function eventOf(who, change, channel, cursor, filters, authors, given, threads = threadReader(who)) {
909
1122
  if (!change.messageId || !change.type.startsWith("message.")) return null;
910
1123
  let found = given ?? await messageById(who, change.messageId).catch((error) => {
911
1124
  if (error instanceof HttpError && error.status === 404) return null;
@@ -915,9 +1128,10 @@ function createVercel(options, environment) {
915
1128
  ...found,
916
1129
  thread: found.message.sequence === 1 ? labeledBy(found.thread, found.message) : await threads(found.thread.id)
917
1130
  };
918
- if (!found || !matches(filters, found.message, found.thread, me)) return null;
1131
+ if (!found || !matches(filters, found.message, found.thread, authors)) return null;
919
1132
  const message = await view(who, found.message, channel);
920
1133
  const by = authorOf(change.actor);
1134
+ const from = change.from ?? null;
921
1135
  const base = {
922
1136
  id: message.id,
923
1137
  thread: message.thread
@@ -934,13 +1148,13 @@ function createVercel(options, environment) {
934
1148
  replyTo: message.replyTo,
935
1149
  thread: message.thread,
936
1150
  labels: message.labels,
937
- noSync: false,
1151
+ noSync: message.noSync,
938
1152
  mentions: [],
939
1153
  by,
940
- origin: null,
941
- from: null,
1154
+ origin: message.origin,
1155
+ from: message.from,
942
1156
  attachments: message.attachments,
943
- links: []
1157
+ links: message.links
944
1158
  };
945
1159
  break;
946
1160
  case "message.edited":
@@ -950,7 +1164,7 @@ function createVercel(options, environment) {
950
1164
  text: message.text,
951
1165
  mentions: [],
952
1166
  by,
953
- from: null
1167
+ from
954
1168
  };
955
1169
  break;
956
1170
  case "message.deleted":
@@ -958,7 +1172,7 @@ function createVercel(options, environment) {
958
1172
  payload = {
959
1173
  ...base,
960
1174
  by,
961
- from: null
1175
+ from
962
1176
  };
963
1177
  break;
964
1178
  case "message.reaction_added":
@@ -968,7 +1182,7 @@ function createVercel(options, environment) {
968
1182
  ...base,
969
1183
  emoji: change.emoji,
970
1184
  by,
971
- from: null
1185
+ from
972
1186
  };
973
1187
  break;
974
1188
  case "message.labeled": {
@@ -984,15 +1198,16 @@ function createVercel(options, environment) {
984
1198
  }
985
1199
  default: return null;
986
1200
  }
987
- return {
988
- cursor,
989
- type,
990
- createdAt: iso(change.createdAt),
991
- payload,
992
- message,
993
- actor: await nameOf(who, change.actor)
994
- };
995
- }
1201
+ return boardEvent(who, change, cursor, type, payload, message);
1202
+ }
1203
+ const boardEvent = async (who, change, cursor, type, payload, message) => ({
1204
+ cursor,
1205
+ type,
1206
+ createdAt: iso(change.createdAt),
1207
+ payload,
1208
+ message,
1209
+ actor: await nameOf(who, change.actor)
1210
+ });
996
1211
  /**
997
1212
  * One read of every channel's feed from `position`: its events, merged by time, each with the
998
1213
  * position right after it, and the position after them all.
@@ -1020,7 +1235,7 @@ function createVercel(options, environment) {
1020
1235
  events
1021
1236
  };
1022
1237
  }));
1023
- const mine = await actorOf(who);
1238
+ const by = await byOf(who, filters.by);
1024
1239
  const threads = threadReader(who, signal);
1025
1240
  const running = { ...position.feeds };
1026
1241
  const merged = pages.flatMap((page) => page.events.map((event) => ({
@@ -1036,7 +1251,7 @@ function createVercel(options, environment) {
1036
1251
  const event = await eventOf(who, change, page.channel.name, cursorOf({
1037
1252
  t: change.createdAt,
1038
1253
  feeds: { ...running }
1039
- }), filters, mine, void 0, threads);
1254
+ }), filters, by, void 0, threads);
1040
1255
  if (event) events.push(event);
1041
1256
  }
1042
1257
  const after = { ...position.feeds };
@@ -1107,8 +1322,8 @@ function createVercel(options, environment) {
1107
1322
  const limit = query.limit ?? 50;
1108
1323
  const thread = threadReader(who, signal);
1109
1324
  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);
1325
+ const by = narrowed ? await byOf(who, query.by) : void 0;
1326
+ const keep = async (message) => !narrowed || matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, by);
1112
1327
  const kept = [];
1113
1328
  if (query.after === void 0) {
1114
1329
  const page = await api(who, "GET", path, {
@@ -1147,7 +1362,7 @@ function createVercel(options, environment) {
1147
1362
  async function channelEvents(who, channel, query, signal) {
1148
1363
  const path = await onBoard(who, "/changes");
1149
1364
  const thread = threadReader(who, signal);
1150
- const me = await actorOf(who);
1365
+ const by = await byOf(who, query.by);
1151
1366
  const until = Date.now() + (query.wait ?? 0) * 1e3;
1152
1367
  let cursor = query.after;
1153
1368
  for (;;) {
@@ -1170,7 +1385,7 @@ function createVercel(options, environment) {
1170
1385
  thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
1171
1386
  } : null;
1172
1387
  if (!found) continue;
1173
- const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, me, found);
1388
+ const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, by, found);
1174
1389
  if (event) events.push(event);
1175
1390
  }
1176
1391
  if (events.length > 0 || Date.now() >= until || signal.aborted) return {
@@ -1179,6 +1394,33 @@ function createVercel(options, environment) {
1179
1394
  };
1180
1395
  }
1181
1396
  }
1397
+ /** A read of the feed, as `vb tail` makes it: one channel's feed when it names one, or every channel's. */
1398
+ async function eventsAs(who, query, signal) {
1399
+ const channel = await oneChannel(who, query);
1400
+ if (channel) return channelEvents(who, channel, query, signal);
1401
+ 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`);
1402
+ const listed = await channelsFor(who, query.channel);
1403
+ let position = query.after === void 0 ? {
1404
+ t: Date.now(),
1405
+ feeds: await heads(who, listed)
1406
+ } : locate(query.after) ? {
1407
+ t: await timeOf(who, query.after),
1408
+ feeds: {}
1409
+ } : positionOf(query.after);
1410
+ const until = Date.now() + (query.wait ?? 0) * 1e3;
1411
+ let busy = false;
1412
+ for (;;) {
1413
+ const started = Date.now();
1414
+ const page = await read(who, listed, position, query, signal);
1415
+ position = page.position;
1416
+ if (page.events.length > 0 || Date.now() >= until || signal.aborted) return {
1417
+ events: page.events,
1418
+ cursor: cursorOf(position)
1419
+ };
1420
+ if (!busy) busy = await changed(who, listed, position, until, signal) && Date.now() - started < 1e3;
1421
+ await pause(Math.min(started + 1e3, until) - Date.now(), signal);
1422
+ }
1423
+ }
1182
1424
  /** 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
1425
  async function oneChannel(who, query) {
1184
1426
  if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
@@ -1187,7 +1429,7 @@ function createVercel(options, environment) {
1187
1429
  return channel ?? null;
1188
1430
  }
1189
1431
  /** 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);
1432
+ const tagOf = async (watch, sync) => (await sha256(canonicalWatchers(watch, sync))).slice(0, 32);
1191
1433
  /** Who `--by` names, as the API's authors: an actor, a principal, or everyone here with that handle or profile, as of now. */
1192
1434
  async function authorsOf(who, by) {
1193
1435
  if (by === "me") return [await actorOf(who)];
@@ -1198,20 +1440,24 @@ function createVercel(options, environment) {
1198
1440
  }
1199
1441
  /**
1200
1442
  * 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.
1443
+ * looked up here, now, and what it can't match (mentions) is refused rather than left to match
1444
+ * nothing. It matches no `--source` either: that's filtered here, where `fromHere` says it is.
1203
1445
  */
1204
- async function filterOf(who, id, spec) {
1446
+ function checkedTail(id, spec, fromHere) {
1205
1447
  const bad = (message) => new HttpError(400, "bad_watcher", `watch ${id}: ${message}`);
1206
1448
  if (!RemoteWatcherId.safeParse(id).success) throw bad("ids start with a letter and use up to 32 letters, numbers, and hyphens");
1207
- let filters;
1449
+ let compiled;
1208
1450
  try {
1209
- ({filters} = compileWatcher(id, spec));
1451
+ compiled = compileWatcher(id, spec);
1210
1452
  } catch (error) {
1211
1453
  throw new HttpError(400, "bad_watcher", error.message);
1212
1454
  }
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`);
1455
+ if (compiled.filters.mentions !== void 0) throw bad("Vercel's boards can't match mentions yet");
1456
+ 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");
1457
+ return compiled;
1458
+ }
1459
+ async function filterOf(who, id, spec, fromHere) {
1460
+ const { filters } = checkedTail(id, spec, fromHere);
1215
1461
  const filter = {};
1216
1462
  if (filters.channel !== void 0) {
1217
1463
  if (filters.channel.endsWith("/")) filter.channelTree = filters.channel.slice(0, -1);
@@ -1223,7 +1469,7 @@ function createVercel(options, environment) {
1223
1469
  }
1224
1470
  if (filters.re !== void 0) {
1225
1471
  const at = locate(filters.re);
1226
- if (!at) throw bad(`--re ${filters.re} names no message here`);
1472
+ if (!at) throw new HttpError(400, "bad_watcher", `watch ${id}: --re ${filters.re} names no message here`);
1227
1473
  filter.threadId = at.threadId;
1228
1474
  }
1229
1475
  if (filters.by !== void 0) filter.authors = await authorsOf(who, filters.by);
@@ -1232,10 +1478,7 @@ function createVercel(options, environment) {
1232
1478
  key,
1233
1479
  values: [...values]
1234
1480
  });
1235
- return {
1236
- filter,
1237
- when: spec.when ?? "matches"
1238
- };
1481
+ return { filter };
1239
1482
  }
1240
1483
  /** A filter shown as a tail again, for listing: what it matches, if not always as it was written. */
1241
1484
  async function tailOf(who, { filter }) {
@@ -1249,75 +1492,118 @@ function createVercel(options, environment) {
1249
1492
  return parts.join(" ");
1250
1493
  }
1251
1494
  /** Where a registration is woken, as board shows it: its URL, or a path on its project (and a preview's branch). */
1495
+ const syncOf = (found) => (found.sync ?? []).map(({ key, platform }) => ({
1496
+ key,
1497
+ platform
1498
+ }));
1252
1499
  const whereOf = (found) => found.path ? {
1253
1500
  url: null,
1254
1501
  path: found.path,
1255
1502
  ...found.branch ? { branch: found.branch } : {}
1256
1503
  } : { 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)])));
1504
+ /**
1505
+ * Vercel's API takes watchers only from a deployment's own credentials: never a person's, an app's,
1506
+ * or a board token's, whoever made it. Anyone else's registration, pull, or ack is its 403
1507
+ * `watchers_need_project`.
1508
+ */
1509
+ const notADeployment = () => new HttpError(403, "watchers_need_project", "Vercel's API takes watchers only from a deployment's own credentials.", {
1510
+ hint: "Register them from the project's deployment, with no board token. Watchers in board()'s config run in this process instead.",
1511
+ origin: "handle"
1512
+ });
1513
+ const needsProject = (error) => error instanceof HttpError && error.code === "watchers_need_project" ? notADeployment() : error;
1514
+ async function watchersApi(...args) {
1515
+ try {
1516
+ return await api(...args);
1517
+ } catch (error) {
1518
+ throw needsProject(error);
1519
+ }
1520
+ }
1521
+ async function registerAs(who, where, watch, sync, fromHere) {
1522
+ const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, { tail: spec.tail }]));
1523
+ const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec, fromHere)])));
1524
+ const entries = sync.map(({ key, platform }) => ({
1525
+ key,
1526
+ platform
1527
+ }));
1263
1528
  let made;
1264
1529
  try {
1265
- made = await api(who, "PUT", await onBoard(who, "/watchers"), { body: {
1530
+ made = await syncApi(who, "PUT", await onBoard(who, "/watchers"), { body: {
1266
1531
  ...where,
1267
1532
  watch: filters,
1268
- tag: await tagOf(specs)
1533
+ tag: await tagOf(specs, entries),
1534
+ ...entries.length ? { sync: entries } : {}
1269
1535
  } });
1270
1536
  } 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;
1537
+ throw needsProject(error);
1276
1538
  }
1277
1539
  return {
1278
1540
  owner: made.owner,
1279
1541
  ...whereOf(made),
1280
1542
  watch: specs,
1281
- sync: [],
1543
+ sync: syncOf(made),
1282
1544
  hash: made.hash
1283
1545
  };
1284
1546
  }
1285
1547
  /** 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) {
1548
+ async function matchOf(who, match, filters) {
1287
1549
  const found = await messageById(who, match.event.messageId).catch((error) => {
1288
1550
  if (error instanceof HttpError && error.status === 404) return null;
1289
1551
  throw error;
1290
1552
  });
1291
1553
  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);
1554
+ if (!found || !channel) return null;
1555
+ 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
1556
  if (!event?.message) return null;
1557
+ const handed = match.watcher === "@sync" && event.type === "labels.changed" ? {
1558
+ ...event,
1559
+ before: {
1560
+ ...event.message,
1561
+ labels: labelsBefore(event.message.labels, match.event.labels)
1562
+ }
1563
+ } : event;
1294
1564
  return {
1295
1565
  id: match.id,
1296
1566
  watcher: match.watcher,
1297
1567
  thread: event.message.thread,
1298
1568
  lease: match.lease,
1299
1569
  attempt: match.attempt,
1300
- event
1570
+ event: handed
1301
1571
  };
1302
1572
  }
1303
- async function pullAs(who, query, signal) {
1304
- const { matches } = await api(who, "GET", await onBoard(who, "/watchers/matches"), {
1573
+ /** A thread bound to a target, as the event that has the sync owning its key backfill a channel: about the thread's root. */
1574
+ async function syncedOf(who, match, root, channel) {
1575
+ const { binding } = match.event;
1576
+ if (!binding) return null;
1577
+ const message = await view(who, root, channel);
1578
+ return boardEvent(who, match.event, match.id, "thread.synced", {
1579
+ thread: message.thread,
1580
+ target: binding.target,
1581
+ cause: binding.cause,
1582
+ kind: binding.targetKind,
1583
+ by: authorOf(match.event.actor)
1584
+ }, message);
1585
+ }
1586
+ async function pullAs(who, query, signal, specs = {}) {
1587
+ const { matches } = await watchersApi(who, "GET", await onBoard(who, "/watchers/matches"), {
1305
1588
  query: {
1306
1589
  limit: query.limit?.toString(),
1307
1590
  wait: query.wait?.toString()
1308
1591
  },
1309
1592
  ...signal ? { signal } : {}
1310
1593
  });
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, {
1594
+ const sources = new Map(Object.entries(specs).map(([id, spec]) => [id, compileWatcher(id, spec).filters.from]));
1595
+ const handed = await Promise.all(matches.map((match) => {
1596
+ const from = sources.get(match.watcher);
1597
+ return matchOf(who, match, from === void 0 ? {} : { from });
1598
+ }));
1599
+ await Promise.all(matches.map((match, i) => handed[i] ? null : ackAs(who, match.id, {
1314
1600
  lease: match.lease,
1315
1601
  skip: true
1316
1602
  }).catch(() => {})));
1317
- return shown.filter((match) => match !== null);
1603
+ return handed.filter((match) => match !== null);
1318
1604
  }
1319
1605
  async function ackAs(who, id, body) {
1320
- await api(who, "POST", await onBoard(who, `/watchers/matches/${encodeURIComponent(id)}/ack`), { body: {
1606
+ await watchersApi(who, "POST", await onBoard(who, `/watchers/matches/${encodeURIComponent(id)}/ack`), { body: {
1321
1607
  lease: body.lease,
1322
1608
  ...body.error !== void 0 ? { error: body.error } : {},
1323
1609
  ...body.skip ? { skip: true } : {}
@@ -1337,19 +1623,170 @@ function createVercel(options, environment) {
1337
1623
  const runner = registrant({
1338
1624
  remote: "Vercel's API",
1339
1625
  registry: {
1340
- register: (where) => registerAs(deployment, where, tails),
1341
- matches: ({ signal, ...query }) => pullAs(deployment, query, signal),
1626
+ register: (where) => registerAs(deployment, where, tails, bound().sync, true).catch((error) => {
1627
+ if (error instanceof HttpError && error.code === "watchers_need_project") {
1628
+ refused = true;
1629
+ runner.close();
1630
+ runHere();
1631
+ }
1632
+ throw error;
1633
+ }),
1634
+ matches: ({ signal, ...query }) => pullAs(deployment, query, signal, tails),
1342
1635
  ack: (id, body) => ackAs(deployment, id, body)
1343
1636
  },
1344
- wakeAt: async (here) => wakePath(here) ?? { url: here },
1637
+ wakeAt: async (here) => wakePath(here) ?? { url: null },
1345
1638
  binding: bound,
1346
- hash: () => tagOf(tails),
1347
- hasWork: () => Object.keys(tails).length > 0,
1639
+ hash: () => tagOf(tails, bound().sync),
1640
+ hasWork: () => Object.keys(tails).length > 0 || bound().sync.length > 0,
1348
1641
  rethrow: (error) => {
1349
1642
  throw error;
1350
1643
  },
1351
1644
  registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
1352
1645
  });
1646
+ let deployed = null;
1647
+ /** Whether Vercel's API refused to register this board's watchers: its credentials aren't a deployment's own. */
1648
+ let refused = false;
1649
+ /**
1650
+ * Whether this board's own credentials are a deployment's own: a project's, and no board token. A
1651
+ * board token you set says so; one in a `fetch` passed in says so when the API refuses it.
1652
+ */
1653
+ const isDeployment = async () => {
1654
+ if (refused || !options.fetch && environment?.boardToken()) return false;
1655
+ return (deployed ??= self(deployment).then((found) => found.actor.principal.type === "project")).catch((error) => {
1656
+ deployed = null;
1657
+ throw error;
1658
+ });
1659
+ };
1660
+ let here = null;
1661
+ let deployedElse = false;
1662
+ /** Anyone else's watchers run in this process, as tails: nothing wakes a person. */
1663
+ function runHere() {
1664
+ if (here || deployedElse) return;
1665
+ if (deployedOnVercel()) {
1666
+ deployedElse = true;
1667
+ console.error("[board] watchers on a deployment need its own OIDC token: with a board token or another Vercel token, none run here");
1668
+ return;
1669
+ }
1670
+ const { sync, run } = bound();
1671
+ 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");
1672
+ const watchers = {};
1673
+ for (const [id, spec] of Object.entries(tails)) try {
1674
+ watchers[id] = checkedTail(id, spec, true);
1675
+ } catch (error) {
1676
+ console.error(`[board] watcher ${id} doesn't run:`, error.message);
1677
+ }
1678
+ here = tailWatchers({
1679
+ watchers,
1680
+ events: (query, signal) => eventsAs(deployment, query, signal),
1681
+ actorOf: (id) => actorOf({
1682
+ profile: { name: id },
1683
+ session: null
1684
+ }),
1685
+ run
1686
+ });
1687
+ here.start();
1688
+ }
1689
+ let failedAt = 0;
1690
+ /** On first use, a deployment registers its watchers with the API, and anyone else runs them here. */
1691
+ async function start() {
1692
+ if (here || Object.keys(tails).length === 0 && bound().sync.length === 0 || Date.now() - failedAt < WHO_AGAIN_MS) return;
1693
+ let project;
1694
+ try {
1695
+ project = await isDeployment();
1696
+ } catch (error) {
1697
+ failedAt = Date.now();
1698
+ console.error("[board] couldn't tell whether this board runs as a deployment:", error instanceof Error ? error.message : String(error));
1699
+ return;
1700
+ }
1701
+ if (project) await runner.start();
1702
+ else runHere();
1703
+ }
1704
+ /** The routes to register and wake: only a deployment's board is woken or registers. */
1705
+ const routes = runner.routes.map((route) => ({
1706
+ ...route,
1707
+ async handle(request, context) {
1708
+ if (context.caller || await isDeployment().catch(() => true)) return route.handle(request, context);
1709
+ waitUntil(start());
1710
+ if (route.path === "/wake") return json({ ran: 0 });
1711
+ throw notADeployment();
1712
+ }
1713
+ }));
1714
+ const platformUser = ({ id, handle, name, avatar, isBot }) => ({
1715
+ id,
1716
+ handle,
1717
+ name,
1718
+ avatar,
1719
+ isBot
1720
+ });
1721
+ /** An import as the API takes it: a channel by its ID, and a reply's `after` as its sequence in the thread. */
1722
+ async function importBody(who, body) {
1723
+ if (body.op === "seen") return {
1724
+ op: "seen",
1725
+ operationId: operationId(),
1726
+ author: platformUser(body.author)
1727
+ };
1728
+ const base = {
1729
+ op: body.op,
1730
+ operationId: operationId(),
1731
+ author: platformUser(body.author),
1732
+ ...body.from !== void 0 ? { from: body.from } : {}
1733
+ };
1734
+ if (body.op === "post") {
1735
+ if (body.attachments?.length) throw notSupported("files on imports");
1736
+ let after;
1737
+ if (body.after !== void 0) {
1738
+ const at = locate(body.after);
1739
+ const re = body.re === void 0 ? null : locate(body.re);
1740
+ if (!at || !re || at.threadId !== re.threadId) throw badRequest(`after: ${body.after} isn't in ${body.re ?? "the thread"}'s thread`, "invalid_after");
1741
+ after = at.sequence;
1742
+ }
1743
+ return {
1744
+ ...base,
1745
+ origin: body.origin === null ? null : originOf(body.origin),
1746
+ ...body.source ? { source: body.source } : {},
1747
+ ...body.channel !== void 0 ? { channelId: (await channelToPost(who, body.channel)).id } : {},
1748
+ ...body.re !== void 0 ? { re: body.re } : {},
1749
+ text: body.text,
1750
+ ...body.labels && Object.keys(body.labels).length ? { labels: body.labels } : {},
1751
+ ...body.noSync ? { noSync: true } : {},
1752
+ ...body.links?.length ? { links: body.links } : {},
1753
+ ...body.id !== void 0 ? { id: body.id } : {},
1754
+ ...after !== void 0 ? { after } : {}
1755
+ };
1756
+ }
1757
+ const changed = {
1758
+ ...base,
1759
+ ...body.origin !== void 0 ? { origin: body.origin } : {},
1760
+ ...body.message !== void 0 ? { message: body.message } : {}
1761
+ };
1762
+ if (body.op === "edit") return {
1763
+ ...changed,
1764
+ text: body.text,
1765
+ ...body.source ? { source: body.source } : {},
1766
+ ...body.revision !== void 0 ? { revision: body.revision } : {}
1767
+ };
1768
+ if (body.op === "delete") return {
1769
+ ...changed,
1770
+ ...body.revision !== void 0 ? { revision: body.revision } : {}
1771
+ };
1772
+ if (body.op === "react") return {
1773
+ ...changed,
1774
+ emoji: body.emoji,
1775
+ ...body.remove ? { remove: true } : {}
1776
+ };
1777
+ if (body.op === "labels") return {
1778
+ ...changed,
1779
+ ...body.set ? { set: body.set } : {},
1780
+ ...body.unset ? { unset: body.unset } : {},
1781
+ ...body.if && Object.keys(body.if).length ? { if: body.if } : {}
1782
+ };
1783
+ return {
1784
+ ...changed,
1785
+ links: body.links
1786
+ };
1787
+ }
1788
+ /** A sync key's inbox, under the board. */
1789
+ const inboxPath = (who, key, rest = "") => onBoard(who, `/sync/inbox/${encodeURIComponent(key)}${rest}`);
1353
1790
  const methods = {
1354
1791
  ...Object.fromEntries(METHODS.map((method) => [method, async () => {
1355
1792
  throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
@@ -1368,7 +1805,10 @@ function createVercel(options, environment) {
1368
1805
  audience: origin,
1369
1806
  team_id: id,
1370
1807
  project_id: null,
1371
- sync: [],
1808
+ sync: (binding?.sync ?? []).map(({ key, platform }) => ({
1809
+ key,
1810
+ platform
1811
+ })),
1372
1812
  wake_by_path: true
1373
1813
  };
1374
1814
  },
@@ -1469,7 +1909,7 @@ function createVercel(options, environment) {
1469
1909
  const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
1470
1910
  return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
1471
1911
  };
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") {
1912
+ if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0) {
1473
1913
  const { messages, feeds, newest } = await collect(who, query, signal);
1474
1914
  const latest = /* @__PURE__ */ new Map();
1475
1915
  for (const { message, thread, channel } of messages) latest.set(thread.id, {
@@ -1538,6 +1978,7 @@ function createVercel(options, environment) {
1538
1978
  },
1539
1979
  async upload(caller, { data, name, type }) {
1540
1980
  const who = whoOf(caller);
1981
+ if ("self" in caller && caller.self === "sync") throw new HttpError(501, "no_files", "Vercel's board takes no files from sync yet");
1541
1982
  if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
1542
1983
  if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
1543
1984
  const bytes = new Uint8Array(data);
@@ -1608,7 +2049,8 @@ function createVercel(options, environment) {
1608
2049
  text: input.text,
1609
2050
  ...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
1610
2051
  ...clientId ? { clientId } : {},
1611
- ...input.attachments?.length ? { attachments: input.attachments } : {}
2052
+ ...input.attachments?.length ? { attachments: input.attachments } : {},
2053
+ ...input.noSync ? { noSync: true } : {}
1612
2054
  },
1613
2055
  signal
1614
2056
  });
@@ -1627,7 +2069,8 @@ function createVercel(options, environment) {
1627
2069
  ...to.sequence > 1 ? { replyTo: to.sequence } : {},
1628
2070
  ...clientId ? { clientId } : {},
1629
2071
  ...input.attachments?.length ? { attachments: input.attachments } : {},
1630
- ...after ? { after: after.sequence } : {}
2072
+ ...after ? { after: after.sequence } : {},
2073
+ ...input.noSync ? { noSync: true } : {}
1631
2074
  },
1632
2075
  signal
1633
2076
  }).catch((error) => {
@@ -1808,6 +2251,7 @@ function createVercel(options, environment) {
1808
2251
  ...target,
1809
2252
  text: input.text,
1810
2253
  ...labels ? { labels } : {},
2254
+ ...input.noSync ? { noSync: true } : {},
1811
2255
  firstAt,
1812
2256
  ...input.every !== void 0 ? { every: ms(input.every) } : {},
1813
2257
  ...until !== void 0 ? { until } : {},
@@ -1833,14 +2277,9 @@ function createVercel(options, environment) {
1833
2277
  if (!channel) return { schedules: [] };
1834
2278
  filter.channelId = channel.id;
1835
2279
  }
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));
2280
+ if (query.by?.startsWith("vercel:")) filter.createdBy = query.by;
2281
+ const by = await byOf(who, query.by);
2282
+ const created = (actor) => by === void 0 || by(actor);
1844
2283
  const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
1845
2284
  return { schedules: await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule))) };
1846
2285
  },
@@ -1855,59 +2294,166 @@ function createVercel(options, environment) {
1855
2294
  canceled
1856
2295
  };
1857
2296
  },
1858
- async events(caller, query, signal) {
2297
+ events: (caller, query, signal) => eventsAs(whoOf(caller), query, signal),
2298
+ async typing(caller, { id, status }, signal) {
2299
+ if (!binding || binding.sync.length === 0) return { targets: [] };
2300
+ const { message, replies } = await methods.message(caller, { id }, signal);
2301
+ return { targets: await binding.typing([message, ...replies], status) };
2302
+ },
2303
+ async readSource(_caller, { key, target, limit, after }) {
2304
+ 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");
2305
+ return binding.readSource(key, target, limit ?? 50, after ?? null);
2306
+ },
2307
+ async joinSource(_caller, { key, target }) {
2308
+ 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");
2309
+ return binding.joinSource(key, target);
2310
+ },
2311
+ async syncImport(caller, body, signal) {
1859
2312
  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);
2313
+ return { message: (await syncApi(who, "POST", await onBoard(who, "/sync/imports"), {
2314
+ body: await importBody(who, body),
2315
+ signal
2316
+ }).catch((error) => {
2317
+ if (error instanceof HttpError && error.code === "newer_message" && body.op === "post") throw new HttpError(409, "newer_message", `a message came after ${body.after}`);
2318
+ throw error;
2319
+ })).message };
2320
+ },
2321
+ async syncReceipt(caller, body, signal) {
2322
+ const who = whoOf(caller);
2323
+ return syncApi(who, "POST", await onBoard(who, "/sync/receipts"), {
2324
+ body,
2325
+ signal
2326
+ });
2327
+ },
2328
+ async syncFind(caller, query, signal) {
2329
+ const who = whoOf(caller);
2330
+ const { thread, message } = await syncApi(who, "GET", await onBoard(who, "/sync/find"), {
2331
+ query,
2332
+ signal
2333
+ });
2334
+ return {
2335
+ thread,
2336
+ message
2337
+ };
2338
+ },
2339
+ async syncThread(caller, { thread }, signal) {
2340
+ const who = whoOf(caller);
2341
+ const found = await syncApi(who, "GET", await onBoard(who, `/sync/threads/${encodeURIComponent(thread)}`), { signal });
2342
+ return {
2343
+ ...found,
2344
+ channel: (await channelById(who, found.channel)).name
2345
+ };
2346
+ },
2347
+ async syncCopies(caller, { message }, signal) {
2348
+ const who = whoOf(caller);
2349
+ return syncApi(who, "GET", await onBoard(who, "/sync/copies"), {
2350
+ query: { message },
2351
+ signal
2352
+ });
2353
+ },
2354
+ async synced(caller, { id }, signal) {
2355
+ const who = whoOf(caller);
2356
+ if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
2357
+ const { targets } = await syncApi(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}/synced`), { signal });
2358
+ return { targets: await Promise.all(targets.map(async (target) => ({
2359
+ ...target,
2360
+ url: binding && target.thread !== null && target.message !== null ? await binding.linkOf(target.key, target.thread, target.message) : null
2361
+ }))) };
2362
+ },
2363
+ async linked(caller, { url }, signal) {
2364
+ const who = whoOf(caller);
2365
+ const missing = () => notFound("no message on this board for that link", "message_not_found");
2366
+ 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])) {
2367
+ const found = await syncApi(who, "GET", await onBoard(who, "/sync/linked"), {
2368
+ query: {
2369
+ thread: `${key}:${thread}`,
2370
+ ...message !== null ? { message } : {}
2371
+ },
2372
+ signal
2373
+ }).catch((error) => {
2374
+ if (error instanceof HttpError && error.status === 404) return null;
2375
+ throw error;
2376
+ });
2377
+ if (found) return methods.message(caller, { id: found.message }, signal).catch((error) => {
2378
+ if (error instanceof HttpError && (error.status === 403 || error.status === 404)) throw missing();
2379
+ throw error;
2380
+ });
1883
2381
  }
2382
+ throw missing();
1884
2383
  },
1885
- async typing() {
1886
- return { targets: [] };
2384
+ async inboxPush(caller, { key, events }, signal) {
2385
+ const who = whoOf(caller);
2386
+ await syncApi(who, "POST", await inboxPath(who, key), {
2387
+ body: { events: events.map(({ id, event, raw }) => ({
2388
+ id,
2389
+ thread: event.thread,
2390
+ event,
2391
+ ...raw !== void 0 ? { raw } : {}
2392
+ })) },
2393
+ signal
2394
+ });
2395
+ return { ok: true };
1887
2396
  },
1888
- async readSource(_caller, { key }) {
1889
- throw notFound(`this board doesn't run sync entry ${key}`, "not_synced_here");
2397
+ async inboxNext(caller, { key, limit }, signal) {
2398
+ const who = whoOf(caller);
2399
+ const { items } = await syncApi(who, "GET", await inboxPath(who, key, "/next"), {
2400
+ query: { limit: limit?.toString() },
2401
+ signal
2402
+ });
2403
+ return { items: items.map(({ raw, ...item }) => ({
2404
+ ...item,
2405
+ key,
2406
+ raw: raw ?? null
2407
+ })) };
2408
+ },
2409
+ async inboxAck(caller, { key, id, lease, error }, signal) {
2410
+ const who = whoOf(caller);
2411
+ await syncApi(who, "POST", await inboxPath(who, key, `/${encodeURIComponent(id)}/ack`), {
2412
+ body: {
2413
+ lease,
2414
+ ...error !== void 0 ? { error } : {}
2415
+ },
2416
+ signal
2417
+ });
2418
+ return { ok: true };
2419
+ },
2420
+ async inbox(caller, { key, channel, limit }, signal) {
2421
+ const who = whoOf(caller);
2422
+ const wanted = Math.min(limit ?? 50, INBOX_LIST_MAX);
2423
+ const { events } = await syncApi(who, "GET", await inboxPath(who, key), {
2424
+ query: { limit: String(channel === void 0 ? wanted : INBOX_LIST_MAX) },
2425
+ signal
2426
+ });
2427
+ const entries = events.flatMap(({ id, createdAt, event, raw }) => event ? [{
2428
+ id,
2429
+ channel: typeof event.channel === "string" ? event.channel : "",
2430
+ createdAt,
2431
+ sync: key,
2432
+ event,
2433
+ raw: raw ?? null
2434
+ }] : []);
2435
+ return { events: (channel === void 0 ? entries : entries.filter((entry) => entry.channel === channel)).slice(0, wanted) };
1890
2436
  },
1891
2437
  async watchers(caller) {
1892
2438
  const who = whoOf(caller);
1893
- const { watchers } = await api(who, "GET", await onBoard(who, "/watchers"));
2439
+ const { watchers } = await watchersApi(who, "GET", await onBoard(who, "/watchers"));
1894
2440
  return { watchers: await Promise.all(watchers.map(async (found) => ({
1895
2441
  owner: found.owner,
1896
2442
  ...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: [],
2443
+ watch: Object.fromEntries(await Promise.all(Object.entries(found.watch).map(async ([id, spec]) => [id, { tail: await tailOf(who, spec) }]))),
2444
+ sync: syncOf(found),
1902
2445
  hash: found.hash
1903
2446
  }))) };
1904
2447
  },
1905
2448
  async register(caller, body) {
1906
- if ((body.sync?.length ?? 0) > 0) throw notSupported("sync");
2449
+ if (typeof body.url === "string") throw new HttpError(400, "invalid_request", "Vercel's API wakes a deployment only by its path.", {
2450
+ hint: "Register a path, or no url to pull its matches.",
2451
+ origin: "handle"
2452
+ });
1907
2453
  return registerAs(whoOf(caller), typeof body.path === "string" ? {
1908
2454
  path: body.path,
1909
2455
  ...body.branch ? { branch: body.branch } : {}
1910
- } : { url: body.url ?? null }, body.watch);
2456
+ } : { url: body.url ?? null }, body.watch, body.sync ?? [], false);
1911
2457
  },
1912
2458
  async matches(caller, query, signal) {
1913
2459
  return { matches: await pullAs(whoOf(caller), query, signal) };
@@ -1920,27 +2466,31 @@ function createVercel(options, environment) {
1920
2466
  return {
1921
2467
  ...Object.fromEntries(Object.entries(methods).map(([name, method]) => [name, (caller, ...args) => {
1922
2468
  if ("identity" in caller) throw servesNone();
1923
- if (binding) runner.start();
2469
+ if (binding) waitUntil(start());
1924
2470
  return method(caller, ...args);
1925
2471
  }])),
1926
- routes: runner.routes,
2472
+ routes,
1927
2473
  keeps: false,
1928
2474
  sendsSchedulesHere: false,
1929
2475
  bind(next) {
1930
2476
  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
2477
  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
2478
  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
- }]] : []));
2479
+ tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, { tail: subscription.tail }]] : []));
1938
2480
  binding = next;
1939
2481
  },
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
2482
+ /** Registers this board's watchers with Vercel's API now, as `POST /watchers` does: only a deployment's. */
2483
+ async registerWatchers() {
2484
+ if (await isDeployment()) return runner.registerNow();
2485
+ waitUntil(start());
2486
+ throw notADeployment();
2487
+ },
2488
+ /** Stops pulling, for a board that pulls on its own, and the tails of one that runs them here. */
2489
+ close() {
2490
+ runner.close();
2491
+ here?.close();
2492
+ here = null;
2493
+ }
1944
2494
  };
1945
2495
  }
1946
2496
  //#endregion
@@ -2174,6 +2724,13 @@ const LOGOS = {
2174
2724
  //#region src/server/avatars.ts
2175
2725
  /** Each known agent's mark on its color. */
2176
2726
  const STYLES = {
2727
+ fx: {
2728
+ background: "#000000",
2729
+ mark: {
2730
+ 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",
2731
+ transform: "scale(0.71111) translate(34 33.95) scale(0.7186) translate(-166.241 0)"
2732
+ }
2733
+ },
2177
2734
  claude: {
2178
2735
  background: "#D97757",
2179
2736
  mark: { path: LOGOS.claude }
@@ -2197,7 +2754,7 @@ function avatarSvg(name) {
2197
2754
  background: "#666666",
2198
2755
  mark: { glyph: name.slice(0, 1).toUpperCase() }
2199
2756
  };
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>`;
2757
+ 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
2758
  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
2759
  }
2203
2760
  //#endregion
@@ -3101,6 +3658,7 @@ async function createServe(context) {
3101
3658
  const made = CREATED.has(target.name) || target.name === "createChannel" && output.created;
3102
3659
  return json(output, made ? 201 : 200);
3103
3660
  } catch (error) {
3661
+ if (request.signal.aborted && error === request.signal.reason) return new Response(null, { status: 499 });
3104
3662
  return toErrorResponse(error);
3105
3663
  }
3106
3664
  }
@@ -3274,8 +3832,7 @@ function createBoard(options, runtime) {
3274
3832
  };
3275
3833
  const subscriptions = Object.fromEntries(Object.entries(watch).map(([id, watcher]) => [id, {
3276
3834
  kind: "tail",
3277
- tail: watcher.tail,
3278
- when: watcher.when ?? "matches"
3835
+ tail: watcher.tail
3279
3836
  }]));
3280
3837
  if (Object.keys(entries).length > 0) subscriptions[SYNC] = { kind: "sync" };
3281
3838
  /** This board's sync entries, as its sync and discovery see them. */