@vercel/board 0.45.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/{access-3udXjJAg.mjs → access-C06pIr0M.mjs} +2 -2
  2. package/dist/access.d.mts +2 -2
  3. package/dist/access.mjs +5 -5
  4. package/dist/{actors-DasGZnfb.mjs → actors-Dkyg-oo0.mjs} +3 -3
  5. package/dist/{auth-aiOVE82-.mjs → auth-B9-wXQ-x.mjs} +29 -9
  6. package/dist/{auth-BG_whr9_.d.mts → auth-li3lKwJG.d.mts} +1 -1
  7. package/dist/{backend-D6yTo8Un.d.mts → backend-i_esjwUS.d.mts} +144 -5
  8. package/dist/backend-local.d.mts +1 -1
  9. package/dist/backend-local.mjs +1 -1
  10. package/dist/{chat-provider-V2jnjVLq.d.mts → chat-provider-BWBGZOZY.d.mts} +4 -2
  11. package/dist/{chat-provider-BvNqOQFL.mjs → chat-provider-CD7jskh7.mjs} +7 -4
  12. package/dist/cli-commands.d.mts +1 -1
  13. package/dist/cli-commands.mjs +1 -1
  14. package/dist/cli-embedded.d.mts +2 -2
  15. package/dist/cli-embedded.mjs +3 -2
  16. package/dist/cli.mjs +46 -15
  17. package/dist/{commands-DewS14_P.d.mts → commands-CJsOA-hf.d.mts} +60 -0
  18. package/dist/{commands-CqdnjUkm.mjs → commands-Dk6_cHLS.mjs} +325 -0
  19. package/dist/{conformance-BInS4_6b.mjs → conformance-CDP8y2Zm.mjs} +1063 -6
  20. package/dist/conformance.d.mts +6 -5
  21. package/dist/conformance.mjs +1 -1
  22. package/dist/{engine-XVBt02Bl.mjs → engine-j2VeNuKG.mjs} +51 -50
  23. package/dist/{errors-ZazTZh-s.mjs → errors-QhkdzI-o.mjs} +176 -9
  24. package/dist/{events-D17RndlV.mjs → events-MOcxGpOQ.mjs} +2 -2
  25. package/dist/{exports-DCxecX15.mjs → exports-CEqS-IPP.mjs} +1417 -84
  26. package/dist/exports-CF9rKCXd.d.mts +44 -0
  27. package/dist/{external-DfhN7lKK.mjs → external-BuVTXT1R.mjs} +7 -3
  28. package/dist/{index-Djmr4GzQ.d.mts → index-ttfx1TZ6.d.mts} +2 -2
  29. package/dist/index.d.mts +6 -6
  30. package/dist/index.mjs +5 -5
  31. package/dist/index.node.d.mts +7 -6
  32. package/dist/index.node.mjs +5 -4
  33. package/dist/inspect/app.js +215 -115
  34. package/dist/inspect/engine.js +5 -5
  35. package/dist/inspect-8YAhl_h3.mjs +2 -0
  36. package/dist/{inspect-CHsgnf_5.mjs → inspect-vOSrW_g6.mjs} +322 -50
  37. package/dist/{local-DE9vmanM.mjs → local-0ajWOVhN.mjs} +1673 -98
  38. package/dist/{main-CF1Me3jg.mjs → main-B8Zkd4Pm.mjs} +1282 -58
  39. package/dist/{memory-DyEL0fvN.mjs → memory-CMm-Fk_A.mjs} +2 -2
  40. package/dist/{mentions-DfZGp3B-.mjs → mentions-CnWt9Z5b.mjs} +34 -1
  41. package/dist/{middleware-BHHKHA9q.mjs → middleware-CT6vMNUc.mjs} +2 -2
  42. package/dist/{provider-BC9mPYVh.d.mts → provider-Bc3xI90K.d.mts} +199 -6
  43. package/dist/{routes-CkUetTO2.mjs → routes-ABXf3CKq.mjs} +261 -8
  44. package/dist/{routes-zm4TXKCC.d.mts → routes-CjA6Mp4D.d.mts} +610 -6
  45. package/dist/{schemas-BhZaystC.mjs → schemas-7VFdomFB.mjs} +34 -1
  46. package/dist/serve-BepKXDH3.mjs +285 -0
  47. package/dist/{server-Bmz0zqYM.mjs → server-4rQL3xuH.mjs} +41 -22
  48. package/dist/{serving-BLVRrJ7P.mjs → serving-BNdiReQT.mjs} +1 -1
  49. package/dist/{sql-CyVcjw8x.mjs → sql-IEbO5vXs.mjs} +174 -9
  50. package/dist/{sqlite-Con-8duk.mjs → sqlite-CVG8XKHm.mjs} +2 -2
  51. package/dist/{sqlite-db-BdzxtUOV.mjs → sqlite-db-BJjPQYx4.mjs} +1 -1
  52. package/dist/sync-chat-sdk.d.mts +16 -2
  53. package/dist/sync-chat-sdk.mjs +2 -2
  54. package/dist/sync-github.d.mts +16 -2
  55. package/dist/sync-github.mjs +3 -3
  56. package/dist/sync-linear.d.mts +17 -3
  57. package/dist/sync-linear.mjs +2 -2
  58. package/dist/sync-slack.d.mts +17 -3
  59. package/dist/sync-slack.mjs +107 -15
  60. package/dist/sync.d.mts +2 -2
  61. package/dist/sync.mjs +2 -2
  62. package/dist/{origin-BbwhnKrg.mjs → task-batch-BZXm6kOE.mjs} +83 -8
  63. package/dist/{tokens-BErYXuHZ.mjs → tokens-BCp4EWTQ.mjs} +2 -2
  64. package/docs/01-board/01-mounting.md +8 -5
  65. package/docs/01-board/03-identity.md +43 -23
  66. package/docs/01-board/04-messages.md +3 -2
  67. package/docs/01-board/06-watchers.md +3 -3
  68. package/docs/01-board/07-schedules.md +2 -2
  69. package/docs/01-board/08-middleware.md +7 -0
  70. package/docs/01-board/09-access.md +6 -4
  71. package/docs/01-board/10-local.md +4 -1
  72. package/docs/01-board/11-tasks.md +348 -0
  73. package/docs/02-sync/01-overview.md +4 -5
  74. package/docs/02-sync/02-functions.md +2 -2
  75. package/docs/02-sync/03-slack.md +8 -5
  76. package/docs/02-sync/06-providers.md +8 -0
  77. package/docs/03-guides/02-inspector.md +83 -10
  78. package/docs/03-guides/06-sandboxed-agents.md +7 -5
  79. package/docs/03-guides/07-build-a-ui.md +210 -0
  80. package/docs/03-guides/08-tailnet.md +123 -0
  81. package/docs/04-reference/01-cli.md +272 -23
  82. package/docs/04-reference/02-board.md +287 -7
  83. package/docs/04-reference/03-http.md +208 -13
  84. package/docs/04-reference/05-conformance.md +10 -7
  85. package/package.json +1 -1
  86. package/dist/exports-Gspe1eEq.d.mts +0 -4
  87. package/dist/inspect-C8U3A4jQ.mjs +0 -2
  88. package/dist/serve-CEMvl0EH.mjs +0 -181
@@ -1,20 +1,20 @@
1
- import { S as mediaType, _ as ATTACHMENT_BYTES_MAX, a as forbidden$1, b as fileName, c as textTooLong, d as BoardError, i as duplicateId, l as toErrorResponse, p as duration, r as badRequest, s as notFound, t as HttpError, v as DIRECT_UPLOAD_BYTES_MAX, y as IMPORT_BYTES_MAX } from "./errors-ZazTZh-s.mjs";
2
- import { S as storable, _ as SeenActorKind, a as CAN_MAX, b as authorView, c as Emoji, f as Labels, g as RemoteWatcherId, h as MessageText, i as Author, l as Handle, m as MessageId, n as Attachment, o as CHANNEL_PATTERN_MAX, s as ChannelPath, t as ActorId, u as LabelKey, x as platformAvatar, y as actorKind } from "./schemas-BhZaystC.mjs";
3
- import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-DfhN7lKK.mjs";
4
- import "./routes-CkUetTO2.mjs";
5
- import { a as waitUntil, c as platformProfile, d as userIdOf, h as isKeyIdOf, l as shownName, m as derivedId, n as MIDDLEWARE_ACTOR, o as actorParts, s as importedHandle, t as DroppedError } from "./middleware-BHHKHA9q.mjs";
1
+ import { S as fileName, a as duplicateId, b as DIRECT_UPLOAD_BYTES_MAX, c as notFound, f as BoardError, i as batchTooLarge, l as textTooLong, m as duration, o as forbidden$1, r as badRequest, t as HttpError, u as toErrorResponse, w as mediaType, x as IMPORT_BYTES_MAX, y as ATTACHMENT_BYTES_MAX } from "./errors-QhkdzI-o.mjs";
2
+ import { A as authorView, D as TaskNote, E as TaskHoldKind, M as storable, T as TASK_NOTE_MAX, _ as OPEN_TASK_STATES, a as CAN_MAX, b as SeenActorKind, c as EDITED_HOLD, d as LabelKey, g as MessageText, h as MessageId, i as Author, j as platformAvatar, k as actorKind, l as Emoji, n as Attachment, o as CHANNEL_PATTERN_MAX, p as Labels, s as ChannelPath, t as ActorId, u as Handle, w as TASK_LABEL, y as RemoteWatcherId } from "./schemas-7VFdomFB.mjs";
3
+ import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-BuVTXT1R.mjs";
4
+ import "./routes-ABXf3CKq.mjs";
5
+ import { a as waitUntil, c as platformProfile, d as userIdOf, h as isKeyIdOf, l as shownName, m as derivedId, n as MIDDLEWARE_ACTOR, o as actorParts, s as importedHandle, t as DroppedError } from "./middleware-CT6vMNUc.mjs";
6
6
  import { a as SCHEMA_DESCRIPTION_MAX, c as canonical, d as parseSchemaId, f as schemaId, i as BUILT_IN_SCHEMAS, l as checkDefinition, n as blocksIn, o as SCHEMA_NAME, s as SCHEMA_VERSION_MAX, u as isBuiltInName } from "./blocks-CVoBC7ur.mjs";
7
- import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-BbwhnKrg.mjs";
8
- import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-3udXjJAg.mjs";
9
- import { S as wroteAs, _ as removes, a as authenticates, c as checkPrincipal, d as grantIssuers, m as joined, n as GITHUB_ISSUER, o as checkCan, p as issuerName, s as checkGrant, x as workflowPath } from "./auth-aiOVE82-.mjs";
7
+ import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-CnWt9Z5b.mjs";
8
+ import { a as runMatch, g as VERSION, h as SYNC, i as canonicalWatchers, l as METHODS, n as SYNC_ACTOR, o as compileWatcher, r as syncTarget, s as hasCriteria, t as batchPlan } from "./task-batch-BZXm6kOE.mjs";
9
+ import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-C06pIr0M.mjs";
10
+ import { T as wroteAs, b as removes, c as checkCan, g as joined, h as issuerName, l as checkGrant, n as GITHUB_ISSUER, p as grantIssuers, s as authenticates, u as checkPrincipal, w as workflowPath } from "./auth-B9-wXQ-x.mjs";
10
11
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
11
- import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-DasGZnfb.mjs";
12
+ import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-Dkyg-oo0.mjs";
12
13
  import { C as sessionClearedError, a as SOCKET_TIMINGS, c as drainSettledHooks, d as nullProtoRecord, f as runtimeConsumerFactory, g as A2Error, h as stateTailReaders, i as RESERVED_PARTICIPANT_IDS, l as failedPreviousAttempt, m as serverInternals, n as POLL_TIMINGS, o as STATE_CACHE, p as runtimeConsumers, r as PRESENCE_TIMINGS, s as STREAM_TIMINGS, t as DRAIN_TIMINGS, u as markSchedulerSendFailure, v as NonRetriableError, x as isSessionCleared, y as asStoreUnavailable } from "./internal-CvsrprnU-CEPOUpAv.mjs";
13
14
  import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-oh3aU_An.mjs";
14
- import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-CyVcjw8x.mjs";
15
- import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-DfZGp3B-.mjs";
15
+ import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-IEbO5vXs.mjs";
16
16
  import { z } from "zod";
17
- import { createHash, randomBytes } from "node:crypto";
17
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
18
18
  import { mkdir, readFile, writeFile } from "node:fs/promises";
19
19
  import { dirname, join, resolve } from "node:path";
20
20
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -3832,6 +3832,15 @@ const stateCacheKey = (sessionId, reducerName) => `${sessionId}\u0000${reducerNa
3832
3832
  const From = z.string().nullable();
3833
3833
  /** The thread key: the event ID of the thread's root. Lanes and sync state are keyed by it. */
3834
3834
  const ThreadKey = z.string().min(1).max(200).refine(storable, "thread key has a NUL character or a lone surrogate");
3835
+ /** The task an event changes: its root's ID, and the root's thread key, which lanes go by. */
3836
+ const Task = {
3837
+ id: MessageId,
3838
+ thread: ThreadKey
3839
+ };
3840
+ /** Which claim of a task this is: 1 for its first, one more for each after. A write that names an older one changes nothing. */
3841
+ const Epoch = z.number().int().positive();
3842
+ /** When a claim's lease runs out, as an ISO time. */
3843
+ const Until = z.string().datetime();
3835
3844
  /** The board's one log. Every board fact is an event in session `board`. */
3836
3845
  const boardEvents = {
3837
3846
  "message.posted": z.object({
@@ -3864,6 +3873,12 @@ const boardEvents = {
3864
3873
  */
3865
3874
  blind: z.literal(true).optional(),
3866
3875
  /**
3876
+ * (server) How many events right after it, in its own append, are about it: what made a new
3877
+ * thread a task. A writer that can't read its channel gets those back with its post on a
3878
+ * retry, and nothing written since. A post that came alone has none.
3879
+ */
3880
+ along: z.number().int().positive().max(3).optional(),
3881
+ /**
3867
3882
  * (server) The principal of the sync elsewhere that imported it, whose copy `origin` names:
3868
3883
  * that sync's to act on. None for the board's own sync, or a write on the board.
3869
3884
  */
@@ -3962,6 +3977,92 @@ const boardEvents = {
3962
3977
  target: ExternalTarget,
3963
3978
  error: z.string().min(1).max(500)
3964
3979
  }),
3980
+ /**
3981
+ * The thread rooted at `id` is a task, and `by.principal` owns it. It waits while it has `needs`,
3982
+ * until `task.ready` says they've all completed; with none, it's ready.
3983
+ */
3984
+ "task.created": z.object({
3985
+ ...Task,
3986
+ needs: z.array(MessageId).max(20),
3987
+ for: ActorId.nullable(),
3988
+ by: Author
3989
+ }),
3990
+ /** Only actor `for` claims it now, or with null, anyone who may. */
3991
+ "task.assigned": z.object({
3992
+ ...Task,
3993
+ for: ActorId.nullable(),
3994
+ by: Author
3995
+ }),
3996
+ /**
3997
+ * It waits for `needs` now, in place of what it waited for. As from `task.created`, it waits
3998
+ * while it has any, until `task.ready` says they've all completed, and with none it's ready. One
3999
+ * that's held stays held.
4000
+ */
4001
+ "task.needs_changed": z.object({
4002
+ ...Task,
4003
+ needs: z.array(MessageId).max(20),
4004
+ by: Author
4005
+ }),
4006
+ /** (server) Every task it needs has completed. */
4007
+ "task.ready": z.object(Task),
4008
+ /** (server) `by` holds it until `until`. `token` is the SHA-256 of the claim's secret, hex: no view shows it. */
4009
+ "task.claimed": z.object({
4010
+ ...Task,
4011
+ epoch: Epoch,
4012
+ until: Until,
4013
+ token: z.string().regex(/^[0-9a-f]{64}$/),
4014
+ by: Author
4015
+ }),
4016
+ "task.renewed": z.object({
4017
+ ...Task,
4018
+ epoch: Epoch,
4019
+ until: Until,
4020
+ by: Author
4021
+ }),
4022
+ "task.released": z.object({
4023
+ ...Task,
4024
+ epoch: Epoch,
4025
+ by: Author
4026
+ }),
4027
+ /** (server) Its lease ran out. */
4028
+ "task.expired": z.object({
4029
+ ...Task,
4030
+ epoch: Epoch
4031
+ }),
4032
+ "task.completed": z.object({
4033
+ ...Task,
4034
+ epoch: Epoch,
4035
+ result: TaskNote.nullable(),
4036
+ by: Author
4037
+ }),
4038
+ "task.failed": z.object({
4039
+ ...Task,
4040
+ epoch: Epoch,
4041
+ reason: TaskNote,
4042
+ by: Author
4043
+ }),
4044
+ /** Held for a person, which ends any claim. Kind `edited` is the board's: `by` edited its root, and isn't its owner. */
4045
+ "task.blocked": z.object({
4046
+ ...Task,
4047
+ kind: TaskHoldKind.nullable(),
4048
+ reason: TaskNote,
4049
+ by: Author
4050
+ }),
4051
+ "task.unblocked": z.object({
4052
+ ...Task,
4053
+ by: Author
4054
+ }),
4055
+ /** Reason `deleted` when its root was. */
4056
+ "task.canceled": z.object({
4057
+ ...Task,
4058
+ reason: TaskNote,
4059
+ by: Author
4060
+ }),
4061
+ /** A failed task is ready again. */
4062
+ "task.reopened": z.object({
4063
+ ...Task,
4064
+ by: Author
4065
+ }),
3965
4066
  "actor.seen": z.object({
3966
4067
  actor: ActorId,
3967
4068
  kind: SeenActorKind,
@@ -4243,6 +4344,22 @@ const schedulesContract = contract({
4243
4344
  }
4244
4345
  });
4245
4346
  const SCHEDULES_SESSION = "schedules";
4347
+ /**
4348
+ * A claim's lease timers, outside the board log: one session, `leases`. Each claim and renewal arms
4349
+ * one for when its lease runs out, carrying `lease.due`. Timers can't be revoked, so one for a claim
4350
+ * that's over, or renewed since, fires into a no-op: the board log holds only a real `task.expired`.
4351
+ */
4352
+ const leasesContract = contract({
4353
+ name: "board-leases",
4354
+ events: {
4355
+ /** (server) A timer: task `id`'s claim at `epoch` was to run out at `at`. */
4356
+ "lease.due": z.object({
4357
+ id: MessageId,
4358
+ epoch: z.number().int().positive(),
4359
+ at: Millis
4360
+ }) }
4361
+ });
4362
+ const LEASES_SESSION = "leases";
4246
4363
  const Grant = z.union([z.literal("all"), z.array(z.string().min(1).max(16)).max(8)]);
4247
4364
  /** A `can`, as config writes it: board() checks it before it's kept. */
4248
4365
  const Can = z.union([Grant, z.record(z.string().min(1).max(CHANNEL_PATTERN_MAX), Grant)]);
@@ -4400,11 +4517,12 @@ const actorsReducer = reducer({
4400
4517
  }).fold(foldActors);
4401
4518
  //#endregion
4402
4519
  //#region src/server/feed.ts
4403
- /** Bookkeeping events, shown only with `all`: who's who, and delivery receipts. */
4520
+ /** Bookkeeping events, shown only with `all`: who's who, delivery receipts, and a claim's renewals. */
4404
4521
  const HIDDEN = /* @__PURE__ */ new Set([
4405
4522
  "actor.seen",
4406
4523
  "message.synced",
4407
- "message.files_synced"
4524
+ "message.files_synced",
4525
+ "task.renewed"
4408
4526
  ]);
4409
4527
  /** Whether the board checked who an actor is, as people see them, at their last write (`actor.seen`'s `verified`). */
4410
4528
  const verifiedRecord = (actor) => actor.verified === true;
@@ -4498,11 +4616,25 @@ const ref = (index) => String(index);
4498
4616
  const scheduleRef = (index) => `s${index}`;
4499
4617
  /** The log index a ref names on this board, or null for a string that names nothing here. */
4500
4618
  const indexOf$1 = (value) => /^(0|[1-9]\d{0,15})$/.test(value) ? Number(value) : null;
4619
+ /** A task as every reader sees it: the tasks it waits for as refs, and its claim without the token, hashed or not. */
4620
+ function taskView(task) {
4621
+ const { needs, claim, ...shown } = task;
4622
+ return {
4623
+ ...shown,
4624
+ needs: needs.map(ref),
4625
+ claim: claim && {
4626
+ actor: claim.actor,
4627
+ until: claim.until
4628
+ },
4629
+ blocked: task.blocked && { ...task.blocked }
4630
+ };
4631
+ }
4501
4632
  /** A message as `reader` sees it. Every view names its reader, so none shows a link's snapshot by default. */
4502
4633
  function view$1(message, actors, reader) {
4503
- const { blind, version, revision, schedule, platformText, mentions: _mentions, ...shown } = message;
4634
+ const { blind, version, revision, schedule, task, platformText, mentions: _mentions, ...shown } = message;
4504
4635
  return {
4505
4636
  ...shown,
4637
+ ...task ? { task: taskView(task) } : {},
4506
4638
  by: authorView(message.by),
4507
4639
  ...blind ? { blind } : {},
4508
4640
  id: ref(message.id),
@@ -4718,14 +4850,15 @@ function eventView(event, after, actors, reader) {
4718
4850
  } } : {}
4719
4851
  };
4720
4852
  }
4721
- /** An event's payload as clients see it: the message IDs in it are refs. */
4853
+ /** An event's payload as clients see it: the message IDs in it are refs, and a claim's token is left out. */
4722
4854
  function payloadView(payload, links) {
4723
- const { mentions: _mentions, ...shown } = payload;
4855
+ const { token: _token, mentions: _mentions, along: _along, ...shown } = payload;
4724
4856
  for (const key of [
4725
4857
  "id",
4726
4858
  "re",
4727
4859
  "replyTo"
4728
4860
  ]) if (typeof shown[key] === "number") shown[key] = ref(shown[key]);
4861
+ if (Array.isArray(shown.needs)) shown.needs = shown.needs.map(ref);
4729
4862
  if (typeof shown.by === "object" && shown.by !== null) shown.by = authorView(shown.by);
4730
4863
  const schedule = shown.schedule;
4731
4864
  if (schedule) shown.schedule = {
@@ -4844,7 +4977,7 @@ async function start(options) {
4844
4977
  const { index: head } = await options.session.state(channelsReducer);
4845
4978
  return options.after === void 0 || options.after >= head ? head : options.after;
4846
4979
  }
4847
- const PAGE = 200;
4980
+ const PAGE$1 = 200;
4848
4981
  /**
4849
4982
  * One long-poll: matching events already in the log return at once; otherwise
4850
4983
  * it waits up to `waitMs` for the first new match. The cursor is the last
@@ -4857,7 +4990,7 @@ async function pollFeed(options, waitMs, signal) {
4857
4990
  let cursor = index;
4858
4991
  const backlog = await options.session.history({
4859
4992
  gte: index + 1,
4860
- lte: index + PAGE
4993
+ lte: index + PAGE$1
4861
4994
  });
4862
4995
  await feed.preload(backlog, index);
4863
4996
  for (const event of backlog) {
@@ -4865,7 +4998,7 @@ async function pollFeed(options, waitMs, signal) {
4865
4998
  cursor = item.index;
4866
4999
  if (item.view) events.push(item.view);
4867
5000
  }
4868
- if (events.length > 0 || backlog.length === PAGE || waitMs <= 0) return {
5001
+ if (events.length > 0 || backlog.length === PAGE$1 || waitMs <= 0) return {
4869
5002
  events,
4870
5003
  cursor
4871
5004
  };
@@ -4932,6 +5065,20 @@ function seenFor(identity, actors) {
4932
5065
  } : actor, actors, identity.principal.facts?.issuer === "host");
4933
5066
  }
4934
5067
  /**
5068
+ * The `actor.seen` of each platform user an import's text mentions that the board hasn't met: who
5069
+ * they are, as the import names them. One it knows keeps its record, which their own writes keep
5070
+ * current: a mention only introduces.
5071
+ */
5072
+ function metBy(introduces, actors, author) {
5073
+ const met = /* @__PURE__ */ new Set([author]);
5074
+ return (introduces ?? []).flatMap((actor) => {
5075
+ if (met.has(actor.id) || own(actors.byId, actor.id)) return [];
5076
+ met.add(actor.id);
5077
+ const seen = actorSeen(actor, actors);
5078
+ return seen ? [seen] : [];
5079
+ });
5080
+ }
5081
+ /**
4935
5082
  * Whether the board checked who a write is by, as it shows them: a principal a credential named (an
4936
5083
  * OIDC token it trusts, or a host's verifier; never the board's own code), shown as
4937
5084
  * that principal names it: its handle and name, and for an agent, that principal after `via`, its
@@ -4949,6 +5096,15 @@ function verifiedAs({ principal, author, actor }) {
4949
5096
  * any of its agents, and a platform user a sync speaks for only as that same user.
4950
5097
  */
4951
5098
  const authored = (message, identity) => message.by.principal === identity.principal.id && (platformProfile(identity.author.profile) === null || message.by.actor === identity.author.actor);
5099
+ /**
5100
+ * Whether `identity` is a task's owner, to change it or what it says: the principal that made it a
5101
+ * task, as itself, or as the profile it made it as. Another of its profiles isn't: they share a
5102
+ * credential, and nothing else keeps one's work from another.
5103
+ */
5104
+ const ownedBy = (task, identity) => wroteAs(identity, {
5105
+ principal: task.owner,
5106
+ actor: task.by
5107
+ });
4952
5108
  const messageNotFound = (id) => () => notFound(`message not found: #${id}`, "message_not_found");
4953
5109
  /**
4954
5110
  * A message the board looked up and the caller may act on with `permission`,
@@ -5042,6 +5198,7 @@ async function writePost(ctx, input) {
5042
5198
  if (input.after !== void 0) throw badRequest("`after` is for replies", "invalid_after");
5043
5199
  thread = id;
5044
5200
  }
5201
+ if (input.with && re !== null) throw new Error("only a new thread is posted with more: a reply has no task to be");
5045
5202
  spend(input.proofs.post, "post", { channel });
5046
5203
  if (hasLabels(input.labels)) spend(input.proofs.label, "label", { channel });
5047
5204
  if (input.sync?.length) spend(input.proofs.sync, "sync", { channel });
@@ -5084,14 +5241,17 @@ async function landedFor(ctx, identity, landed) {
5084
5241
  const { state: actors } = await ctx.session.state(actorsReducer);
5085
5242
  if (access.readable(landed.channel)) return view$1(landed, actors, await readerFor(ctx, access, landed));
5086
5243
  if (!landed.blind) return null;
5087
- const [event] = await ctx.session.history({
5244
+ const events = await ctx.session.history({
5088
5245
  gte: landed.id,
5089
- lte: landed.id
5246
+ lte: landed.id + 3
5090
5247
  });
5091
- const posted = foldMessages({
5248
+ const along = events[0].payload.along ?? 0;
5249
+ const folded = {
5092
5250
  byId: {},
5093
5251
  replies: {}
5094
- }, event).byId[landed.id];
5252
+ };
5253
+ for (const event of events.slice(0, 1 + along)) foldMessages(folded, event);
5254
+ const posted = folded.byId[landed.id];
5095
5255
  return {
5096
5256
  ...view$1(posted, actors, await readerFor(ctx, access, posted)),
5097
5257
  text: blindText(posted.text, identity.actor.id)
@@ -5131,6 +5291,7 @@ async function commitPost(ctx, input, placed) {
5131
5291
  })));
5132
5292
  const events = [
5133
5293
  ...seen ? [seen] : [],
5294
+ ...metBy(input.introduces, actors, identity.actor.id),
5134
5295
  {
5135
5296
  type: "message.posted",
5136
5297
  ...id ? { id } : {},
@@ -5156,9 +5317,29 @@ async function commitPost(ctx, input, placed) {
5156
5317
  ];
5157
5318
  let rows;
5158
5319
  try {
5159
- rows = input.after === void 0 || re === null ? await ctx.session.append(...events) : await appendWhile(ctx, nothingAfter(ctx, re, input.after), events);
5320
+ if (input.with) {
5321
+ const along = input.with;
5322
+ const before = events.findIndex((event) => event.type === "message.posted");
5323
+ rows = await appendFrom(ctx, async () => {
5324
+ const { position, events: more } = await along();
5325
+ const came = more({
5326
+ id: position + 1 + before,
5327
+ thread
5328
+ });
5329
+ return {
5330
+ position,
5331
+ events: [...events.map((event) => event.type === "message.posted" ? {
5332
+ ...event,
5333
+ payload: {
5334
+ ...event.payload,
5335
+ along: came.length
5336
+ }
5337
+ } : event), ...came]
5338
+ };
5339
+ });
5340
+ } else rows = input.after === void 0 || re === null ? await ctx.session.append(...events) : await appendWhile(ctx, nothingAfter(ctx, re, input.after), events);
5160
5341
  } catch (error) {
5161
- const replayed = error instanceof HttpError && error.code === "newer_message" ? await replayOf(ctx, input, {
5342
+ const replayed = error instanceof HttpError && error.code === "newer_message" || input.with !== void 0 && duplicateEvent(error) ? await replayOf(ctx, input, {
5162
5343
  channel,
5163
5344
  re,
5164
5345
  replyTo
@@ -5168,22 +5349,130 @@ async function commitPost(ctx, input, placed) {
5168
5349
  }
5169
5350
  const posted = rows.find((row) => row.type === "message.posted");
5170
5351
  await untilApplied(ctx, rows);
5171
- const message = foldMessages({
5352
+ const folded = {
5172
5353
  byId: {},
5173
5354
  replies: {}
5174
- }, posted).byId[posted.index];
5175
- const known = seen ? {
5176
- ...actors,
5177
- byId: {
5178
- ...actors.byId,
5179
- [identity.actor.id]: {
5180
- ...identity.actor,
5181
- ...seen.payload.host ? { host: true } : {},
5182
- ...seen.payload.verified ? { verified: true } : {}
5183
- }
5355
+ };
5356
+ for (const row of [...rows].sort((a, b) => a.index - b.index)) foldMessages(folded, row);
5357
+ const message = folded.byId[posted.index];
5358
+ return shownTo(view$1(message, knownWith(actors, identity, seen), await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent);
5359
+ }
5360
+ /** The actors with a write's author as the board now records them: a host's principal stays the host's. */
5361
+ const knownWith = (actors, identity, seen) => seen ? {
5362
+ ...actors,
5363
+ byId: {
5364
+ ...actors.byId,
5365
+ [identity.actor.id]: {
5366
+ ...identity.actor,
5367
+ ...seen.payload.host ? { host: true } : {},
5368
+ ...seen.payload.verified ? { verified: true } : {}
5184
5369
  }
5185
- } : actors;
5186
- return shownTo(view$1(message, known, await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent);
5370
+ }
5371
+ } : actors;
5372
+ /**
5373
+ * Several new threads in `channel`, in one append: each root with what `with` makes of it right
5374
+ * after it, in the order given, all of them or none. Answers the roots as the append left them.
5375
+ * With `again`, the roots are a caller's own to send again: `again.landed` finds the ones the same
5376
+ * request landed already, which are answered as they are with nothing written, and `again.asked`
5377
+ * is the ID the event right after the first root carries, which says what was asked for.
5378
+ */
5379
+ async function writeRoots(ctx, input) {
5380
+ const { identity, channel, roots } = input;
5381
+ const { access } = identity.principal;
5382
+ spend(input.proofs.post, "post", { channel });
5383
+ if (roots.some((root) => hasLabels(root.labels))) spend(input.proofs.label, "label", { channel });
5384
+ const { state: actors } = await ctx.session.state(actorsReducer);
5385
+ const seen = seenFor(identity, actors);
5386
+ const blind = !access.readable(channel);
5387
+ const read = { landed: null };
5388
+ const rows = await appendFrom(ctx, async () => {
5389
+ const found = input.again ? await input.again.landed() : null;
5390
+ if (found && "not" in found && found.not !== "made") throw duplicateId();
5391
+ read.landed = found && "tasks" in found ? found.tasks : null;
5392
+ if (read.landed) return {
5393
+ position: 0,
5394
+ events: []
5395
+ };
5396
+ const { position, counts, events: more } = await input.with();
5397
+ let next = position + 1 + (seen ? 1 : 0);
5398
+ const came = more(roots.map((root, at) => {
5399
+ const here = {
5400
+ id: next,
5401
+ thread: root.id
5402
+ };
5403
+ next += 1 + counts[at];
5404
+ return here;
5405
+ }));
5406
+ if (input.again && came[0]?.[0]) came[0][0] = {
5407
+ ...came[0][0],
5408
+ id: input.again.asked
5409
+ };
5410
+ const events = seen ? [seen] : [];
5411
+ for (const [at, root] of roots.entries()) {
5412
+ if (came[at].length !== counts[at]) throw new Error(`a root's append carries the ${counts[at]} events it said, not ${came[at].length}`);
5413
+ events.push({
5414
+ type: "message.posted",
5415
+ id: root.id,
5416
+ payload: {
5417
+ channel,
5418
+ text: root.text,
5419
+ re: null,
5420
+ replyTo: null,
5421
+ thread: root.id,
5422
+ labels: root.labels ?? {},
5423
+ noSync: root.noSync ?? false,
5424
+ by: identity.author,
5425
+ origin: null,
5426
+ from: null,
5427
+ ...root.attachments?.length ? { attachments: root.attachments } : {},
5428
+ ...blind ? { blind: true } : {},
5429
+ ...came[at].length > 0 ? { along: came[at].length } : {}
5430
+ }
5431
+ }, ...came[at]);
5432
+ }
5433
+ return {
5434
+ position,
5435
+ events
5436
+ };
5437
+ });
5438
+ if (read.landed) return read.landed;
5439
+ await untilApplied(ctx, rows);
5440
+ const folded = {
5441
+ byId: {},
5442
+ replies: {}
5443
+ };
5444
+ const ordered = [...rows].sort((a, b) => a.index - b.index);
5445
+ for (const row of ordered) foldMessages(folded, row);
5446
+ const known = knownWith(actors, identity, seen);
5447
+ const posted = ordered.filter((row) => row.type === "message.posted");
5448
+ return Promise.all(posted.map(async (row, at) => {
5449
+ const message = folded.byId[row.index];
5450
+ return shownTo(view$1(message, known, await readerFor(ctx, access, message)), access, roots[at].text);
5451
+ }));
5452
+ }
5453
+ /**
5454
+ * The batch a caller made under an `id`, found by the IDs its events carry, as a post is by its
5455
+ * own: `rootId` names each root's post in turn, and `asked`, when the caller says what it asks
5456
+ * for, the event right after the first one. What's happened to its tasks since makes it no other
5457
+ * batch, and neither does what the middleware made of it: `asked` is of the request as given.
5458
+ */
5459
+ async function landedBatch(ctx, identity, rootId, asked) {
5460
+ const first = await ctx.reads.byEventId(await rootId(0));
5461
+ if (!first) return { not: "made" };
5462
+ const tasks = [];
5463
+ for (let at = 0, landed = first; landed; landed = await ctx.reads.byEventId(await rootId(++at))) {
5464
+ const mine = await landedFor(ctx, identity, landed);
5465
+ if (!mine) return { not: "yours" };
5466
+ tasks.push(mine);
5467
+ }
5468
+ if (asked !== void 0) {
5469
+ const [, made] = await ctx.session.history({
5470
+ gte: first.id,
5471
+ lte: first.id + 1
5472
+ });
5473
+ if (made?.id !== asked) return { not: "asked" };
5474
+ }
5475
+ return { tasks };
5187
5476
  }
5188
5477
  /**
5189
5478
  * A post's view for its writer. One that can't read the channel gets back the
@@ -5218,11 +5507,17 @@ async function unclaimed(ctx, target, thread, access) {
5218
5507
  * slow or stuck, it still succeeds.
5219
5508
  */
5220
5509
  async function untilApplied(ctx, rows) {
5510
+ if (rows.length === 0) return;
5221
5511
  const events = [...rows].sort((a, b) => a.index - b.index);
5222
5512
  const last = events.at(-1).index;
5223
5513
  try {
5224
5514
  let caughtUp = true;
5225
- for (const event of events) if (!(caughtUp = await ctx.reads.tables.applyNext(event))) break;
5515
+ for (const event of events) {
5516
+ if (await ctx.reads.tables.applyNext(event)) continue;
5517
+ if (await ctx.reads.tables.position() >= event.index) continue;
5518
+ caughtUp = false;
5519
+ break;
5520
+ }
5226
5521
  if (caughtUp) return;
5227
5522
  } catch {}
5228
5523
  await ctx.reads.ensure(last, AbortSignal.timeout(LANDED_WAIT_MS)).catch((error) => {
@@ -5238,12 +5533,32 @@ const LANDED_WAIT_MS = 1e4;
5238
5533
  * anywhere on the board, moves it, and it looks again from there.
5239
5534
  */
5240
5535
  async function appendWhile(ctx, holds, events) {
5536
+ return appendFrom(ctx, async () => ({
5537
+ position: await holds(),
5538
+ events
5539
+ }));
5540
+ }
5541
+ /**
5542
+ * As `appendWhile`, for a write whose events depend on what it finds: `look` reads the tables,
5543
+ * throws what refuses the write, and returns what to append with the index its reads reflect. It
5544
+ * looks again, and decides again, each time the board moves on first. Nothing to append appends
5545
+ * nothing.
5546
+ */
5547
+ async function appendFrom(ctx, look) {
5241
5548
  return whileHeadMoves(async () => {
5242
5549
  await ctx.reads.ensure();
5243
- return appendIfLast(ctx.session, await holds(), events);
5550
+ const { position, events } = await look();
5551
+ return events.length === 0 ? [] : appendIfLast(ctx.session, position, events);
5244
5552
  });
5245
5553
  }
5246
5554
  /**
5555
+ * What a look throws when its reads don't all reflect one index: the board moved on under it, so
5556
+ * `whileHeadMoves` has it look again.
5557
+ */
5558
+ const movedOn = () => Object.assign(/* @__PURE__ */ new Error("the board moved on while a write read it"), { code: "LAST_INDEX_MISMATCH" });
5559
+ /** An append that holds an event ID already in the log. */
5560
+ const duplicateEvent = (error) => ["PARTIAL_DUPLICATE_BATCH", "DUPLICATE_EVENT_ID"].includes(error?.code ?? "");
5561
+ /**
5247
5562
  * Runs `attempt`, a look and a conditional append, again each time the board moves on in
5248
5563
  * between, up to `CONDITIONAL_TRIES` times: how every conditional write here looks again.
5249
5564
  */
@@ -5284,17 +5599,29 @@ async function writeEdit(ctx, input) {
5284
5599
  async function commitEdit(ctx, input, message) {
5285
5600
  const { state: actors } = await ctx.session.state(actorsReducer);
5286
5601
  const seen = seenFor(input.identity, actors);
5287
- const events = [...seen ? [seen] : [], {
5288
- type: "message.edited",
5289
- payload: {
5290
- id: message.id,
5291
- thread: message.thread,
5292
- text: input.text,
5293
- by: input.identity.author,
5294
- from: input.from ?? null
5602
+ const events = [
5603
+ ...seen ? [seen] : [],
5604
+ ...metBy(input.introduces, actors, input.identity.actor.id),
5605
+ {
5606
+ type: "message.edited",
5607
+ payload: {
5608
+ id: message.id,
5609
+ thread: message.thread,
5610
+ text: input.text,
5611
+ by: input.identity.author,
5612
+ from: input.from ?? null
5613
+ }
5295
5614
  }
5296
- }];
5297
- await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...events) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), events));
5615
+ ];
5616
+ const { revision } = input;
5617
+ await untilApplied(ctx, message.re === null ? await appendFrom(ctx, async () => {
5618
+ const { position, found } = await asOfNow(ctx, message.id);
5619
+ if (revision !== void 0) atRevision(found, message.id, revision);
5620
+ return {
5621
+ position,
5622
+ events: [...events, ...heldByEdit(found, input.identity)]
5623
+ };
5624
+ }) : revision === void 0 ? await ctx.session.append(...events) : await appendWhile(ctx, revisionIs(ctx, message.id, revision), events));
5298
5625
  }
5299
5626
  /** A message's links, replaced: a platform edit or unfurl changed what it links to. */
5300
5627
  async function writeLinks(ctx, input) {
@@ -5327,16 +5654,72 @@ async function writeDelete(ctx, input) {
5327
5654
  from: input.from ?? null
5328
5655
  }
5329
5656
  }];
5330
- await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...deleted) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), deleted));
5657
+ const { revision } = input;
5658
+ await untilApplied(ctx, message.re === null ? await appendFrom(ctx, async () => {
5659
+ const { position, found } = await asOfNow(ctx, message.id);
5660
+ if (revision !== void 0) atRevision(found, message.id, revision);
5661
+ return {
5662
+ position,
5663
+ events: found?.deleted ? [] : [...canceledByDelete(found, input.identity), ...deleted]
5664
+ };
5665
+ }) : revision === void 0 ? await ctx.session.append(...deleted) : await appendWhile(ctx, revisionIs(ctx, message.id, revision), deleted));
5331
5666
  }
5332
- /** An edit's or a delete's `revision`: no edit or delete since, as of the index the read reflects. */
5333
- const revisionIs = (ctx, id, revision) => async () => {
5667
+ /** A message as the tables have it now, and the index that read reflects. */
5668
+ async function asOfNow(ctx, id) {
5334
5669
  const position = await ctx.reads.tables.position();
5335
- const message = (await ctx.reads.tables.messagesAt([id], position)).get(id);
5670
+ return {
5671
+ position,
5672
+ found: (await ctx.reads.tables.messagesAt([id], position)).get(id)
5673
+ };
5674
+ }
5675
+ /** Refuses an edit or a delete at `revision` when the message has been edited or deleted since. */
5676
+ function atRevision(message, id, revision) {
5336
5677
  const now = message ? message.revision ?? message.id : null;
5337
5678
  if (now !== revision) throw new HttpError(409, "revision_conflict", message?.deleted ? `#${id} was deleted since revision ${revision}` : `#${id} was edited since revision ${revision}: it's at ${now}`);
5679
+ }
5680
+ /** An edit's or a delete's `revision`: no edit or delete since, as of the index the read reflects. */
5681
+ const revisionIs = (ctx, id, revision) => async () => {
5682
+ const { position, found } = await asOfNow(ctx, id);
5683
+ atRevision(found, id, revision);
5338
5684
  return position;
5339
5685
  };
5686
+ /** Why a task is held once its root was edited by someone who doesn't own it. */
5687
+ const EDITED = "its text was edited by someone who does not own the task";
5688
+ /**
5689
+ * The hold an edit of a task's root brings, by anyone but the task's owner: the thread's author when
5690
+ * someone else made it a task, or a platform's edit, whichever principal's sync imported it. The task says what its owner read, so it waits
5691
+ * for them to read it again, and whoever held it has lost it. One that's held or finished stays as it is.
5692
+ */
5693
+ function heldByEdit(root, editor) {
5694
+ const task = root?.task;
5695
+ const owner = task !== void 0 && ownedBy(task, editor) && editor.principal.kind !== "external";
5696
+ if (!root || root.deleted || !task || owner) return [];
5697
+ if (task.state !== "waiting" && task.state !== "ready" && task.state !== "claimed") return [];
5698
+ return [{
5699
+ type: "task.blocked",
5700
+ payload: {
5701
+ id: root.id,
5702
+ thread: root.thread,
5703
+ kind: EDITED_HOLD,
5704
+ reason: EDITED,
5705
+ by: editor.author
5706
+ }
5707
+ }];
5708
+ }
5709
+ /** The cancel a delete of a task's root brings, unless the task has completed or been canceled: before the delete, while the root still wears its labels. */
5710
+ function canceledByDelete(root, deleter) {
5711
+ const task = root?.task;
5712
+ if (!root || !task || task.state === "completed" || task.state === "canceled") return [];
5713
+ return [{
5714
+ type: "task.canceled",
5715
+ payload: {
5716
+ id: root.id,
5717
+ thread: root.thread,
5718
+ reason: "deleted",
5719
+ by: deleter.author
5720
+ }
5721
+ }];
5722
+ }
5340
5723
  async function writeReaction(ctx, input) {
5341
5724
  const message = spent(input.authorized, "react");
5342
5725
  if (message.deleted) throw badRequest("message was deleted", "message_deleted");
@@ -5606,9 +5989,17 @@ const storedGrant = (row) => ({
5606
5989
  * repository's run with what it says of its workflow, branch (main unless it says), and event, or an issuer's token with
5607
5990
  * its claims. A board that verifies tokens itself looks no names up, so a name is a 400.
5608
5991
  */
5609
- function principalNamed(query, team) {
5992
+ function principalNamed(query, team, logins) {
5610
5993
  if (query.user !== void 0) {
5611
- if (query.user.includes("@")) throw badRequest(`this board can't look up ${query.user}: it verifies tokens itself, so name the user by ID`);
5994
+ if (query.user.includes("@")) {
5995
+ if (!logins) throw badRequest(`this board can't look up ${query.user}: it verifies tokens itself, so name the user by ID`);
5996
+ const login = query.user.toLowerCase();
5997
+ return {
5998
+ id: `vercel:user:${login}`,
5999
+ kind: "person",
6000
+ handle: login
6001
+ };
6002
+ }
5612
6003
  return {
5613
6004
  id: `vercel:user:${query.user}`,
5614
6005
  kind: "person",
@@ -5754,7 +6145,7 @@ const namesIssuer = (principals) => principals.some((principal) => principal.kin
5754
6145
  * name an oidc issuer. A removal goes by who a principal is; an add joins one the grant names
5755
6146
  * already. `issuers` are the ones the board's rules trust.
5756
6147
  */
5757
- async function updated(identity, state, { id, add, remove, can }, issuers, accessIn, team) {
6148
+ async function updated(identity, state, { id, add, remove, can }, issuers, accessIn, team, logins) {
5758
6149
  const index = indexOf(id);
5759
6150
  const row = index === null ? void 0 : state.grants[index];
5760
6151
  if (!row) {
@@ -5766,7 +6157,7 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
5766
6157
  const others = grantIssuers(Object.values(state.grants).filter((other) => other.id !== row.id).map(storedGrant));
5767
6158
  let principals = [...row.principals];
5768
6159
  for (const input of remove ?? []) {
5769
- const removal = checkPrincipal(input, [...issuers, ...others], true);
6160
+ const removal = checkPrincipal(input, [...issuers, ...others], true, null, logins);
5770
6161
  const kept = principals.filter((principal) => !removes(removal, principal));
5771
6162
  if (kept.length === principals.length) throw badRequest(`${id} doesn't name that ${removal.kind} principal`, "not_in_grant");
5772
6163
  principals = kept;
@@ -5776,7 +6167,7 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
5776
6167
  ...issuers,
5777
6168
  ...others,
5778
6169
  ...grantIssuers([{ principals }])
5779
- ], false, team);
6170
+ ], false, team, logins);
5780
6171
  const at = principals.findIndex((principal) => joined(added, principal) !== null);
5781
6172
  if (at === -1) principals.push(added);
5782
6173
  else principals[at] = joined(added, principals[at]);
@@ -5809,6 +6200,7 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
5809
6200
  * defaults and the grants.
5810
6201
  */
5811
6202
  function createTrust(options) {
6203
+ const logins = () => options.logins?.() ?? false;
5812
6204
  const accessIn = (principal, grants) => options.accessNow(principal, grants);
5813
6205
  const session = createServer({
5814
6206
  contract: accessContract,
@@ -5829,7 +6221,7 @@ function createTrust(options) {
5829
6221
  const team = await options.team();
5830
6222
  const [row] = await whileHeadMoves(async () => {
5831
6223
  const { state, index } = await latest();
5832
- const checked = checkGrant(body, grantIssuers(Object.values(state.grants).map(storedGrant)), team);
6224
+ const checked = checkGrant(body, grantIssuers(Object.values(state.grants).map(storedGrant)), team, logins());
5833
6225
  const before = Object.values(state.grants).map(storedGrant);
5834
6226
  const after = [...before, checked];
5835
6227
  await mayGrant(identity, { changed: checked }, before, after, accessIn);
@@ -5851,7 +6243,7 @@ function createTrust(options) {
5851
6243
  const team = await options.team();
5852
6244
  const id = await whileHeadMoves(async () => {
5853
6245
  const { state, index } = await latest();
5854
- const event = await updated(identity, state, input, [], accessIn, team);
6246
+ const event = await updated(identity, state, input, [], accessIn, team, logins());
5855
6247
  await session.append.ifLastIndex(index, event);
5856
6248
  return event.payload.id;
5857
6249
  });
@@ -5870,7 +6262,7 @@ function createTrust(options) {
5870
6262
  can: []
5871
6263
  };
5872
6264
  const { id, kind, handle, facts, scope } = identity.principal;
5873
- const principal = named ? principalNamed(query, await options.team()) : {
6265
+ const principal = named ? principalNamed(query, await options.team(), logins()) : {
5874
6266
  id,
5875
6267
  kind,
5876
6268
  handle,
@@ -6311,9 +6703,18 @@ function createReads(tables, session, projection) {
6311
6703
  catchUp();
6312
6704
  if (filter.channels?.length === 0) return {
6313
6705
  threads: [],
6314
- position: await tables.position()
6706
+ position: await tables.position(),
6707
+ ...page.after === void 0 ? { older: null } : {}
6315
6708
  };
6316
6709
  return tables.threads(filter, page);
6710
+ },
6711
+ async roots(filter, page) {
6712
+ catchUp();
6713
+ if (filter.channels?.length === 0) return {
6714
+ threads: [],
6715
+ position: await tables.position()
6716
+ };
6717
+ return tables.roots(filter, page);
6317
6718
  }
6318
6719
  };
6319
6720
  }
@@ -6406,7 +6807,7 @@ function createRegistry(options) {
6406
6807
  /** Vercel Queues delays at most 6 days: a send further out than this goes in hops. */
6407
6808
  const MAX_HOP_MS = 432e6;
6408
6809
  /** A timer that fires this early just waits again; any closer counts as on time. */
6409
- const EARLY_MS = 1e3;
6810
+ const EARLY_MS$1 = 1e3;
6410
6811
  /**
6411
6812
  * Who a schedule sends as: its creator, shown as its principal names it. One made before handles were
6412
6813
  * checked keeps the actor its creator's client named; it sends as what verified that creator instead.
@@ -6600,7 +7001,7 @@ function createSchedules(options) {
6600
7001
  if (deployment !== null && state.takeover !== null && state.takeover.deployment !== deployment) return;
6601
7002
  if (schedule && ctx.attempt > 1 && schedule.sent === n + 1 && schedule.next !== null) return arm("next", id, n + 1, schedule.next);
6602
7003
  if (!schedule || schedule.next !== at || schedule.sent !== n) return;
6603
- if (Date.now() < at - EARLY_MS) return arm("hop", id, n, at);
7004
+ if (Date.now() < at - EARLY_MS$1) return arm("hop", id, n, at);
6604
7005
  if (schedule.re !== null) {
6605
7006
  const root = await writes.reads.message(schedule.re, ctx.signal);
6606
7007
  if (!root || root.deleted) {
@@ -6858,10 +7259,971 @@ function createSchedules(options) {
6858
7259
  }
6859
7260
  };
6860
7261
  }
7262
+ const LEASE_CAP_S = 3600;
7263
+ /** How many owners one claim takes tasks from on this board, beside its caller. */
7264
+ const FROM_MAX = 32;
7265
+ /**
7266
+ * This board's own limits on a task. board() checks a request's shape and leaves how much a
7267
+ * backend holds to the backend, so these are checked here: what's over one is refused as a
7268
+ * misshapen request is, 400 `invalid_request`, before anything is read or written.
7269
+ */
7270
+ const taskLimits = {
7271
+ lease(seconds) {
7272
+ if (seconds !== void 0 && !(seconds >= 30 && seconds <= 3600)) throw badRequest(`lease: a lease is 30 to ${LEASE_CAP_S} seconds`);
7273
+ },
7274
+ needs(refs) {
7275
+ if (new Set(refs).size > 20) throw badRequest(`needs: a task waits for at most 20 tasks`);
7276
+ },
7277
+ note(what, note) {
7278
+ if (typeof note === "string" && note.length > 1e3) throw badRequest(`${what}: a task's ${what} is at most ${TASK_NOTE_MAX.toLocaleString("en-US")} characters`);
7279
+ },
7280
+ kind(kind) {
7281
+ if (kind !== void 0 && !TaskHoldKind.safeParse(kind).success) throw badRequest("kind: a kind is up to 64 lowercase letters, numbers, and _.-");
7282
+ },
7283
+ from(owners) {
7284
+ if ((owners?.length ?? 0) > FROM_MAX) throw badRequest(`from: a claim takes tasks from at most ${FROM_MAX} owners`);
7285
+ },
7286
+ /** A batch: how many tasks this board makes in one append, which its sender splits on, and of each what one task holds. */
7287
+ batch(tasks) {
7288
+ if (tasks.length > 100) throw batchTooLarge(tasks.length, 100);
7289
+ for (const [at, task] of tasks.entries()) {
7290
+ if (task.key !== void 0 && task.key.length > 64) throw badRequest(`tasks.${at}.key: a task's key is at most 64 characters`);
7291
+ if (new Set(task.needs?.map((need) => typeof need === "string" ? `id ${need}` : `key ${need.key}`)).size > 20) throw badRequest(`tasks.${at}.needs: a task waits for at most 20 tasks`);
7292
+ }
7293
+ }
7294
+ };
7295
+ /** A timer that fires this early waits again; any closer counts as on time. */
7296
+ const EARLY_MS = 1e3;
7297
+ /** Roots a scan of tasks reads at a time. */
7298
+ const PAGE = 500;
7299
+ const conflict = (code, message) => new HttpError(409, code, message);
7300
+ const notATask = (id) => notFound(`#${id} isn't a task`, "not_a_task");
7301
+ /** 128 random bits, base64url: a claim's secret, which the board answers once and keeps only the hash of. */
7302
+ const newToken = () => randomBytes(16).toString("base64url");
7303
+ const hashOf = (token) => createHash("sha256").update(token).digest("hex");
7304
+ /** Whether `token` is the secret `hash` was made from, compared without saying how much of it matched. */
7305
+ const hashes = (token, hash) => timingSafeEqual(Buffer.from(hashOf(token), "hex"), Buffer.from(hash, "hex"));
7306
+ /** A lease asked for in seconds, as this board gives it, in milliseconds. */
7307
+ const leaseOf = (seconds) => Math.min(seconds ?? 900, LEASE_CAP_S) * 1e3;
7308
+ /** Whether a task's claim has run out its lease: it's claimable at once, whatever its label still says. */
7309
+ const lapsed = (task, at) => task.state === "claimed" && Date.parse(task.claim.until) <= at;
7310
+ /** A task's state as claims and lists take it: a claim whose lease has run out is ready. */
7311
+ const stateNow = (task, at) => lapsed(task, at) ? "ready" : task.state;
7312
+ const finished = (task) => task.state === "completed" || task.state === "failed" || task.state === "canceled";
7313
+ /** Whether `value` is shaped like an ID, `<where it's from>:<who>`, as every principal's and actor's is. What it names is a credential's to say, never a client's. */
7314
+ const isId = (value) => /^[^\s:]+:\S+$/.test(value);
7315
+ /** Waits `ms`, or until `signal` aborts, whichever is first. */
7316
+ const paused = (ms, signal) => new Promise((resolve) => {
7317
+ const done = () => {
7318
+ clearTimeout(timer);
7319
+ signal.removeEventListener("abort", done);
7320
+ resolve();
7321
+ };
7322
+ const timer = setTimeout(done, ms);
7323
+ signal.addEventListener("abort", done, { once: true });
7324
+ });
7325
+ /** The profile part of an actor ID, as the board writes one: lowercase. */
7326
+ const PROFILE = /^[a-z][a-z0-9-]{0,31}$/;
7327
+ /**
7328
+ * The actor a task is assigned to: one of its owner's (`<owner>+<profile>`), or null for anyone who
7329
+ * may claim it. Another principal's actor is refused: a profile is the owner's own word for which of
7330
+ * its agents does what.
7331
+ */
7332
+ function ownActor(owner, actor) {
7333
+ if (actor === void 0 || actor === null) return null;
7334
+ if (!actor.startsWith(`${owner}+`) || !PROFILE.test(actor.slice(owner.length + 1))) throw badRequest(`for: a task is assigned to one of its owner's profiles, ${owner}+<profile>, got ${actor}`);
7335
+ return actor;
7336
+ }
7337
+ /**
7338
+ * Tasks on a local board: a thread with a state, kept on its root. Every write here is one
7339
+ * conditional append: it reads the task as the tables have it, decides, and lands only while that
7340
+ * read is still the log's last word, so of writes that race, one lands and the rest look again.
7341
+ * A claim's lease is timed outside the board log, which holds only what came of it.
7342
+ */
7343
+ function createTasks(options) {
7344
+ let bound = null;
7345
+ const writes = () => {
7346
+ if (!bound) throw new Error("tasks used before the board bound them");
7347
+ return bound;
7348
+ };
7349
+ /**
7350
+ * A claim's lease, timed: when it's due, the task's claim expires if it's still that claim and
7351
+ * its lease wasn't renewed. A renewal arms its own timer, so one for an earlier end fires into
7352
+ * nothing.
7353
+ */
7354
+ async function due(context) {
7355
+ const ctx = writes();
7356
+ const { id, epoch, at } = context.event.payload;
7357
+ const read = { early: null };
7358
+ await untilApplied(ctx, await appendFrom(ctx, async () => {
7359
+ read.early = null;
7360
+ const position = await ctx.reads.tables.position();
7361
+ const root = (await ctx.reads.tables.messagesAt([id], position)).get(id);
7362
+ const task = root?.task;
7363
+ if (!root || !task || task.state !== "claimed" || task.epoch !== epoch) return {
7364
+ position,
7365
+ events: []
7366
+ };
7367
+ const until = Date.parse(task.claim.until);
7368
+ if (until - Date.now() > EARLY_MS) {
7369
+ if (until === at) read.early = task.claim.until;
7370
+ return {
7371
+ position,
7372
+ events: []
7373
+ };
7374
+ }
7375
+ return {
7376
+ position,
7377
+ events: [{
7378
+ type: "task.expired",
7379
+ payload: {
7380
+ id,
7381
+ thread: root.thread,
7382
+ epoch
7383
+ }
7384
+ }]
7385
+ };
7386
+ }));
7387
+ if (read.early !== null) await arm(id, epoch, read.early, `again-${context.event.index}`);
7388
+ }
7389
+ const expiring = consumer({
7390
+ contract: leasesContract,
7391
+ name: "board-leases",
7392
+ types: ["lease.due"],
7393
+ lane: ({ event }) => `task:${event.payload.id}`
7394
+ }).run(due);
7395
+ const server = createServer({
7396
+ contract: leasesContract,
7397
+ ...options.store ? { store: options.store } : {},
7398
+ ...options.scheduler ? { scheduler: options.scheduler } : {},
7399
+ consumers: [expiring]
7400
+ });
7401
+ const leases = server.session(LEASES_SESSION);
7402
+ /**
7403
+ * Arms the timer for a claim's lease. Without a scheduler there's none: a claim still checks the
7404
+ * clock, so a lease that ran out is claimable, and its label says so once someone claims it. One
7405
+ * that can't be armed is the same, so the claim that landed still answers.
7406
+ */
7407
+ async function arm(id, epoch, until, again) {
7408
+ if (!options.scheduler) return;
7409
+ const at = Date.parse(until);
7410
+ const name = `lease-${id}-${epoch}-${at}${again ? `-${again}` : ""}`;
7411
+ await leases.schedule(name, { at: new Date(at) }, {
7412
+ type: "lease.due",
7413
+ payload: {
7414
+ id,
7415
+ epoch,
7416
+ at
7417
+ }
7418
+ }).catch((error) => {
7419
+ console.warn(`[board] no timer for #${id}'s lease, which a claim still ends:`, error.message);
7420
+ });
7421
+ }
7422
+ /** A message the caller may read, as the tables have it: a 404 otherwise, as if it weren't there. */
7423
+ async function readable(access, id) {
7424
+ const message = await writes().reads.message(id);
7425
+ if (!message || !access.readable(message.channel)) throw notFound(`message not found: #${id}`, "message_not_found");
7426
+ return message;
7427
+ }
7428
+ /** A task the caller may read, by its root's ID. Who it is and where it is never change, so what a caller may do to it is checked on this read. */
7429
+ async function taskOf(access, id) {
7430
+ const message = await readable(access, id);
7431
+ if (!message.task) throw notATask(id);
7432
+ return message;
7433
+ }
7434
+ /** `message` as `identity` sees it. */
7435
+ async function shown(identity, message) {
7436
+ const ctx = writes();
7437
+ const { state: actors } = await ctx.session.state(actorsReducer);
7438
+ return view$1(message, actors, await ctx.reads.reader(identity.principal.access, [message]));
7439
+ }
7440
+ /**
7441
+ * One write to the message `id`: `decide` gets it as it is at the index the write will land after,
7442
+ * throws what refuses the write, and returns what to append. Answers the message as the write left
7443
+ * it: as it was, when there was nothing to append.
7444
+ */
7445
+ async function change(identity, id, decide) {
7446
+ const ctx = writes();
7447
+ const seen = seenFor(identity, (await ctx.session.state(actorsReducer)).state);
7448
+ const read = {};
7449
+ const rows = await appendFrom(ctx, async () => {
7450
+ const position = await ctx.reads.tables.position();
7451
+ const found = (await ctx.reads.tables.messagesAt([id], position)).get(id);
7452
+ if (!found) throw notFound(`message not found: #${id}`, "message_not_found");
7453
+ read.before = found;
7454
+ const events = await decide(found, position);
7455
+ return {
7456
+ position,
7457
+ events: events.length > 0 && seen ? [seen, ...events] : events
7458
+ };
7459
+ });
7460
+ await untilApplied(ctx, rows);
7461
+ return after(read.before, rows);
7462
+ }
7463
+ /** `message` once `rows`, a write's own events, are applied to it: what the write answers, whatever lands next. */
7464
+ function after(message, rows) {
7465
+ const state = {
7466
+ byId: { [message.id]: structuredClone(message) },
7467
+ replies: {}
7468
+ };
7469
+ for (const row of [...rows].sort((a, b) => a.index - b.index)) foldMessages(state, row);
7470
+ return state.byId[message.id];
7471
+ }
7472
+ /** `change`, for a write to a task: `decide` gets its root. */
7473
+ const changeTask = (identity, id, decide) => change(identity, id, (found, position) => {
7474
+ if (!found.task) throw notATask(id);
7475
+ return decide(found, position);
7476
+ });
7477
+ /**
7478
+ * Whether the caller changes a task as its owner: `manage` in its channel, or the owner while it
7479
+ * may still write there. A principal ID is coarser than access (a proxy narrows one token with
7480
+ * `x-board-can`), so one narrowed to reading doesn't cancel its principal's tasks. And a
7481
+ * principal's profiles share its credential (a sandbox's agent writes as one), so, as with a
7482
+ * message, a profile changes only the tasks it made, and the principal itself any of them:
7483
+ * otherwise one profile would assign itself what was another's.
7484
+ */
7485
+ function owns(identity, root) {
7486
+ const { access } = identity.principal;
7487
+ if (access.can("manage", root.channel)) return;
7488
+ if (ownedBy(root.task, identity) && (access.can("post", root.channel) || access.can("label", root.channel))) return;
7489
+ throw new HttpError(403, "task_not_owned", `#${root.id} is someone else's task: its owner as itself, the profile that made it, or manage in ${root.channel}, changes it`);
7490
+ }
7491
+ /** Refuses a write whose claim is over: released, settled, held, taken over, or past its lease. It never says who holds the task now. */
7492
+ function fenced(root, proof) {
7493
+ const { task } = root;
7494
+ if (!(task.state === "claimed" && task.epoch === proof.epoch && Date.parse(task.claim.until) > Date.now() && hashes(proof.token, task.claim.token))) throw conflict("claim_lost", `this claim on #${root.id} is over: claim it again`);
7495
+ }
7496
+ /**
7497
+ * Whether `identity` is who a task is assigned to: its owner's principal, writing as that actor.
7498
+ * The actor ID alone doesn't say whose it is. An ID is a principal's and then `+<profile>`, and
7499
+ * another principal's own ID can end that way, so the two can be one string.
7500
+ */
7501
+ const assignedTo = (task, identity) => task.for === identity.actor.id && task.owner === identity.principal.id;
7502
+ /** Refuses a claim of a task that can't be claimed now, by `identity`. */
7503
+ function claimable(root, identity) {
7504
+ const { task } = root;
7505
+ if (task.state === "waiting") throw conflict("task_waiting", `#${root.id} waits for ${task.needs.map((need) => `#${need}`).join(", ")}`);
7506
+ if (task.state === "blocked") throw conflict("task_blocked", `#${root.id} is held for a person: ${task.blocked.reason}`);
7507
+ if (finished(task)) throw conflict("task_finished", `#${root.id} is ${task.state}`);
7508
+ if (task.for !== null && !assignedTo(task, identity)) throw conflict("task_assigned", `#${root.id} is assigned to ${task.for}`);
7509
+ if (task.state === "claimed" && !lapsed(task, Date.now())) throw conflict("task_claimed", `#${root.id} is claimed until ${task.claim.until}`);
7510
+ }
7511
+ /**
7512
+ * A claim of a task as it stands, by `identity`: the events, and what the claim answers. A claim
7513
+ * whose lease ran out expires in the same append, so the log says what happened to it.
7514
+ */
7515
+ function claiming(root, task, identity, lease, token) {
7516
+ const about = {
7517
+ id: root.id,
7518
+ thread: root.thread
7519
+ };
7520
+ const epoch = (task?.epoch ?? 0) + 1;
7521
+ const until = new Date(Date.now() + leaseOf(lease)).toISOString();
7522
+ return {
7523
+ events: [...task?.state === "claimed" ? [{
7524
+ type: "task.expired",
7525
+ payload: {
7526
+ ...about,
7527
+ epoch: task.epoch
7528
+ }
7529
+ }] : [], {
7530
+ type: "task.claimed",
7531
+ payload: {
7532
+ ...about,
7533
+ epoch,
7534
+ until,
7535
+ token: hashOf(token),
7536
+ by: identity.author
7537
+ }
7538
+ }],
7539
+ claim: {
7540
+ epoch,
7541
+ token,
7542
+ until
7543
+ }
7544
+ };
7545
+ }
7546
+ /**
7547
+ * The tasks `refs` name, as of `position`, and whether they've all completed. One that isn't a
7548
+ * task, or that the caller can't read, is refused alike, so `needs` says nothing of what's out of
7549
+ * sight. Needs never change, and nothing can need a thread before it's a task, so the only cycle
7550
+ * there could be is a task that waits for itself: `self` isn't a task yet, so it's refused as any
7551
+ * thread that isn't one, and named here only so the refusal says why. One that was canceled is
7552
+ * refused too: it can never complete, so a task that waited for it would wait for good, and its
7553
+ * maker hears now. A failed one may yet be reopened, so it's still something to wait for.
7554
+ */
7555
+ async function needsAt(access, refs, position, self) {
7556
+ const named = namedNeeds(refs, self);
7557
+ return needsAmong(access, named, named.size === 0 ? /* @__PURE__ */ new Map() : await writes().reads.tables.messagesAt([...named.keys()], position));
7558
+ }
7559
+ const invalidNeed = (value, why) => badRequest(`needs: #${value} ${why}`, "invalid_needs");
7560
+ /** The messages `refs` name, each by the ref that named it: one that names none, or `self`, is refused. */
7561
+ function namedNeeds(refs, self) {
7562
+ const named = /* @__PURE__ */ new Map();
7563
+ for (const value of refs ?? []) {
7564
+ const id = indexOf$1(value);
7565
+ if (id === null || id === 0) throw invalidNeed(value, "isn't a task");
7566
+ if (id === self) throw invalidNeed(value, "is the task itself: it can't wait for itself");
7567
+ named.set(id, value);
7568
+ }
7569
+ return named;
7570
+ }
7571
+ /** The tasks `named` names among `found`, the messages read for them, and whether they've all completed. */
7572
+ function needsAmong(access, named, found) {
7573
+ for (const [id, value] of named) {
7574
+ const need = found.get(id);
7575
+ if (!need?.task || !access.readable(need.channel)) throw invalidNeed(value, "isn't a task");
7576
+ if (need.task.state === "canceled") throw invalidNeed(value, "was canceled: it can never complete");
7577
+ }
7578
+ const ids = [...named.keys()];
7579
+ return {
7580
+ ids,
7581
+ completed: ids.every((id) => found.get(id).task.state === "completed")
7582
+ };
7583
+ }
7584
+ /**
7585
+ * Refuses prerequisites that would make task `id` wait for itself: one that waits for it already,
7586
+ * through however many tasks. A new task can't be waited for, so only a change of what a task
7587
+ * needs can close a cycle, and only with a prerequisite it adds: one the task keeps was looked
7588
+ * behind when it was added, and whatever came to wait behind it since was checked as it did. So
7589
+ * it walks what the `added` ones need, and what those need, a level a read, and gives up past
7590
+ * `NEEDS_WALK_MAX` tasks: a change it can't check is refused too. One that only drops some walks
7591
+ * nothing.
7592
+ *
7593
+ * It follows no completed task's needs that `access` reads. A task completes by a claim, which
7594
+ * it takes only once all it needs has completed, and neither it nor they change after: completed
7595
+ * is for good, and a finished task's needs can't be changed. So everything behind a completed
7596
+ * task has completed, and task `id`, which hasn't, isn't there. Finished work behind a
7597
+ * prerequisite, however much, is never too much to check. One the caller can't read is followed
7598
+ * all the same, completed or not: the walk reads tasks out of the caller's sight, as it must to
7599
+ * find a cycle, so where it stops, and whether it gets past `NEEDS_WALK_MAX`, must depend on
7600
+ * nothing the caller can't see. A canceled task is followed: it may have waited for anything.
7601
+ */
7602
+ async function acyclic(access, id, added, position) {
7603
+ const invalid = (need, why) => badRequest(`needs: #${need} ${why}`, "invalid_needs");
7604
+ /** Each task the walk reached, by the added prerequisite it reached it from. */
7605
+ const from = new Map(added.map((need) => [need, need]));
7606
+ for (let level = [...added]; level.length > 0;) {
7607
+ const found = await writes().reads.tables.messagesAt(level, position);
7608
+ const next = [];
7609
+ for (const at of level) {
7610
+ const message = found.get(at);
7611
+ const task = message?.task;
7612
+ if (!task || task.state === "completed" && access.readable(message.channel)) continue;
7613
+ for (const need of task.needs) {
7614
+ if (need === id) throw invalid(from.get(at), `waits for #${id} already: they would wait for each other`);
7615
+ if (from.has(need)) continue;
7616
+ from.set(need, from.get(at));
7617
+ next.push(need);
7618
+ }
7619
+ }
7620
+ if (from.size > 500) throw invalid(added[0], `has more than 500 tasks behind it and the others: too many to check that none waits for #${id}`);
7621
+ level = next;
7622
+ }
7623
+ }
7624
+ /** Whether every task `task` waits for has completed, as of `position`, leaving out `but`, which is completing now. */
7625
+ async function satisfied(task, position, but) {
7626
+ const ids = task.needs.filter((id) => id !== but);
7627
+ if (ids.length === 0) return true;
7628
+ const found = await writes().reads.tables.messagesAt(ids, position);
7629
+ return ids.every((id) => found.get(id)?.task?.state === "completed");
7630
+ }
7631
+ /** Every root that wears `board.task` as one of `states` and matches `filter`, oldest first, all as of `position`. */
7632
+ async function* rootsAt(filter, states, position) {
7633
+ const labels = [...filter.labels ?? [], {
7634
+ key: TASK_LABEL,
7635
+ values: states
7636
+ }];
7637
+ for (let after = 0;;) {
7638
+ const page = await writes().reads.tables.roots({
7639
+ ...filter,
7640
+ labels
7641
+ }, {
7642
+ after,
7643
+ limit: PAGE
7644
+ });
7645
+ if (page.position !== position) throw movedOn();
7646
+ for (const { root } of page.threads) if (root.task) yield root;
7647
+ if (page.threads.length < PAGE) return;
7648
+ after = page.threads.at(-1).root.id;
7649
+ }
7650
+ }
7651
+ /** `task.ready` for each task that waited only for `id`, which is completing: its dependents, in the same append. */
7652
+ async function readied(id, position) {
7653
+ const events = [];
7654
+ for await (const root of rootsAt({}, ["waiting"], position)) if (root.task.needs.includes(id) && await satisfied(root.task, position, id)) events.push({
7655
+ type: "task.ready",
7656
+ payload: {
7657
+ id: root.id,
7658
+ thread: root.thread
7659
+ }
7660
+ });
7661
+ return events;
7662
+ }
7663
+ /**
7664
+ * `filter`, narrowed to the channels where `access` gives `permission` among those the log has,
7665
+ * and the index that list reflects. One that gives it everywhere needs nothing more.
7666
+ */
7667
+ async function within(filter, access, permission) {
7668
+ if (access.everywhere(permission)) return {
7669
+ filter,
7670
+ through: Number.POSITIVE_INFINITY
7671
+ };
7672
+ const { state, index } = await writes().session.state(channelsReducer);
7673
+ const { channel, ...rest } = filter;
7674
+ const inside = (path) => !channel || path === channel.path || channel.subtree && path.startsWith(`${channel.path}/`);
7675
+ return {
7676
+ filter: {
7677
+ ...rest,
7678
+ channels: Object.keys(state).filter((path) => inside(path) && access.can(permission, path))
7679
+ },
7680
+ through: index
7681
+ };
7682
+ }
7683
+ /** The IDs a handle or an ID names, itself included: an owner or an assignee the board has yet to see write is still found by its ID. */
7684
+ async function named(value) {
7685
+ const who = whoIs(value, (await writes().session.state(actorsReducer)).state);
7686
+ return /* @__PURE__ */ new Set([
7687
+ value,
7688
+ ...who.actors,
7689
+ ...who.principals
7690
+ ]);
7691
+ }
7692
+ /**
7693
+ * The owner a claim's `from` names: the principal with that ID. A task's text is instructions for
7694
+ * whoever claims it, so whose it takes is never a handle's to say: a handle is how someone shows,
7695
+ * and several can show the same, one a client picked and one a credential gave alike (two projects
7696
+ * on different teams share a name). An ID is one principal's alone, whether or not the board has
7697
+ * seen it write as itself: one that only ever wrote through a profile owns its tasks all the same.
7698
+ */
7699
+ function ownerFrom(value) {
7700
+ if (isId(value)) return value;
7701
+ throw badRequest(`from: ${value} is a handle, which several can share: name the owner by ID`, "invalid_from");
7702
+ }
7703
+ /** A claim of the oldest ready task there that the caller takes, or null when there's none now. */
7704
+ async function claimNext(identity, input, signal) {
7705
+ const ctx = writes();
7706
+ const { principal, actor } = identity;
7707
+ const subtree = input.channel.endsWith("/");
7708
+ const channel = {
7709
+ path: subtree ? input.channel.slice(0, -1) : input.channel,
7710
+ subtree
7711
+ };
7712
+ if (!subtree) authorize(principal.access, "label", channel.path);
7713
+ else if (!principal.access.anywhere("label")) throw forbidden$1("this token can't label anywhere, so it can't claim a task");
7714
+ const { filter } = await within({
7715
+ channel,
7716
+ labels: Object.entries(input.label ?? {}).map(([key, value]) => ({
7717
+ key,
7718
+ values: [value]
7719
+ }))
7720
+ }, principal.access, "label");
7721
+ if (filter.channels?.length === 0) return null;
7722
+ const owners = /* @__PURE__ */ new Set([principal.id]);
7723
+ for (const value of input.from ?? []) owners.add(ownerFrom(value));
7724
+ const seen = seenFor(identity, (await ctx.session.state(actorsReducer)).state);
7725
+ const token = newToken();
7726
+ const read = { taken: null };
7727
+ const rows = await appendFrom(ctx, async () => {
7728
+ read.taken = null;
7729
+ const position = await ctx.reads.tables.position();
7730
+ const now = Date.now();
7731
+ let pool = null;
7732
+ let mine = null;
7733
+ for await (const root of rootsAt(filter, ["ready", "claimed"], position)) {
7734
+ const { task } = root;
7735
+ if (stateNow(task, now) !== "ready") continue;
7736
+ if (assignedTo(task, identity)) {
7737
+ mine = root;
7738
+ break;
7739
+ }
7740
+ if (task.for === null && pool === null && owners.has(task.owner)) pool = root;
7741
+ }
7742
+ const root = mine ?? pool;
7743
+ if (!root || signal.aborted) return {
7744
+ position,
7745
+ events: []
7746
+ };
7747
+ const { events, claim } = claiming(root, root.task, identity, input.lease, token);
7748
+ read.taken = {
7749
+ root,
7750
+ claim
7751
+ };
7752
+ return {
7753
+ position,
7754
+ events: seen ? [seen, ...events] : events
7755
+ };
7756
+ });
7757
+ if (read.taken === null) return null;
7758
+ const { root, claim } = read.taken;
7759
+ await untilApplied(ctx, rows);
7760
+ await arm(root.id, claim.epoch, claim.until);
7761
+ return {
7762
+ root: after(root, rows),
7763
+ claim
7764
+ };
7765
+ }
7766
+ return {
7767
+ server,
7768
+ bind: (binding) => {
7769
+ bound = binding.writes;
7770
+ },
7771
+ /**
7772
+ * What makes a new thread a task, to append with its root: `task.created`, `task.ready` when
7773
+ * the tasks it needs have all completed, and its claim when it asks for one. `claimed(id)` is
7774
+ * what that claim answers once root `id` landed: null for a task made without one, or one this
7775
+ * request didn't make (a retry of a post that landed gets the post back, and no claim).
7776
+ */
7777
+ starting(identity, input) {
7778
+ const { principal, actor, author } = identity;
7779
+ const assigned = ownActor(principal.id, input.for);
7780
+ if (input.claim) authorize(principal.access, "label", input.channel);
7781
+ const token = newToken();
7782
+ const along = async () => {
7783
+ const position = await writes().reads.tables.position();
7784
+ const needs = await needsAt(principal.access, input.needs, position, null);
7785
+ const waits = needs.ids.length > 0 && !needs.completed;
7786
+ if (input.claim && waits) throw conflict("task_waiting", `the task would wait for ${needs.ids.map((id) => `#${id}`).join(", ")}: nothing was made`);
7787
+ if (input.claim && assigned !== null && assigned !== actor.id) throw conflict("task_assigned", `the task would be assigned to ${assigned}: nothing was made`);
7788
+ return {
7789
+ position,
7790
+ events: (root) => {
7791
+ const about = {
7792
+ id: root.id,
7793
+ thread: root.thread
7794
+ };
7795
+ const events = [{
7796
+ type: "task.created",
7797
+ payload: {
7798
+ ...about,
7799
+ needs: needs.ids,
7800
+ for: assigned,
7801
+ by: author
7802
+ }
7803
+ }];
7804
+ if (needs.ids.length > 0 && !waits) events.push({
7805
+ type: "task.ready",
7806
+ payload: about
7807
+ });
7808
+ if (input.claim) events.push(...claiming(root, null, identity, input.lease, token).events);
7809
+ return events;
7810
+ }
7811
+ };
7812
+ };
7813
+ const claimed = async (id) => {
7814
+ if (!input.claim) return null;
7815
+ const held = (await writes().reads.message(id))?.task;
7816
+ if (!held?.claim || !hashes(token, held.claim.token)) return null;
7817
+ await arm(id, held.epoch, held.claim.until);
7818
+ return {
7819
+ epoch: held.epoch,
7820
+ token,
7821
+ until: held.claim.until
7822
+ };
7823
+ };
7824
+ return {
7825
+ along,
7826
+ claimed
7827
+ };
7828
+ },
7829
+ /**
7830
+ * What makes several new threads tasks, to append with their roots, all in one write: for each,
7831
+ * `task.created`, and `task.ready` when it waits only for tasks that were there and have all
7832
+ * completed. A task waits for the batch's others by their `key`, wherever they come in it, and
7833
+ * those are new, so it waits. Refused before anything is read: an assignee that isn't its
7834
+ * owner's, a `key` two tasks have or none has, and tasks that wait for each other.
7835
+ */
7836
+ startingMany(identity, tasks) {
7837
+ const { principal, author } = identity;
7838
+ const assigned = tasks.map((task) => ownActor(principal.id, task.for));
7839
+ const plan = batchPlan(tasks);
7840
+ if ("problem" in plan) throw badRequest(`needs: ${plan.problem}`, "invalid_needs");
7841
+ const { inside } = plan;
7842
+ const named = tasks.map((task) => namedNeeds((task.needs ?? []).filter((need) => typeof need === "string"), null));
7843
+ const outside = [...new Set(named.flatMap((needs) => [...needs.keys()]))];
7844
+ return async () => {
7845
+ const position = await writes().reads.tables.position();
7846
+ const found = outside.length === 0 ? /* @__PURE__ */ new Map() : await writes().reads.tables.messagesAt(outside, position);
7847
+ const needs = named.map((refs) => needsAmong(principal.access, refs, found));
7848
+ const readied = needs.map(({ ids, completed }, at) => ids.length > 0 && completed && inside[at].length === 0);
7849
+ return {
7850
+ position,
7851
+ counts: readied.map((ready) => ready ? 2 : 1),
7852
+ events: (roots) => roots.map((root, at) => {
7853
+ const about = {
7854
+ id: root.id,
7855
+ thread: root.thread
7856
+ };
7857
+ const waitsFor = [...needs[at].ids, ...inside[at].map((other) => roots[other].id)];
7858
+ return [{
7859
+ type: "task.created",
7860
+ payload: {
7861
+ ...about,
7862
+ needs: waitsFor,
7863
+ for: assigned[at],
7864
+ by: author
7865
+ }
7866
+ }, ...readied[at] ? [{
7867
+ type: "task.ready",
7868
+ payload: about
7869
+ }] : []];
7870
+ })
7871
+ };
7872
+ };
7873
+ },
7874
+ /**
7875
+ * Makes the thread rooted at `id` a task, as it is: `label` in its channel, and the caller's
7876
+ * principal owns it. A reply names no task, and neither does a root that's gone.
7877
+ */
7878
+ async adopt(identity, id, input) {
7879
+ const { principal, actor, author } = identity;
7880
+ await authorizeMessage(writes(), principal.access, "label", id);
7881
+ const assigned = ownActor(principal.id, input.for);
7882
+ const token = newToken();
7883
+ const made = { claim: null };
7884
+ const root = await change(identity, id, async (found, position) => {
7885
+ made.claim = null;
7886
+ if (found.re !== null) throw badRequest(`#${id} is a reply: a task is a thread, so name its root, #${found.re}`);
7887
+ if (found.deleted) throw badRequest("message was deleted", "message_deleted");
7888
+ if (found.task) throw conflict("already_a_task", `#${id} is a task already`);
7889
+ const needs = await needsAt(principal.access, input.needs, position, id);
7890
+ const waits = needs.ids.length > 0 && !needs.completed;
7891
+ if (input.claim && waits) throw conflict("task_waiting", `#${id} would wait for ${needs.ids.map((need) => `#${need}`).join(", ")}: it wasn't made a task`);
7892
+ if (input.claim && assigned !== null && assigned !== actor.id) throw conflict("task_assigned", `#${id} would be assigned to ${assigned}: it wasn't made a task`);
7893
+ const about = {
7894
+ id,
7895
+ thread: found.thread
7896
+ };
7897
+ const events = [{
7898
+ type: "task.created",
7899
+ payload: {
7900
+ ...about,
7901
+ needs: needs.ids,
7902
+ for: assigned,
7903
+ by: author
7904
+ }
7905
+ }];
7906
+ if (needs.ids.length > 0 && !waits) events.push({
7907
+ type: "task.ready",
7908
+ payload: about
7909
+ });
7910
+ if (input.claim) {
7911
+ const claimed = claiming(found, null, identity, input.lease, token);
7912
+ events.push(...claimed.events);
7913
+ made.claim = claimed.claim;
7914
+ }
7915
+ return events;
7916
+ });
7917
+ const { claim } = made;
7918
+ if (claim) await arm(id, claim.epoch, claim.until);
7919
+ return {
7920
+ task: await shown(identity, root),
7921
+ ...claim ? { claim } : {}
7922
+ };
7923
+ },
7924
+ /** Tasks the caller reads, oldest first, a page at a time. */
7925
+ async list(identity, query) {
7926
+ const ctx = writes();
7927
+ const { principal, actor } = identity;
7928
+ const { state: actors } = await ctx.session.state(actorsReducer);
7929
+ const wanted = query.state ?? "open";
7930
+ const states = wanted === "all" ? null : wanted === "open" ? OPEN_TASK_STATES : wanted === "ready" ? ["ready", "claimed"] : [wanted];
7931
+ const base = toMessageFilter({
7932
+ ...query.channel !== void 0 ? { channel: query.channel } : {},
7933
+ ...query.by !== void 0 ? { by: query.by } : {},
7934
+ ...query.label ? { label: query.label } : {}
7935
+ }, {
7936
+ me: {
7937
+ id: actor.id,
7938
+ handle: actor.handle
7939
+ },
7940
+ actors,
7941
+ access: principal.access
7942
+ });
7943
+ const { filter, through } = await within({
7944
+ ...base,
7945
+ labels: [...base.labels ?? [], {
7946
+ key: TASK_LABEL,
7947
+ values: states
7948
+ }]
7949
+ }, principal.access, "read");
7950
+ const owners = query.owner === void 0 ? null : await named(query.owner);
7951
+ const assignees = query.for === void 0 ? null : await named(query.for);
7952
+ const needed = query.needs === void 0 ? null : indexOf$1(query.needs) ?? -1;
7953
+ const now = Date.now();
7954
+ const matches = ({ task }) => (wanted === "all" || wanted === "open" || stateNow(task, now) === wanted) && (owners === null || owners.has(task.owner)) && (assignees === null || task.for !== null && assignees.has(task.for)) && (needed === null || task.needs.includes(needed));
7955
+ const limit = query.limit ?? 50;
7956
+ const found = [];
7957
+ let last = 0;
7958
+ if (query.after !== void 0) {
7959
+ const at = indexOf$1(query.after);
7960
+ if (at === null) throw badRequest(`${query.after} isn't a cursor or a message ID on this board`, "invalid_cursor");
7961
+ last = at;
7962
+ }
7963
+ let position = await ctx.reads.position();
7964
+ scan: for (let more = filter.channels?.length !== 0; more;) {
7965
+ const page = await ctx.reads.roots(filter, {
7966
+ after: last,
7967
+ limit: PAGE
7968
+ });
7969
+ position = page.position;
7970
+ more = page.threads.length === PAGE;
7971
+ for (const thread of page.threads) {
7972
+ last = thread.root.id;
7973
+ if (thread.root.task && matches(thread.root)) found.push(thread);
7974
+ if (found.length === limit) break scan;
7975
+ }
7976
+ }
7977
+ const cursor = found.length === limit ? last : Math.max(last, Math.min(position, through));
7978
+ const reader = await ctx.reads.reader(principal.access, found.flatMap((t) => t.last ? [t.root, t.last] : [t.root]));
7979
+ return {
7980
+ tasks: found.map((t) => ({
7981
+ message: view$1(t.root, actors, reader),
7982
+ replies: t.replies,
7983
+ last: t.last && view$1(t.last, actors, reader)
7984
+ })),
7985
+ cursor: ref(cursor)
7986
+ };
7987
+ },
7988
+ /** Claims a task: `label` in its channel, whoever owns it. Of claims that race, one lands. */
7989
+ async claim(identity, id, lease) {
7990
+ const { principal, actor } = identity;
7991
+ const { channel } = await taskOf(principal.access, id);
7992
+ authorize(principal.access, "label", channel);
7993
+ const token = newToken();
7994
+ const made = {};
7995
+ const root = await changeTask(identity, id, (found) => {
7996
+ claimable(found, identity);
7997
+ const claimed = claiming(found, found.task, identity, lease, token);
7998
+ made.claim = claimed.claim;
7999
+ return claimed.events;
8000
+ });
8001
+ const claim = made.claim;
8002
+ await arm(id, claim.epoch, claim.until);
8003
+ return {
8004
+ task: await shown(identity, root),
8005
+ claim
8006
+ };
8007
+ },
8008
+ /** Claims the oldest ready task there, waiting up to `wait` seconds for one. */
8009
+ async claimReady(identity, input, signal) {
8010
+ const deadline = Date.now() + (input.wait ?? 0) * 1e3;
8011
+ for (let pause = 100;; pause = Math.min(pause * 2, 1e3)) {
8012
+ if (signal.aborted) return { task: null };
8013
+ const next = await claimNext(identity, input, signal);
8014
+ if (next) return {
8015
+ task: await shown(identity, next.root),
8016
+ claim: next.claim
8017
+ };
8018
+ if (Date.now() >= deadline) return { task: null };
8019
+ await paused(Math.min(pause, Math.max(0, deadline - Date.now())), signal);
8020
+ }
8021
+ },
8022
+ /** Extends a claim's lease from now. */
8023
+ async renew(identity, id, proof, lease) {
8024
+ await taskOf(identity.principal.access, id);
8025
+ const made = { until: "" };
8026
+ const root = await changeTask(identity, id, (found) => {
8027
+ fenced(found, proof);
8028
+ made.until = new Date(Date.now() + leaseOf(lease)).toISOString();
8029
+ return [{
8030
+ type: "task.renewed",
8031
+ payload: {
8032
+ id,
8033
+ thread: found.thread,
8034
+ epoch: proof.epoch,
8035
+ until: made.until,
8036
+ by: identity.author
8037
+ }
8038
+ }];
8039
+ });
8040
+ await arm(id, proof.epoch, made.until);
8041
+ return {
8042
+ task: await shown(identity, root),
8043
+ until: made.until
8044
+ };
8045
+ },
8046
+ /** What ends a claim, by the claim: released, completed, or failed. A completion readies the tasks that waited only for it. */
8047
+ async settle(identity, id, proof, how) {
8048
+ await taskOf(identity.principal.access, id);
8049
+ return { task: await shown(identity, await changeTask(identity, id, async (found, position) => {
8050
+ fenced(found, proof);
8051
+ const about = {
8052
+ id,
8053
+ thread: found.thread,
8054
+ epoch: proof.epoch,
8055
+ by: identity.author
8056
+ };
8057
+ if (how.type === "task.released") return [{
8058
+ type: "task.released",
8059
+ payload: about
8060
+ }];
8061
+ if (how.type === "task.failed") return [{
8062
+ type: "task.failed",
8063
+ payload: {
8064
+ ...about,
8065
+ reason: how.reason
8066
+ }
8067
+ }];
8068
+ return [{
8069
+ type: "task.completed",
8070
+ payload: {
8071
+ ...about,
8072
+ result: how.result
8073
+ }
8074
+ }, ...await readied(id, position)];
8075
+ })) };
8076
+ },
8077
+ /**
8078
+ * Holds a task for a person. A claimed task's hold is its claim's, which it ends; otherwise its
8079
+ * owner's, or `manage`'s. One whose lease ran out is no one's, so its owner holds it.
8080
+ */
8081
+ async block(identity, id, input) {
8082
+ const task = await taskOf(identity.principal.access, id);
8083
+ if (!input.proof) owns(identity, task);
8084
+ const { proof } = input;
8085
+ return { task: await shown(identity, await changeTask(identity, id, (found) => {
8086
+ if (proof) fenced(found, proof);
8087
+ else {
8088
+ const state = stateNow(found.task, Date.now());
8089
+ if (state === "claimed") throw conflict("task_claimed", `#${id} is claimed until ${found.task.claim.until}: only its claim holds it`);
8090
+ if (state === "blocked") throw conflict("task_blocked", `#${id} is held already: ${found.task.blocked.reason}`);
8091
+ if (finished(found.task)) throw conflict("task_finished", `#${id} is ${found.task.state}`);
8092
+ }
8093
+ return [{
8094
+ type: "task.blocked",
8095
+ payload: {
8096
+ id,
8097
+ thread: found.thread,
8098
+ kind: input.kind ?? null,
8099
+ reason: input.reason,
8100
+ by: identity.author
8101
+ }
8102
+ }];
8103
+ })) };
8104
+ },
8105
+ /** Lifts a hold: back to ready, or to waiting while a task it needs hasn't completed. One that isn't held is left as it is. */
8106
+ async unblock(identity, id) {
8107
+ owns(identity, await taskOf(identity.principal.access, id));
8108
+ return { task: await shown(identity, await changeTask(identity, id, async (found, position) => {
8109
+ if (finished(found.task)) throw conflict("task_finished", `#${id} is ${found.task.state}`);
8110
+ if (found.task.state !== "blocked") return [];
8111
+ const about = {
8112
+ id,
8113
+ thread: found.thread
8114
+ };
8115
+ const ready = found.task.needs.length > 0 && await satisfied(found.task, position);
8116
+ return [{
8117
+ type: "task.unblocked",
8118
+ payload: {
8119
+ ...about,
8120
+ by: identity.author
8121
+ }
8122
+ }, ...ready ? [{
8123
+ type: "task.ready",
8124
+ payload: about
8125
+ }] : []];
8126
+ })) };
8127
+ },
8128
+ /** Makes a failed task ready again, in place, so what waits for it still does. One that's open is left as it is. */
8129
+ async reopen(identity, id) {
8130
+ owns(identity, await taskOf(identity.principal.access, id));
8131
+ return { task: await shown(identity, await changeTask(identity, id, (found) => {
8132
+ if (found.task.state === "completed" || found.task.state === "canceled") throw conflict("task_finished", `#${id} is ${found.task.state}`);
8133
+ return found.task.state === "failed" ? [{
8134
+ type: "task.reopened",
8135
+ payload: {
8136
+ id,
8137
+ thread: found.thread,
8138
+ by: identity.author
8139
+ }
8140
+ }] : [];
8141
+ })) };
8142
+ },
8143
+ /** Assigns a task to one of its owner's actors, or with null to anyone who may claim it. A claim it has stays. */
8144
+ async assign(identity, id, actor) {
8145
+ const task = await taskOf(identity.principal.access, id);
8146
+ owns(identity, task);
8147
+ const assigned = ownActor(task.task.owner, actor);
8148
+ return { task: await shown(identity, await changeTask(identity, id, (found) => {
8149
+ if (finished(found.task)) throw conflict("task_finished", `#${id} is ${found.task.state}`);
8150
+ return found.task.for === assigned ? [] : [{
8151
+ type: "task.assigned",
8152
+ payload: {
8153
+ id,
8154
+ thread: found.thread,
8155
+ for: assigned,
8156
+ by: identity.author
8157
+ }
8158
+ }];
8159
+ })) };
8160
+ },
8161
+ /**
8162
+ * Replaces what a task waits for, for its owner or `manage`, while no one holds it and it isn't
8163
+ * finished. They're checked as a new task's are, and must leave it waiting for no task that
8164
+ * waits for it. It waits for them from this write, and `task.ready` follows in it when they've
8165
+ * all completed; with none it's ready. A held task stays held, and the same set changes nothing.
8166
+ */
8167
+ async needs(identity, id, refs) {
8168
+ const { principal } = identity;
8169
+ owns(identity, await taskOf(principal.access, id));
8170
+ return { task: await shown(identity, await changeTask(identity, id, async (found, position) => {
8171
+ const { task } = found;
8172
+ if (finished(task)) throw conflict("task_finished", `#${id} is ${task.state}`);
8173
+ const over = lapsed(task, Date.now());
8174
+ if (task.state === "claimed" && !over) throw conflict("task_claimed", `#${id} is claimed until ${task.claim.until}: what it needs changes once no one holds it`);
8175
+ const needs = await needsAt(principal.access, refs, position, id);
8176
+ if (needs.ids.length === task.needs.length && needs.ids.every((need) => task.needs.includes(need))) return [];
8177
+ await acyclic(principal.access, id, needs.ids.filter((need) => !task.needs.includes(need)), position);
8178
+ const about = {
8179
+ id,
8180
+ thread: found.thread
8181
+ };
8182
+ return [
8183
+ ...over ? [{
8184
+ type: "task.expired",
8185
+ payload: {
8186
+ ...about,
8187
+ epoch: task.epoch
8188
+ }
8189
+ }] : [],
8190
+ {
8191
+ type: "task.needs_changed",
8192
+ payload: {
8193
+ ...about,
8194
+ needs: needs.ids,
8195
+ by: identity.author
8196
+ }
8197
+ },
8198
+ ...needs.ids.length > 0 && needs.completed && task.state !== "blocked" ? [{
8199
+ type: "task.ready",
8200
+ payload: about
8201
+ }] : []
8202
+ ];
8203
+ })) };
8204
+ },
8205
+ /** Cancels a task that hasn't completed, ending any claim. What waits for it keeps waiting. */
8206
+ async cancel(identity, id, reason) {
8207
+ owns(identity, await taskOf(identity.principal.access, id));
8208
+ return { task: await shown(identity, await changeTask(identity, id, (found) => {
8209
+ if (found.task.state === "completed" || found.task.state === "canceled") throw conflict("task_finished", `#${id} is ${found.task.state}`);
8210
+ return [{
8211
+ type: "task.canceled",
8212
+ payload: {
8213
+ id,
8214
+ thread: found.thread,
8215
+ reason,
8216
+ by: identity.author
8217
+ }
8218
+ }];
8219
+ })) };
8220
+ }
8221
+ };
8222
+ }
6861
8223
  //#endregion
6862
8224
  //#region src/server/watch.ts
6863
8225
  const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
6864
- /** The events a tail shows, receipts included for `--all`: each concerns a message, and carries its thread for the lane. */
8226
+ /** The events a tail shows, receipts and a claim's renewals included for `--all`: each concerns a message, and carries its thread for the lane. */
6865
8227
  const WATCHED = [
6866
8228
  "message.posted",
6867
8229
  "message.edited",
@@ -6872,10 +8234,28 @@ const WATCHED = [
6872
8234
  "message.sync_failed",
6873
8235
  "message.synced",
6874
8236
  "message.files_synced",
6875
- "thread.synced"
8237
+ "thread.synced",
8238
+ "task.created",
8239
+ "task.assigned",
8240
+ "task.needs_changed",
8241
+ "task.ready",
8242
+ "task.claimed",
8243
+ "task.renewed",
8244
+ "task.released",
8245
+ "task.expired",
8246
+ "task.completed",
8247
+ "task.failed",
8248
+ "task.blocked",
8249
+ "task.unblocked",
8250
+ "task.canceled",
8251
+ "task.reopened"
6876
8252
  ];
6877
- /** Receipts: only a `--all` tail shows them. */
6878
- const RECEIPTS = /* @__PURE__ */ new Set(["message.synced", "message.files_synced"]);
8253
+ /** Receipts and a claim's renewals: only a `--all` tail shows them. */
8254
+ const RECEIPTS = /* @__PURE__ */ new Set([
8255
+ "message.synced",
8256
+ "message.files_synced",
8257
+ "task.renewed"
8258
+ ]);
6879
8259
  /**
6880
8260
  * What a registrant's sync gets, in every channel where it may sync: what it delivers to platforms,
6881
8261
  * and a thread's new targets. A tail never shows `thread.synced`, so no watcher gets it.
@@ -7342,6 +8722,16 @@ function cursorAt(value) {
7342
8722
  if (index === null) throw badRequest(`${value} isn't a cursor or a message ID on this board`, "invalid_cursor");
7343
8723
  return index;
7344
8724
  }
8725
+ /** A `/threads` page's `older` on this board: where its oldest thread stands, its latest message's index then its root's. */
8726
+ const olderRef = (position) => `${position.at}.${position.id}`;
8727
+ function olderAt(value) {
8728
+ const match = /^(\d{1,15})\.(\d{1,15})$/.exec(value);
8729
+ if (!match) throw badRequest(`${value} isn't a page of threads on this board`, "invalid_cursor");
8730
+ return {
8731
+ at: Number(match[1]),
8732
+ id: Number(match[2])
8733
+ };
8734
+ }
7345
8735
  /** The message a ref in a request names, as its log index, or a 404 for one that names nothing here. */
7346
8736
  function messageAt(value) {
7347
8737
  const index = indexOf$1(value);
@@ -7518,6 +8908,10 @@ function build(options, binding) {
7518
8908
  store: log,
7519
8909
  scheduler: options.scheduler
7520
8910
  });
8911
+ const tasks = createTasks({
8912
+ store: log,
8913
+ scheduler: options.scheduler
8914
+ });
7521
8915
  const projection = tablesConsumer(store.tables);
7522
8916
  /** Sync's delivery in progress here: its receipts are its consumer's appends, fenced by its attempt. */
7523
8917
  const delivering = new AsyncLocalStorage();
@@ -7587,7 +8981,8 @@ function build(options, binding) {
7587
8981
  store: log,
7588
8982
  accessNow: (principal, grants) => binding.accessNow(principal, grants),
7589
8983
  explain: (principal, channel) => binding.explain(principal, channel),
7590
- team: async () => (await binding.project()).teamId
8984
+ team: async () => (await binding.project()).teamId,
8985
+ logins: () => binding.logins
7591
8986
  });
7592
8987
  const schemaRegistry = createSchemas({ store: log });
7593
8988
  const inboxes = inboxServer.session(INBOXES_SESSION);
@@ -7598,6 +8993,7 @@ function build(options, binding) {
7598
8993
  accessNow: binding.accessNow,
7599
8994
  send: async (identity, origin, input) => sendAs(identity, origin, input)
7600
8995
  });
8996
+ tasks.bind({ writes });
7601
8997
  watchers.bind({ reads });
7602
8998
  /**
7603
8999
  * Whether `principal` may have a file: one it uploaded, or one a message it
@@ -7643,6 +9039,12 @@ function build(options, binding) {
7643
9039
  before = messages[0].id;
7644
9040
  }
7645
9041
  }
9042
+ /**
9043
+ * The IDs the events of a batch made under `id` carry, as a post's carries its own: each root's post in turn, and the
9044
+ * event after the first root, which says what the batch was asked for. A batch is found again by them alone.
9045
+ */
9046
+ const batchRoot = (id, at) => derivedId("board-batch", id, String(at));
9047
+ const batchAsked = (id, request) => derivedId("board-batch-request", id, request);
7646
9048
  /** Files a write carries, as the board stored them: each one the caller may have, or 404 as if it didn't exist. */
7647
9049
  const attachmentsFor = (principal, ids) => Promise.all([...new Set(ids ?? [])].map(async (id) => {
7648
9050
  const { attachment, ...uploader } = await readUpload(blob, id);
@@ -7673,6 +9075,13 @@ function build(options, binding) {
7673
9075
  throw error;
7674
9076
  }
7675
9077
  }
9078
+ /** Refuses a request's post an ID that's someone else's to post with: the board's own, another client's key, or a sync's import. */
9079
+ function ownId(caller, principal, id) {
9080
+ if (!fromRequest(caller) || id === void 0) return;
9081
+ if (DERIVED_ID.test(id)) throw badRequest("id: UUIDv8s are the board's own, for the writes it makes itself");
9082
+ if (id.startsWith("key:") && !isKeyIdOf(id, principal.id)) throw badRequest(`id: key:… IDs derive from a client's key, and this token's are key:${principal.id}:…`);
9083
+ if (id.startsWith("sync:")) throw badRequest("id: sync:… IDs are what sync imports, under the principal that imports them");
9084
+ }
7676
9085
  /** A post as it lands: what the caller may post, with the files it may have. */
7677
9086
  async function postNow(caller, identity, parsed) {
7678
9087
  const { principal } = identity;
@@ -7682,9 +9091,7 @@ function build(options, binding) {
7682
9091
  re: parsed.re === void 0 ? void 0 : messageAt(parsed.re)
7683
9092
  };
7684
9093
  const proofs = await authorizePost(writes, principal.access, body);
7685
- if (fromRequest(caller) && body.id !== void 0 && DERIVED_ID.test(body.id)) throw badRequest("id: UUIDv8s are the board's own, for the writes it makes itself");
7686
- if (fromRequest(caller) && body.id?.startsWith("key:") && !isKeyIdOf(body.id, principal.id)) throw badRequest(`id: key:… IDs derive from a client's key, and this token's are key:${principal.id}:…`);
7687
- if (fromRequest(caller) && body.id?.startsWith("sync:")) throw badRequest("id: sync:… IDs are what sync imports, under the principal that imports them");
9094
+ ownId(caller, principal, body.id);
7688
9095
  const attachments = await attachmentsFor(principal, body.attachments);
7689
9096
  const { schedule } = caller.origin;
7690
9097
  return { message: await writePost(writes, {
@@ -7806,8 +9213,9 @@ function build(options, binding) {
7806
9213
  actors,
7807
9214
  access: principal.access
7808
9215
  }), principal.access);
7809
- const { threads, position } = await reads.threads(filter, {
9216
+ const { threads, position, older } = await reads.threads(filter, {
7810
9217
  ...query.after !== void 0 ? { after: cursorAt(query.after) } : {},
9218
+ ...query.before !== void 0 ? { before: olderAt(query.before) } : {},
7811
9219
  limit: query.limit ?? 50
7812
9220
  });
7813
9221
  const reader = await reads.reader(principal.access, threads.flatMap((t) => t.last ? [t.root, t.last] : [t.root]));
@@ -7817,7 +9225,8 @@ function build(options, binding) {
7817
9225
  replies: t.replies,
7818
9226
  last: t.last && view$1(t.last, actors, reader)
7819
9227
  })),
7820
- cursor: ref(Math.min(position, through))
9228
+ cursor: ref(Math.min(position, through)),
9229
+ ...older !== void 0 ? { older: older && olderRef(older) } : {}
7821
9230
  };
7822
9231
  },
7823
9232
  async message(caller, { id }, signal) {
@@ -7927,6 +9336,158 @@ function build(options, binding) {
7927
9336
  schedule: blindSchedule(answer.schedule, identity.principal.access, identity.actor.id)
7928
9337
  };
7929
9338
  },
9339
+ tasks: async (caller, query) => tasks.list(await identityOf(caller), query),
9340
+ async createTask(caller, body) {
9341
+ if (body.re === void 0) withinLimits({
9342
+ text: body.text ?? "",
9343
+ attachments: body.attachments
9344
+ });
9345
+ taskLimits.needs(body.needs);
9346
+ taskLimits.lease(body.lease);
9347
+ const identity = await identityOf(caller);
9348
+ const { principal } = identity;
9349
+ const about = {
9350
+ needs: body.needs,
9351
+ for: body.for,
9352
+ claim: body.claim,
9353
+ lease: body.lease
9354
+ };
9355
+ if (body.re !== void 0) return tasks.adopt(identity, messageAt(body.re), about);
9356
+ const proofs = await authorizePost(writes, principal.access, {
9357
+ channel: body.channel,
9358
+ labels: body.labels
9359
+ });
9360
+ ownId(caller, principal, body.id);
9361
+ const attachments = await attachmentsFor(principal, body.attachments);
9362
+ const made = tasks.starting(identity, {
9363
+ channel: body.channel,
9364
+ ...about
9365
+ });
9366
+ const task = await writePost(writes, {
9367
+ attachments,
9368
+ identity,
9369
+ proofs,
9370
+ channel: body.channel,
9371
+ text: body.text ?? "",
9372
+ labels: body.labels,
9373
+ noSync: body.noSync,
9374
+ id: body.id,
9375
+ with: made.along
9376
+ });
9377
+ if (!task.task) throw duplicateId();
9378
+ const claim = await made.claimed(messageAt(task.id));
9379
+ return {
9380
+ task,
9381
+ ...claim ? { claim } : {}
9382
+ };
9383
+ },
9384
+ async createTasks(caller, body) {
9385
+ taskLimits.batch(body.tasks);
9386
+ for (const [at, task] of body.tasks.entries()) {
9387
+ if (task.text.length > 1e4) throw textTooLong();
9388
+ if ((task.attachments?.length ?? 0) > 10) throw badRequest(`tasks.${at}.attachments: a message carries at most 10`);
9389
+ }
9390
+ const identity = await identityOf(caller);
9391
+ const { principal } = identity;
9392
+ const proofs = await authorizePost(writes, principal.access, {
9393
+ channel: body.channel,
9394
+ labels: body.tasks.find((task) => Object.keys(task.labels ?? {}).length > 0)?.labels
9395
+ });
9396
+ ownId(caller, principal, body.id);
9397
+ const made = tasks.startingMany(identity, body.tasks);
9398
+ const rootId = (at) => body.id !== void 0 ? batchRoot(body.id, at) : Promise.resolve(crypto.randomUUID());
9399
+ const roots = await Promise.all(body.tasks.map(async (task, at) => ({
9400
+ id: await rootId(at),
9401
+ text: task.text,
9402
+ labels: task.labels,
9403
+ noSync: task.noSync,
9404
+ attachments: await attachmentsFor(principal, task.attachments)
9405
+ })));
9406
+ const { id } = body;
9407
+ const asked = id !== void 0 ? await batchAsked(id, body.request ?? "") : void 0;
9408
+ const again = id !== void 0 && asked !== void 0 ? {
9409
+ asked,
9410
+ landed: () => landedBatch(writes, identity, (at) => batchRoot(id, at), asked)
9411
+ } : void 0;
9412
+ return { tasks: await writeRoots(writes, {
9413
+ identity,
9414
+ proofs,
9415
+ channel: body.channel,
9416
+ roots,
9417
+ with: made,
9418
+ again
9419
+ }) };
9420
+ },
9421
+ async createdTasks(caller, { id, request }) {
9422
+ const identity = await identityOf(caller);
9423
+ const found = await landedBatch(writes, identity, (at) => batchRoot(id, at), request !== void 0 ? await batchAsked(id, request) : void 0);
9424
+ if ("tasks" in found) return found;
9425
+ if (found.not === "asked") throw duplicateId();
9426
+ throw notFound(`no batch of yours has id ${id}`, "batch_not_found");
9427
+ },
9428
+ async claimReadyTask(caller, body, signal) {
9429
+ taskLimits.lease(body.lease);
9430
+ taskLimits.from(body.from);
9431
+ return tasks.claimReady(await identityOf(caller), body, signal);
9432
+ },
9433
+ async claimTask(caller, { id, lease }) {
9434
+ taskLimits.lease(lease);
9435
+ return tasks.claim(await identityOf(caller), messageAt(id), lease);
9436
+ },
9437
+ async renewTask(caller, { id, epoch, token, lease }) {
9438
+ taskLimits.lease(lease);
9439
+ return tasks.renew(await identityOf(caller), messageAt(id), {
9440
+ epoch,
9441
+ token
9442
+ }, lease);
9443
+ },
9444
+ releaseTask: async (caller, { id, epoch, token }) => tasks.settle(await identityOf(caller), messageAt(id), {
9445
+ epoch,
9446
+ token
9447
+ }, { type: "task.released" }),
9448
+ async completeTask(caller, { id, epoch, token, result }) {
9449
+ taskLimits.note("result", result);
9450
+ return tasks.settle(await identityOf(caller), messageAt(id), {
9451
+ epoch,
9452
+ token
9453
+ }, {
9454
+ type: "task.completed",
9455
+ result: result ?? null
9456
+ });
9457
+ },
9458
+ async failTask(caller, { id, epoch, token, reason }) {
9459
+ taskLimits.note("reason", reason);
9460
+ return tasks.settle(await identityOf(caller), messageAt(id), {
9461
+ epoch,
9462
+ token
9463
+ }, {
9464
+ type: "task.failed",
9465
+ reason
9466
+ });
9467
+ },
9468
+ async blockTask(caller, { id, reason, kind, epoch, token }) {
9469
+ taskLimits.note("reason", reason);
9470
+ taskLimits.kind(kind);
9471
+ return tasks.block(await identityOf(caller), messageAt(id), {
9472
+ reason,
9473
+ kind,
9474
+ ...epoch !== void 0 && token !== void 0 ? { proof: {
9475
+ epoch,
9476
+ token
9477
+ } } : {}
9478
+ });
9479
+ },
9480
+ unblockTask: async (caller, { id }) => tasks.unblock(await identityOf(caller), messageAt(id)),
9481
+ reopenTask: async (caller, { id }) => tasks.reopen(await identityOf(caller), messageAt(id)),
9482
+ assignTask: async (caller, { id, for: actor }) => tasks.assign(await identityOf(caller), messageAt(id), actor),
9483
+ async setTaskNeeds(caller, { id, needs }) {
9484
+ taskLimits.needs(needs);
9485
+ return tasks.needs(await identityOf(caller), messageAt(id), needs);
9486
+ },
9487
+ async cancelTask(caller, { id, reason }) {
9488
+ taskLimits.note("reason", reason);
9489
+ return tasks.cancel(await identityOf(caller), messageAt(id), reason);
9490
+ },
7930
9491
  grants: async (caller) => access.grants(await identityOf(caller)),
7931
9492
  createGrant: async (caller, body) => access.createGrant(await identityOf(caller), body),
7932
9493
  updateGrant: async (caller, input) => access.updateGrant(await identityOf(caller), input),
@@ -8129,11 +9690,17 @@ function build(options, binding) {
8129
9690
  },
8130
9691
  async syncImport(caller, body, signal) {
8131
9692
  const { principal } = await needSync(caller, "import", true);
8132
- const platform = await speaksFor(caller, principal.id, body.author, body.from);
9693
+ const mentioned = body.op === "post" || body.op === "edit" ? body.mentioned ?? [] : [];
9694
+ const [platform, ...platforms] = await speaksFor(caller, principal.id, [body.author, ...mentioned], body.from);
8133
9695
  const author = externalIdentity(body.author, ownSync(caller) ? null : principal, platform);
8134
9696
  const may = (channel) => principal.access.can("sync", channel);
8135
9697
  const keys = ownSync(caller) ? [] : (await entriesOf(caller, principal.id)).map(({ key }) => key);
8136
- const asNamed = (text) => keys.length === 0 ? text : replaceMentions(text, (token) => token.kind === "actor" && keys.some((key) => token.actor.startsWith(`${key}:`)) ? `@[${principal.id}+${token.actor}]` : null);
9698
+ const asNamed = (text) => {
9699
+ if (keys.length === 0) return text;
9700
+ const named = replaceMentions(text, (token) => token.kind === "actor" && keys.some((key) => token.actor.startsWith(`${key}:`)) ? `@[${principal.id}+${token.actor}]` : null);
9701
+ return named.length > 1e4 ? text : named;
9702
+ };
9703
+ const introduces = mentioned.map((user, at) => externalIdentity(user, ownSync(caller) ? null : principal, platforms[at]).actor);
8137
9704
  if (body.op === "post") {
8138
9705
  if (body.channel === void 0 === (body.re === void 0)) throw badRequest("an import needs `channel`; a reply needs `re`");
8139
9706
  let re;
@@ -8168,7 +9735,8 @@ function build(options, binding) {
8168
9735
  ...body.origin && !ownSync(caller) ? { importedBy: principal.id } : {},
8169
9736
  after: afterAt(body.after),
8170
9737
  attachments,
8171
- links: await linksOf(principal, body.links)
9738
+ links: await linksOf(principal, body.links),
9739
+ introduces
8172
9740
  })).id;
8173
9741
  };
8174
9742
  const write = {
@@ -8195,7 +9763,8 @@ function build(options, binding) {
8195
9763
  text: asNamed(text),
8196
9764
  from: body.from,
8197
9765
  asAuthor,
8198
- revision: body.revision
9766
+ revision: body.revision,
9767
+ introduces
8199
9768
  });
8200
9769
  return ref(found.id);
8201
9770
  };
@@ -8488,35 +10057,40 @@ function build(options, binding) {
8488
10057
  return [...found.values()];
8489
10058
  }
8490
10059
  /**
8491
- * Whether a caller may write as `author`, and the platform of the sync key they're a user of: a
8492
- * platform user, never anyone this board signs in, named under a key it syncs (`slack-eu:…`):
8493
- * entry `from`, when it names one.
10060
+ * Whether a caller may write as each of `users`, and the platform of the sync key each is a user
10061
+ * of: a platform user, never anyone this board signs in, named under a key it syncs
10062
+ * (`slack-eu:…`): entry `from`, when it names one. An import's author, and who its text mentions.
8494
10063
  */
8495
- async function speaksFor(caller, principal, author, from) {
8496
- if (authenticates(author.id) || await signedIn(author.id)) throw forbidden$1(`${author.id} is someone this board signs in, not a platform user: sync can't write as them`);
10064
+ async function speaksFor(caller, principal, users, from) {
10065
+ const signs = await signedIn();
10066
+ for (const { id } of users) if (authenticates(id) || signs(id)) throw forbidden$1(`${id} is someone this board signs in, not a platform user: sync can't write as them`);
8497
10067
  const entries = await entriesOf(caller, principal);
8498
10068
  const keys = from === null ? entries : entries.filter((entry) => entry.key === from);
8499
10069
  if (from !== null && keys.length === 0) throw forbidden$1(`this token doesn't sync ${from} here: its board registers its sync entries`);
8500
- const entry = keys.find(({ key }) => author.id.startsWith(`${key}:`));
8501
- if (!entry) throw forbidden$1(`${author.id} isn't a user of ${keys.length ? keys.map(({ key }) => key).join(" or ") : "a sync key this token has"}: their ID starts with its key`);
8502
- return entry.platform;
10070
+ return users.map(({ id }) => {
10071
+ const entry = keys.find(({ key }) => id.startsWith(`${key}:`));
10072
+ if (!entry) throw forbidden$1(`${id} isn't a user of ${keys.length ? keys.map(({ key }) => key).join(" or ") : "a sync key this token has"}: their ID starts with its key`);
10073
+ return entry.platform;
10074
+ });
8503
10075
  }
8504
10076
  /**
8505
- * Whether `id` is someone this board signs in that `authenticates` can't tell by its shape: a
10077
+ * Whether an ID is someone this board signs in that `authenticates` can't tell by its shape: a
8506
10078
  * host's principal, which may take any ID and kind, and their agents (`<principal>+<profile>`).
8507
10079
  * It is once it has registered (its watchers write as `<principal>+<id>`, which never wakes
8508
10080
  * them), or written: the board records a host's principals and their profiles as the host's,
8509
10081
  * whatever their kind, and anything else that writes as other than a platform user.
8510
10082
  */
8511
- async function signedIn(id) {
8512
- const plus = id.indexOf("+");
10083
+ async function signedIn() {
8513
10084
  const owners = (await registry.state()).byOwner;
8514
- if (owners[id] || plus > 0 && owners[id.slice(0, plus)]) return true;
8515
10085
  const { state: actors } = await session.state(actorsReducer);
8516
- return [id, plus > 0 ? id.slice(0, plus) : null].some((known) => {
8517
- const actor = known === null ? void 0 : actors.byId[known];
8518
- return actor !== void 0 && (actor.kind !== "external" || actor.host === true);
8519
- });
10086
+ return (id) => {
10087
+ const plus = id.indexOf("+");
10088
+ if (owners[id] || plus > 0 && owners[id.slice(0, plus)]) return true;
10089
+ return [id, plus > 0 ? id.slice(0, plus) : null].some((known) => {
10090
+ const actor = known === null ? void 0 : actors.byId[known];
10091
+ return actor !== void 0 && (actor.kind !== "external" || actor.host === true);
10092
+ });
10093
+ };
8520
10094
  }
8521
10095
  /**
8522
10096
  * Refuses a caller narrowed with `x-board-can` (a sandboxed agent, say): its principal's
@@ -8657,6 +10231,7 @@ function build(options, binding) {
8657
10231
  inboxServer,
8658
10232
  schedules.server,
8659
10233
  registry.server,
10234
+ tasks.server,
8660
10235
  watchers.server
8661
10236
  ];
8662
10237
  return {
@@ -8813,10 +10388,10 @@ function local(options = {}) {
8813
10388
  opening ??= (async () => {
8814
10389
  const file = localFile(bound.name);
8815
10390
  let store;
8816
- if (options.memory) store = (await import("./memory-DyEL0fvN.mjs")).memory();
10391
+ if (options.memory) store = (await import("./memory-CMm-Fk_A.mjs")).memory();
8817
10392
  else {
8818
10393
  const { mkdir } = await import("node:fs/promises");
8819
- const { sqlite } = await import("./sqlite-Con-8duk.mjs");
10394
+ const { sqlite } = await import("./sqlite-CVG8XKHm.mjs");
8820
10395
  const path = join(dir, `${file}.db`);
8821
10396
  try {
8822
10397
  await mkdir(dir, {