@vercel/board 0.35.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 (80) 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-9hCT654s.mjs → chat-provider-C0WUS3-G.mjs} +2 -2
  9. package/dist/{chat-provider-DmZCmBkb.d.mts → chat-provider-DFYEReZL.d.mts} +2 -2
  10. package/dist/cli-commands.d.mts +1 -1
  11. package/dist/cli-commands.mjs +1 -1
  12. package/dist/cli-embedded.d.mts +18 -2
  13. package/dist/cli-embedded.mjs +22 -4
  14. package/dist/cli.mjs +50 -676
  15. package/dist/{commands-CENWob9m.mjs → commands-D2pFCMSh.mjs} +19 -6
  16. package/dist/{commands-BorACIFS.d.mts → commands-DGID-4Z2.d.mts} +4 -2
  17. package/dist/{conformance-CKrwglzA.mjs → conformance-rCrc_mwi.mjs} +2 -3
  18. package/dist/conformance.d.mts +1 -1
  19. package/dist/conformance.mjs +1 -1
  20. package/dist/digest-CLGw7653.mjs +4 -0
  21. package/dist/{engine-wN7quvbU.mjs → engine-COa73McY.mjs} +17 -13
  22. package/dist/{events-IQg0k281.mjs → events-v8f7pF9f.mjs} +22 -8
  23. package/dist/exports-Bb0m03fT.d.mts +4 -0
  24. package/dist/{exports-GIRJm2Ja.mjs → exports-DTezg4xR.mjs} +776 -173
  25. package/dist/{external-CYe424fO.mjs → external-BA2aCC_3.mjs} +1 -1
  26. package/dist/{index-LREsSZb2.d.mts → index-B1TZrMMu.d.mts} +2 -2
  27. package/dist/index.d.mts +5 -5
  28. package/dist/index.mjs +3 -3
  29. package/dist/index.node.d.mts +5 -5
  30. package/dist/index.node.mjs +2 -2
  31. package/dist/inspect/app.js +35 -35
  32. package/dist/inspect/engine.js +5 -5
  33. package/dist/inspect-B8c0Wh5Z.mjs +2 -0
  34. package/dist/inspect-CoFk2Xj7.mjs +643 -0
  35. package/dist/{local-yKwdgukb.mjs → local-Cm7a7_Q0.mjs} +14 -69
  36. package/dist/{main-DjokcEAL.mjs → main-DoZ8IFPb.mjs} +17 -13
  37. package/dist/{memory-7RRnLa4X.mjs → memory-DqwXlyK4.mjs} +2 -2
  38. package/dist/{middleware-BxgizazV.mjs → middleware-k_XKQ6f7.mjs} +9 -1
  39. package/dist/page-BAQpb-s-.mjs +2 -0
  40. package/dist/page-LysMGAl3.mjs +30 -0
  41. package/dist/{provider-DEOfc4Ls.d.mts → provider-7pOnK8Jw.d.mts} +5 -3
  42. package/dist/{routes-BpKdMvgX.d.mts → routes-BtsZzal-.d.mts} +0 -17
  43. package/dist/{serve-CJ8hauK2.mjs → serve-2U_JPJtS.mjs} +2 -2
  44. package/dist/{server-CtaTtyhw.mjs → server-Drul_uwj.mjs} +18 -10
  45. package/dist/{sql-BQzKUqQt.mjs → sql-aetuEBZC.mjs} +1 -1
  46. package/dist/{sqlite-DCtZFEVm.mjs → sqlite-DvsB8ENQ.mjs} +2 -2
  47. package/dist/{sqlite-db-qLTs52Ny.mjs → sqlite-db-BPwRoDI7.mjs} +1 -1
  48. package/dist/sync-chat-sdk.d.mts +2 -2
  49. package/dist/sync-chat-sdk.mjs +2 -2
  50. package/dist/sync-github.d.mts +2 -2
  51. package/dist/sync-github.mjs +2 -2
  52. package/dist/sync-linear.d.mts +3 -3
  53. package/dist/sync-linear.mjs +2 -2
  54. package/dist/sync-slack.d.mts +3 -3
  55. package/dist/sync-slack.mjs +3 -3
  56. package/dist/sync.d.mts +2 -2
  57. package/dist/sync.mjs +2 -2
  58. package/dist/{targets-n2i2ZOWI.mjs → targets-B0D4tJDY.mjs} +64 -19
  59. package/docs/01-board/01-mounting.md +11 -8
  60. package/docs/01-board/03-identity.md +3 -2
  61. package/docs/01-board/06-watchers.md +71 -40
  62. package/docs/01-board/09-access.md +1 -1
  63. package/docs/01-quickstart.md +1 -1
  64. package/docs/02-sync/01-overview.md +7 -7
  65. package/docs/02-sync/02-functions.md +5 -8
  66. package/docs/02-sync/03-slack.md +0 -8
  67. package/docs/02-sync/04-github.md +0 -8
  68. package/docs/02-sync/07-linear.md +0 -6
  69. package/docs/03-guides/01-coding-agents.md +1 -0
  70. package/docs/03-guides/02-inspector.md +3 -2
  71. package/docs/03-guides/03-ci.md +1 -1
  72. package/docs/03-guides/04-triage.md +8 -13
  73. package/docs/04-reference/01-cli.md +32 -8
  74. package/docs/04-reference/02-board.md +5 -0
  75. package/docs/04-reference/03-http.md +1 -1
  76. package/docs/04-reference/05-conformance.md +1 -1
  77. package/docs/index.md +3 -10
  78. package/package.json +2 -1
  79. package/dist/attempts-HXcskN1w.mjs +0 -10
  80. 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-n2i2ZOWI.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,22 +1067,58 @@ 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
861
1074
  });
862
1075
  }
863
1076
  }
864
- messages.sort((a, b) => a.message.createdAt - b.message.createdAt || a.thread.id.localeCompare(b.thread.id) || a.message.sequence - b.message.sequence);
1077
+ messages.sort(byTime);
865
1078
  return {
866
1079
  messages,
867
1080
  feeds,
868
1081
  newest
869
1082
  };
870
1083
  }
1084
+ /** A thread's messages in order; across threads, by time, as a person reads a channel. */
1085
+ const byTime = (a, b) => a.message.createdAt - b.message.createdAt || a.message.threadId.localeCompare(b.message.threadId) || a.message.sequence - b.message.sequence;
1086
+ /**
1087
+ * The latest `limit` in `listed`, unfiltered: each channel's latest page from the API's message
1088
+ * list, all at once, never a thread at a time. The list goes back one page, so a full page cuts the
1089
+ * answer off at its oldest message: every message newer than the oldest it answers with is in it,
1090
+ * even when that's fewer than `limit`. Each page's cursor is its channel's feed then, which the
1091
+ * read's cursor goes on from.
1092
+ */
1093
+ async function latest(who, listed, limit, signal) {
1094
+ const path = await onBoard(who, "/messages");
1095
+ const asked = Math.min(limit, PAGE_MAX);
1096
+ const pages = await Promise.all(listed.map(async (channel) => ({
1097
+ channel,
1098
+ ...await api(who, "GET", path, {
1099
+ query: {
1100
+ channelId: channel.id,
1101
+ limit: String(asked)
1102
+ },
1103
+ signal
1104
+ })
1105
+ })));
1106
+ const full = pages.filter((page) => page.messages.length === asked);
1107
+ const cutoff = Math.max(-Infinity, ...full.map((page) => Math.min(...page.messages.map((message) => message.createdAt))));
1108
+ return {
1109
+ messages: pages.flatMap(({ channel, messages }) => messages.map((message) => ({
1110
+ message,
1111
+ channel
1112
+ }))).filter(({ message }) => message.createdAt >= cutoff).sort(byTime).slice(-limit),
1113
+ feeds: Object.fromEntries(pages.map((page) => [page.channel.id, {
1114
+ at: page.cursor,
1115
+ skip: 0
1116
+ }])),
1117
+ newest: Math.max(0, ...pages.flatMap((page) => page.messages.map((message) => message.createdAt)))
1118
+ };
1119
+ }
871
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. */
872
- 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)) {
873
1122
  if (!change.messageId || !change.type.startsWith("message.")) return null;
874
1123
  let found = given ?? await messageById(who, change.messageId).catch((error) => {
875
1124
  if (error instanceof HttpError && error.status === 404) return null;
@@ -879,9 +1128,10 @@ function createVercel(options, environment) {
879
1128
  ...found,
880
1129
  thread: found.message.sequence === 1 ? labeledBy(found.thread, found.message) : await threads(found.thread.id)
881
1130
  };
882
- if (!found || !matches(filters, found.message, found.thread, me)) return null;
1131
+ if (!found || !matches(filters, found.message, found.thread, authors)) return null;
883
1132
  const message = await view(who, found.message, channel);
884
1133
  const by = authorOf(change.actor);
1134
+ const from = change.from ?? null;
885
1135
  const base = {
886
1136
  id: message.id,
887
1137
  thread: message.thread
@@ -898,13 +1148,13 @@ function createVercel(options, environment) {
898
1148
  replyTo: message.replyTo,
899
1149
  thread: message.thread,
900
1150
  labels: message.labels,
901
- noSync: false,
1151
+ noSync: message.noSync,
902
1152
  mentions: [],
903
1153
  by,
904
- origin: null,
905
- from: null,
1154
+ origin: message.origin,
1155
+ from: message.from,
906
1156
  attachments: message.attachments,
907
- links: []
1157
+ links: message.links
908
1158
  };
909
1159
  break;
910
1160
  case "message.edited":
@@ -914,7 +1164,7 @@ function createVercel(options, environment) {
914
1164
  text: message.text,
915
1165
  mentions: [],
916
1166
  by,
917
- from: null
1167
+ from
918
1168
  };
919
1169
  break;
920
1170
  case "message.deleted":
@@ -922,7 +1172,7 @@ function createVercel(options, environment) {
922
1172
  payload = {
923
1173
  ...base,
924
1174
  by,
925
- from: null
1175
+ from
926
1176
  };
927
1177
  break;
928
1178
  case "message.reaction_added":
@@ -932,7 +1182,7 @@ function createVercel(options, environment) {
932
1182
  ...base,
933
1183
  emoji: change.emoji,
934
1184
  by,
935
- from: null
1185
+ from
936
1186
  };
937
1187
  break;
938
1188
  case "message.labeled": {
@@ -948,15 +1198,16 @@ function createVercel(options, environment) {
948
1198
  }
949
1199
  default: return null;
950
1200
  }
951
- return {
952
- cursor,
953
- type,
954
- createdAt: iso(change.createdAt),
955
- payload,
956
- message,
957
- actor: await nameOf(who, change.actor)
958
- };
959
- }
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
+ });
960
1211
  /**
961
1212
  * One read of every channel's feed from `position`: its events, merged by time, each with the
962
1213
  * position right after it, and the position after them all.
@@ -984,7 +1235,7 @@ function createVercel(options, environment) {
984
1235
  events
985
1236
  };
986
1237
  }));
987
- const mine = await actorOf(who);
1238
+ const by = await byOf(who, filters.by);
988
1239
  const threads = threadReader(who, signal);
989
1240
  const running = { ...position.feeds };
990
1241
  const merged = pages.flatMap((page) => page.events.map((event) => ({
@@ -1000,7 +1251,7 @@ function createVercel(options, environment) {
1000
1251
  const event = await eventOf(who, change, page.channel.name, cursorOf({
1001
1252
  t: change.createdAt,
1002
1253
  feeds: { ...running }
1003
- }), filters, mine, void 0, threads);
1254
+ }), filters, by, void 0, threads);
1004
1255
  if (event) events.push(event);
1005
1256
  }
1006
1257
  const after = { ...position.feeds };
@@ -1071,8 +1322,8 @@ function createVercel(options, environment) {
1071
1322
  const limit = query.limit ?? 50;
1072
1323
  const thread = threadReader(who, signal);
1073
1324
  const narrowed = filtered(query);
1074
- const me = narrowed ? await actorOf(who) : null;
1075
- 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);
1076
1327
  const kept = [];
1077
1328
  if (query.after === void 0) {
1078
1329
  const page = await api(who, "GET", path, {
@@ -1111,7 +1362,7 @@ function createVercel(options, environment) {
1111
1362
  async function channelEvents(who, channel, query, signal) {
1112
1363
  const path = await onBoard(who, "/changes");
1113
1364
  const thread = threadReader(who, signal);
1114
- const me = await actorOf(who);
1365
+ const by = await byOf(who, query.by);
1115
1366
  const until = Date.now() + (query.wait ?? 0) * 1e3;
1116
1367
  let cursor = query.after;
1117
1368
  for (;;) {
@@ -1134,7 +1385,7 @@ function createVercel(options, environment) {
1134
1385
  thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
1135
1386
  } : null;
1136
1387
  if (!found) continue;
1137
- 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);
1138
1389
  if (event) events.push(event);
1139
1390
  }
1140
1391
  if (events.length > 0 || Date.now() >= until || signal.aborted) return {
@@ -1143,6 +1394,33 @@ function createVercel(options, environment) {
1143
1394
  };
1144
1395
  }
1145
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
+ }
1146
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. */
1147
1425
  async function oneChannel(who, query) {
1148
1426
  if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
@@ -1151,7 +1429,7 @@ function createVercel(options, environment) {
1151
1429
  return channel ?? null;
1152
1430
  }
1153
1431
  /** A watcher's tail registers with the API as its own: an API watcher, so a match is the API's to make. */
1154
- 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);
1155
1433
  /** Who `--by` names, as the API's authors: an actor, a principal, or everyone here with that handle or profile, as of now. */
1156
1434
  async function authorsOf(who, by) {
1157
1435
  if (by === "me") return [await actorOf(who)];
@@ -1162,20 +1440,24 @@ function createVercel(options, environment) {
1162
1440
  }
1163
1441
  /**
1164
1442
  * A tail as the filter the API matches. The API reads no tails: channels, people, and threads are
1165
- * looked up here, now, and what it can't match (mentions, other sources) is refused rather than
1166
- * 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.
1167
1445
  */
1168
- async function filterOf(who, id, spec) {
1446
+ function checkedTail(id, spec, fromHere) {
1169
1447
  const bad = (message) => new HttpError(400, "bad_watcher", `watch ${id}: ${message}`);
1170
1448
  if (!RemoteWatcherId.safeParse(id).success) throw bad("ids start with a letter and use up to 32 letters, numbers, and hyphens");
1171
- let filters;
1449
+ let compiled;
1172
1450
  try {
1173
- ({filters} = compileWatcher(id, spec));
1451
+ compiled = compileWatcher(id, spec);
1174
1452
  } catch (error) {
1175
1453
  throw new HttpError(400, "bad_watcher", error.message);
1176
1454
  }
1177
- if (filters.mentions !== void 0) throw bad("Vercel's boards can't match mentions yet");
1178
- 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);
1179
1461
  const filter = {};
1180
1462
  if (filters.channel !== void 0) {
1181
1463
  if (filters.channel.endsWith("/")) filter.channelTree = filters.channel.slice(0, -1);
@@ -1187,7 +1469,7 @@ function createVercel(options, environment) {
1187
1469
  }
1188
1470
  if (filters.re !== void 0) {
1189
1471
  const at = locate(filters.re);
1190
- 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`);
1191
1473
  filter.threadId = at.threadId;
1192
1474
  }
1193
1475
  if (filters.by !== void 0) filter.authors = await authorsOf(who, filters.by);
@@ -1196,10 +1478,7 @@ function createVercel(options, environment) {
1196
1478
  key,
1197
1479
  values: [...values]
1198
1480
  });
1199
- return {
1200
- filter,
1201
- when: spec.when ?? "matches"
1202
- };
1481
+ return { filter };
1203
1482
  }
1204
1483
  /** A filter shown as a tail again, for listing: what it matches, if not always as it was written. */
1205
1484
  async function tailOf(who, { filter }) {
@@ -1213,75 +1492,118 @@ function createVercel(options, environment) {
1213
1492
  return parts.join(" ");
1214
1493
  }
1215
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
+ }));
1216
1499
  const whereOf = (found) => found.path ? {
1217
1500
  url: null,
1218
1501
  path: found.path,
1219
1502
  ...found.branch ? { branch: found.branch } : {}
1220
1503
  } : { url: found.url };
1221
- async function registerAs(who, where, watch) {
1222
- const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, {
1223
- tail: spec.tail,
1224
- when: spec.when ?? "matches"
1225
- }]));
1226
- 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
+ }));
1227
1528
  let made;
1228
1529
  try {
1229
- made = await api(who, "PUT", await onBoard(who, "/watchers"), { body: {
1530
+ made = await syncApi(who, "PUT", await onBoard(who, "/watchers"), { body: {
1230
1531
  ...where,
1231
1532
  watch: filters,
1232
- tag: await tagOf(specs)
1533
+ tag: await tagOf(specs, entries),
1534
+ ...entries.length ? { sync: entries } : {}
1233
1535
  } });
1234
1536
  } catch (error) {
1235
- if (error instanceof HttpError && error.code === "board_token_unsupported") throw new HttpError(403, "board_token_unsupported", "a board token can't register watchers yet.", {
1236
- hint: "Register them with a person's or a deployment's own credentials.",
1237
- origin: "handle"
1238
- });
1239
- throw error;
1537
+ throw needsProject(error);
1240
1538
  }
1241
1539
  return {
1242
1540
  owner: made.owner,
1243
1541
  ...whereOf(made),
1244
1542
  watch: specs,
1245
- sync: [],
1543
+ sync: syncOf(made),
1246
1544
  hash: made.hash
1247
1545
  };
1248
1546
  }
1249
1547
  /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
1250
- async function matchOf(who, match, me) {
1548
+ async function matchOf(who, match, filters) {
1251
1549
  const found = await messageById(who, match.event.messageId).catch((error) => {
1252
1550
  if (error instanceof HttpError && error.status === 404) return null;
1253
1551
  throw error;
1254
1552
  });
1255
1553
  const channel = found && await channelById(who, found.thread.channelId);
1256
- 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);
1257
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;
1258
1564
  return {
1259
1565
  id: match.id,
1260
1566
  watcher: match.watcher,
1261
1567
  thread: event.message.thread,
1262
1568
  lease: match.lease,
1263
1569
  attempt: match.attempt,
1264
- event
1570
+ event: handed
1265
1571
  };
1266
1572
  }
1267
- async function pullAs(who, query, signal) {
1268
- 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"), {
1269
1588
  query: {
1270
1589
  limit: query.limit?.toString(),
1271
1590
  wait: query.wait?.toString()
1272
1591
  },
1273
1592
  ...signal ? { signal } : {}
1274
1593
  });
1275
- const me = await actorOf(who);
1276
- const shown = await Promise.all(matches.map((match) => matchOf(who, match, me)));
1277
- 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, {
1278
1600
  lease: match.lease,
1279
1601
  skip: true
1280
1602
  }).catch(() => {})));
1281
- return shown.filter((match) => match !== null);
1603
+ return handed.filter((match) => match !== null);
1282
1604
  }
1283
1605
  async function ackAs(who, id, body) {
1284
- 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: {
1285
1607
  lease: body.lease,
1286
1608
  ...body.error !== void 0 ? { error: body.error } : {},
1287
1609
  ...body.skip ? { skip: true } : {}
@@ -1301,19 +1623,170 @@ function createVercel(options, environment) {
1301
1623
  const runner = registrant({
1302
1624
  remote: "Vercel's API",
1303
1625
  registry: {
1304
- register: (where) => registerAs(deployment, where, tails),
1305
- 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),
1306
1635
  ack: (id, body) => ackAs(deployment, id, body)
1307
1636
  },
1308
- wakeAt: async (here) => wakePath(here) ?? { url: here },
1637
+ wakeAt: async (here) => wakePath(here) ?? { url: null },
1309
1638
  binding: bound,
1310
- hash: () => tagOf(tails),
1311
- hasWork: () => Object.keys(tails).length > 0,
1639
+ hash: () => tagOf(tails, bound().sync),
1640
+ hasWork: () => Object.keys(tails).length > 0 || bound().sync.length > 0,
1312
1641
  rethrow: (error) => {
1313
1642
  throw error;
1314
1643
  },
1315
1644
  registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
1316
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}`);
1317
1790
  const methods = {
1318
1791
  ...Object.fromEntries(METHODS.map((method) => [method, async () => {
1319
1792
  throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
@@ -1332,7 +1805,10 @@ function createVercel(options, environment) {
1332
1805
  audience: origin,
1333
1806
  team_id: id,
1334
1807
  project_id: null,
1335
- sync: [],
1808
+ sync: (binding?.sync ?? []).map(({ key, platform }) => ({
1809
+ key,
1810
+ platform
1811
+ })),
1336
1812
  wake_by_path: true
1337
1813
  };
1338
1814
  },
@@ -1401,10 +1877,20 @@ function createVercel(options, environment) {
1401
1877
  };
1402
1878
  }
1403
1879
  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`);
1880
+ const limit = query.limit ?? 50;
1881
+ if (query.re === void 0 && query.after === void 0 && query.before === void 0 && !filtered(query)) {
1882
+ const { messages, feeds, newest } = await latest(who, await channelsFor(who, query.channel), limit, signal);
1883
+ return {
1884
+ messages: await Promise.all(messages.map(({ message, channel }) => view(who, message, channel.name))),
1885
+ cursor: cursorOf({
1886
+ t: newest,
1887
+ feeds
1888
+ })
1889
+ };
1890
+ }
1404
1891
  const { messages, feeds, newest } = await collect(who, query, signal);
1405
1892
  const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
1406
1893
  const before = query.before !== void 0 ? await timeOf(who, query.before) : void 0;
1407
- const limit = query.limit ?? 50;
1408
1894
  const bounded = messages.filter(({ message }) => (after === void 0 || message.createdAt > after) && (before === void 0 || message.createdAt < before));
1409
1895
  const page = after !== void 0 ? bounded.slice(0, limit) : bounded.slice(-limit);
1410
1896
  return {
@@ -1423,7 +1909,7 @@ function createVercel(options, environment) {
1423
1909
  const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
1424
1910
  return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
1425
1911
  };
1426
- 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) {
1427
1913
  const { messages, feeds, newest } = await collect(who, query, signal);
1428
1914
  const latest = /* @__PURE__ */ new Map();
1429
1915
  for (const { message, thread, channel } of messages) latest.set(thread.id, {
@@ -1492,6 +1978,7 @@ function createVercel(options, environment) {
1492
1978
  },
1493
1979
  async upload(caller, { data, name, type }) {
1494
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");
1495
1982
  if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
1496
1983
  if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
1497
1984
  const bytes = new Uint8Array(data);
@@ -1562,7 +2049,8 @@ function createVercel(options, environment) {
1562
2049
  text: input.text,
1563
2050
  ...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
1564
2051
  ...clientId ? { clientId } : {},
1565
- ...input.attachments?.length ? { attachments: input.attachments } : {}
2052
+ ...input.attachments?.length ? { attachments: input.attachments } : {},
2053
+ ...input.noSync ? { noSync: true } : {}
1566
2054
  },
1567
2055
  signal
1568
2056
  });
@@ -1581,7 +2069,8 @@ function createVercel(options, environment) {
1581
2069
  ...to.sequence > 1 ? { replyTo: to.sequence } : {},
1582
2070
  ...clientId ? { clientId } : {},
1583
2071
  ...input.attachments?.length ? { attachments: input.attachments } : {},
1584
- ...after ? { after: after.sequence } : {}
2072
+ ...after ? { after: after.sequence } : {},
2073
+ ...input.noSync ? { noSync: true } : {}
1585
2074
  },
1586
2075
  signal
1587
2076
  }).catch((error) => {
@@ -1762,6 +2251,7 @@ function createVercel(options, environment) {
1762
2251
  ...target,
1763
2252
  text: input.text,
1764
2253
  ...labels ? { labels } : {},
2254
+ ...input.noSync ? { noSync: true } : {},
1765
2255
  firstAt,
1766
2256
  ...input.every !== void 0 ? { every: ms(input.every) } : {},
1767
2257
  ...until !== void 0 ? { until } : {},
@@ -1787,14 +2277,9 @@ function createVercel(options, environment) {
1787
2277
  if (!channel) return { schedules: [] };
1788
2278
  filter.channelId = channel.id;
1789
2279
  }
1790
- const me = query.by === "me" ? await actorOf(who) : void 0;
1791
- const by = me ?? query.by;
1792
- if (by?.startsWith("vercel:")) filter.createdBy = by;
1793
- const created = (actor) => by === void 0 || (me ? actor.id === me : [
1794
- actor.id,
1795
- principalId(actor.principal),
1796
- actor.profile?.name
1797
- ].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);
1798
2283
  const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
1799
2284
  return { schedules: await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule))) };
1800
2285
  },
@@ -1809,59 +2294,166 @@ function createVercel(options, environment) {
1809
2294
  canceled
1810
2295
  };
1811
2296
  },
1812
- 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) {
1813
2312
  const who = whoOf(caller);
1814
- const channel = await oneChannel(who, query);
1815
- if (channel) return channelEvents(who, channel, query, signal);
1816
- 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`);
1817
- const listed = await channelsFor(who, query.channel);
1818
- let position = query.after === void 0 ? {
1819
- t: Date.now(),
1820
- feeds: await heads(who, listed)
1821
- } : locate(query.after) ? {
1822
- t: await timeOf(who, query.after),
1823
- feeds: {}
1824
- } : positionOf(query.after);
1825
- const until = Date.now() + (query.wait ?? 0) * 1e3;
1826
- let busy = false;
1827
- for (;;) {
1828
- const started = Date.now();
1829
- const page = await read(who, listed, position, query, signal);
1830
- position = page.position;
1831
- if (page.events.length > 0 || Date.now() >= until || signal.aborted) return {
1832
- events: page.events,
1833
- cursor: cursorOf(position)
1834
- };
1835
- if (!busy) busy = await changed(who, listed, position, until, signal) && Date.now() - started < 1e3;
1836
- 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
+ });
1837
2381
  }
2382
+ throw missing();
1838
2383
  },
1839
- async typing() {
1840
- 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 };
2396
+ },
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
+ })) };
1841
2408
  },
1842
- async readSource(_caller, { key }) {
1843
- throw notFound(`this board doesn't run sync entry ${key}`, "not_synced_here");
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) };
1844
2436
  },
1845
2437
  async watchers(caller) {
1846
2438
  const who = whoOf(caller);
1847
- const { watchers } = await api(who, "GET", await onBoard(who, "/watchers"));
2439
+ const { watchers } = await watchersApi(who, "GET", await onBoard(who, "/watchers"));
1848
2440
  return { watchers: await Promise.all(watchers.map(async (found) => ({
1849
2441
  owner: found.owner,
1850
2442
  ...whereOf(found),
1851
- watch: Object.fromEntries(await Promise.all(Object.entries(found.watch).map(async ([id, spec]) => [id, {
1852
- tail: await tailOf(who, spec),
1853
- when: spec.when
1854
- }]))),
1855
- 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),
1856
2445
  hash: found.hash
1857
2446
  }))) };
1858
2447
  },
1859
2448
  async register(caller, body) {
1860
- 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
+ });
1861
2453
  return registerAs(whoOf(caller), typeof body.path === "string" ? {
1862
2454
  path: body.path,
1863
2455
  ...body.branch ? { branch: body.branch } : {}
1864
- } : { url: body.url ?? null }, body.watch);
2456
+ } : { url: body.url ?? null }, body.watch, body.sync ?? [], false);
1865
2457
  },
1866
2458
  async matches(caller, query, signal) {
1867
2459
  return { matches: await pullAs(whoOf(caller), query, signal) };
@@ -1874,27 +2466,31 @@ function createVercel(options, environment) {
1874
2466
  return {
1875
2467
  ...Object.fromEntries(Object.entries(methods).map(([name, method]) => [name, (caller, ...args) => {
1876
2468
  if ("identity" in caller) throw servesNone();
1877
- if (binding) runner.start();
2469
+ if (binding) waitUntil(start());
1878
2470
  return method(caller, ...args);
1879
2471
  }])),
1880
- routes: runner.routes,
2472
+ routes,
1881
2473
  keeps: false,
1882
2474
  sendsSchedulesHere: false,
1883
2475
  bind(next) {
1884
2476
  if (binding) throw new Error("vercel: this backend already serves a board: create one vercel() per board()");
1885
- 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");
1886
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`);
1887
2478
  for (const id of Object.keys(next.subscriptions)) own.add(id);
1888
- tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, {
1889
- tail: subscription.tail,
1890
- when: subscription.when
1891
- }]] : []));
2479
+ tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, { tail: subscription.tail }]] : []));
1892
2480
  binding = next;
1893
2481
  },
1894
- /** Registers this board's watchers with Vercel's API now, as `POST /watchers` does. */
1895
- registerWatchers: runner.registerNow,
1896
- /** Stops pulling, for a board that pulls on its own. */
1897
- 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
+ }
1898
2494
  };
1899
2495
  }
1900
2496
  //#endregion
@@ -2128,6 +2724,13 @@ const LOGOS = {
2128
2724
  //#region src/server/avatars.ts
2129
2725
  /** Each known agent's mark on its color. */
2130
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
+ },
2131
2734
  claude: {
2132
2735
  background: "#D97757",
2133
2736
  mark: { path: LOGOS.claude }
@@ -2151,7 +2754,7 @@ function avatarSvg(name) {
2151
2754
  background: "#666666",
2152
2755
  mark: { glyph: name.slice(0, 1).toUpperCase() }
2153
2756
  };
2154
- 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>`;
2155
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>`;
2156
2759
  }
2157
2760
  //#endregion
@@ -3055,6 +3658,7 @@ async function createServe(context) {
3055
3658
  const made = CREATED.has(target.name) || target.name === "createChannel" && output.created;
3056
3659
  return json(output, made ? 201 : 200);
3057
3660
  } catch (error) {
3661
+ if (request.signal.aborted && error === request.signal.reason) return new Response(null, { status: 499 });
3058
3662
  return toErrorResponse(error);
3059
3663
  }
3060
3664
  }
@@ -3228,8 +3832,7 @@ function createBoard(options, runtime) {
3228
3832
  };
3229
3833
  const subscriptions = Object.fromEntries(Object.entries(watch).map(([id, watcher]) => [id, {
3230
3834
  kind: "tail",
3231
- tail: watcher.tail,
3232
- when: watcher.when ?? "matches"
3835
+ tail: watcher.tail
3233
3836
  }]));
3234
3837
  if (Object.keys(entries).length > 0) subscriptions[SYNC] = { kind: "sync" };
3235
3838
  /** This board's sync entries, as its sync and discovery see them. */