@941design/marmot 0.0.0-stage → 0.2.0-alpha.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 (192) hide show
  1. package/CHANGELOG.md +709 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,1022 @@
1
+ /**
2
+ * `createMarmotClient` and the typed client surface (docs/client-api.md).
3
+ *
4
+ * Construction is synchronous and side-effect free towards the consumer's
5
+ * collaborators: it validates options, wraps the account signer with
6
+ * `nostr-events`' `withSignerBudget` (AC-API-5, ADR-009) and narrows the
7
+ * transport to the three `TransportContract` members (AC-API-4). It never
8
+ * calls the signer or the transport.
9
+ *
10
+ * No member is a stub: AC-FIX-6 (S11) sweeps the built package and fails on
11
+ * any `not-implemented` MarmotError.
12
+ */
13
+ import type { MarmotGroupEngineOptions } from '@941design/marmot-engine/engine';
14
+ import type { NostrEvent, Rumor } from '@941design/nostr-events/event';
15
+ import { type Signer } from '@941design/nostr-events/signer';
16
+ import { type BudgetPolicy } from '@941design/nostr-events/signer/budget';
17
+ import type { PermissionDeclaration } from '@941design/nostr-events/signer/permissions';
18
+ import type { TransportContract } from '@941design/nostr-events/transport/contract';
19
+ import type { AppliedNotification, GroupNotification, HistoryBackend, LeafEquivocationNotification, OrderingKey } from '../history/index.js';
20
+ import type { EncryptedMedia, EncryptMediaOptions, MediaCache } from '../media/index.js';
21
+ import { type DeviceForgetOutcome, type DeviceInfo, type DeviceKeyRotationOutcome, type DeviceLineage, type DeviceMaintenanceKind, type EnrolmentApprovalOutcome, type EnrolmentPrompt, type EnrolmentRequestHandle, type EnrolmentRequestOptions } from '../account/index.js';
22
+ import { type InboxDisposition, type InboxRumorHandler } from '../inbox/index.js';
23
+ import { type KeyPackageOffer, type MaintenanceKind, type PendingInvitation, type ProposalCallback, type WelcomeOutcome } from '../invitations/index.js';
24
+ import { MarmotError } from '../shared/index.js';
25
+ import type { AccountStore, GroupStore, GroupStoreTx } from '../storage/index.js';
26
+ import { type BeforeCreateGroupGates, type CreateGroupGate } from './before-create-group.js';
27
+ import { type BeforePublishHook, type BeforePublishRegistry, type BeforePublishSkipped } from './before-publish-hooks.js';
28
+ import { type GroupRegistry, type GroupRuntime } from './group-runtime.js';
29
+ import type { GroupSnapshot } from './group-snapshot.js';
30
+ import { type InboxRumorDelivery } from './inbox-send.js';
31
+ import { type LifecycleEventPayloads, type LifecycleEvents } from './lifecycle-events.js';
32
+ import { type EngineSeamsOverride } from './client-config.js';
33
+ /** Consumer-supplied check run on every relay event before it is trusted (ADR-008). */
34
+ export type EventVerifier = (event: NostrEvent) => boolean | Promise<boolean>;
35
+ /**
36
+ * The consumer's ADR-007 stores — `{ account, groupFactory }` of a
37
+ * `WritableStores` (`@941design/marmot/storage`), opened under the lease.
38
+ */
39
+ export interface ClientStores {
40
+ readonly account: AccountStore;
41
+ groupFactory(groupId: string): GroupStore;
42
+ }
43
+ /** Relay policy: `discover` resolves inbox relays via 10050/10002; `fixed` is single-relay mode. */
44
+ export interface RelayOptions {
45
+ readonly defaults: readonly string[];
46
+ readonly mode: 'discover' | 'fixed';
47
+ }
48
+ /** Injectable millisecond clock (grace window, deadlines, rate limits). */
49
+ export interface ClientClock {
50
+ now(): number;
51
+ }
52
+ /**
53
+ * Injectable scheduler for the client's deferred work: confirmation and
54
+ * publish retries, history re-requests and the engine's convergence
55
+ * settle-check. Defaults to `setTimeout` / `clearTimeout`.
56
+ */
57
+ export interface ClientTimers {
58
+ set(callback: () => void, ms: number): unknown;
59
+ clear(handle: unknown): void;
60
+ }
61
+ export interface ClientOptions {
62
+ /** Defaults to `Date.now`. */
63
+ readonly clock?: ClientClock;
64
+ /** Consecutive history timeouts before a relay is excluded from history requests (AC-PIPE-14). Default 3. */
65
+ readonly historySilenceThreshold?: number;
66
+ /** KeyPackage `init_key` retention after consumption (AC-KP-3). Default 24 h. */
67
+ readonly graceWindowMs?: number;
68
+ /** Scheduler for retries and deferred work. Defaults to `setTimeout` / `clearTimeout`. */
69
+ readonly timers?: ClientTimers;
70
+ /** Deadline of each kind-445 history `requestWithDeadline` (AC-PIPE-7). Default 10 s. */
71
+ readonly historyTimeoutMs?: number;
72
+ /** Failed publishes after which a retryable intent goes terminal (`send-rejected` / `intentFailed`). Default 20. */
73
+ readonly maxPublishAttempts?: number;
74
+ /**
75
+ * AC-BAR-2: the one deadline (ms) under which an own commit's `onBeforePublish` barriers are awaited before its first
76
+ * publish. A barrier still pending at the deadline is abandoned (its signal aborts), the commit is published anyway
77
+ * and `beforePublishSkipped { reason: 'barrier-timeout' }` fires. An integer >= 1; default 10 000.
78
+ */
79
+ readonly beforePublishTimeoutMs?: number;
80
+ /** Most kind-1059 wrap ids the persisted inbox seen-set keeps; the oldest are evicted first (AC-INBOX-4). Default 10 000. */
81
+ readonly seenSetCap?: number;
82
+ /**
83
+ * Most distinct enrolment requests one session id may have prompted within
84
+ * a minute; the rest are dropped silently (AC-DEV-5). Default 3.
85
+ */
86
+ readonly enrolmentPromptRateLimit?: number;
87
+ /**
88
+ * Relay event-size budget (bytes of event JSON) of the gift wrap an own enrolment request is sent in:
89
+ * `devices.requestEnrolment` refuses a request whose wrap could exceed it (`invalid-options`,
90
+ * `details.reason: 'request-too-large'`, with `wrapBytes`) before anything is minted. A positive safe
91
+ * integer; default 65 536 (64 KiB, a common relay cap).
92
+ */
93
+ readonly maxGiftWrapBytes?: number;
94
+ /**
95
+ * How long `group.leave()` (and each group of `devices.forget(ownLeafKey)`)
96
+ * waits for a peer's confirmed commit of the local leaf's SelfRemove before
97
+ * purging the group anyway (AC-ADMIN-6). Client-clock milliseconds; default 60 000.
98
+ */
99
+ readonly leaveTimeoutMs?: number;
100
+ /**
101
+ * How long a proposal `onProposal` deferred stays deferred (AC-INVITE-4).
102
+ * Client-clock milliseconds from its first `defer`; default 86 400 000
103
+ * (24 h); `0` = never expires. The deadline is persisted with the deferral
104
+ * (no timer) and checked on every own-commit attempt, on group load, on
105
+ * each history pass of the group and on each inbox pass — never while the
106
+ * group is not caught up (no complete sync since load or since its live
107
+ * subscription last ended). `Infinity` also means never. Once it passed,
108
+ * the proposal is treated as `reject` (never auto-accepted) and
109
+ * `proposalExpired` fires.
110
+ */
111
+ readonly proposalDeferralTimeoutMs?: number;
112
+ /**
113
+ * S20 (AC-ADMIN-6/-10): how long a removal of the local leaf stays revisable after the group's own state first
114
+ * shows it — a same-epoch sibling commit arriving inside it rewinds the removal (the device stays a member; a
115
+ * `leave()` resumes as a member) — before it settles: later input is then `self-evicted`, and a `leave()` /
116
+ * own-leaf `devices.forget` waiting on the removal performs `abandon()`. Client-clock milliseconds, a finite
117
+ * integer >= 0; default 10 000. `0` settles at the removal (the pre-S20 timing) — an opt-out that accepts the
118
+ * zombie leave: a device removed only on the losing branch of a race purges while the group still holds its
119
+ * leaf. No upper bound: values above `leaveTimeoutMs` only lengthen the post-removal wait, never the
120
+ * pre-removal one.
121
+ */
122
+ readonly removalSettleMs?: number;
123
+ /**
124
+ * S5 (AC-RACE-2): how long `advanceQueue` and `invite()`'s proposal policy wait for the elected member's
125
+ * confirmed commit before an admin's own `send()`/`invite()` commits a staged SelfRemove-only batch another
126
+ * member is elected to commit (`decideAutoCommit`/`electionAtRest`, client/pipeline.ts) itself. Client-clock
127
+ * milliseconds, a finite integer >= 0; default 5000 (well under `leaveTimeoutMs`'s default 60000). `0` commits
128
+ * at once (the pre-S5 timing): an opt-out that accepts pre-empting the elected committer.
129
+ */
130
+ readonly selfRemoveElectionWaitMs?: number;
131
+ /**
132
+ * S7 (AC-HYG-2): how long an invite's account record is kept once every one of its Welcome deliveries is
133
+ * `delivered` or `declined` — client-clock milliseconds after its last delivery settled. Until then
134
+ * `retryWelcome` can re-send a delivered Welcome and an invitee's decline is matched to it (`welcomeDeclined`);
135
+ * after it the record is deleted the next time the group is loaded, invited to, retried or declined in. A record
136
+ * with a pending, retryable or failed delivery is never deleted by age. A safe integer >= 0; default 30 days.
137
+ */
138
+ readonly inviteRetentionMs?: number;
139
+ /**
140
+ * inbox-handler-time-budget: how long an inbox consumer callback (a `registerInboxHandler` handler or
141
+ * `onApplicationRumor`) may run before `handlerSlow` reports it — a diagnostic only: the handler is never detached
142
+ * and the inbox queue still waits for it (the "handlers must not await long work" contract stands). Client-clock
143
+ * milliseconds, a safe integer >= 0; default 30 000; `0` never reports.
144
+ */
145
+ readonly inboxHandlerBudgetMs?: number;
146
+ /**
147
+ * S8 (AC-RATCH-1): how many generations the own application sender ratchet skips at the first own application
148
+ * message of a group after it is loaded from storage (encrypted once its first post-load sync opened the send
149
+ * gate). The loaded state may be a restored snapshot that never saw own messages sent after it, held only by a
150
+ * relay the first sync excluded as silent: skipping keeps the next message from re-using one of their
151
+ * generations (same key and nonce; members that read the earlier one refuse it). A safe integer in [32, 100];
152
+ * default 64. The skip is applied with that first message only — never persisted without it — so repeated loads
153
+ * with no send do not accumulate; and until a relay accepted an own application message at or after a recorded
154
+ * skip, a load of that same epoch state does not skip again (group-records.ts `ratchetSkipArmed`), so restarts whose
155
+ * first message is refused everywhere keep the gap within one margin plus the undelivered messages. Own messages
156
+ * the first post-load sync reads back from relays floor the skip (ingesting them advances the own ratchet), and one
157
+ * at or after an undelivered recorded skip marks it delivered and re-arms the skip (BACKLOG
158
+ * ratchet-skip-relay-derived-floor). Skips add up
159
+ * otherwise only for a member that misses messages: one that missed every own
160
+ * message of n load cycles in one epoch reads the next one while n × (margin + messages per cycle) + margin stays
161
+ * within the receivers' forward window (ts-mls `maximumForwardRatchetSteps`, 200); the upper bound (half of it)
162
+ * keeps any single skip, plus fewer than a margin of own messages a member did not receive, inside it. Own
163
+ * messages a restored snapshot can miss must stay fewer than the margin.
164
+ */
165
+ readonly ratchetSkipMargin?: number;
166
+ }
167
+ export interface MarmotClientOptions {
168
+ /** Account-key signer; the client wraps it with `withSignerBudget(signer, budget)`. */
169
+ readonly signer: Signer;
170
+ /** `nostr-events` budget policy; `{ policy: 'none' }` is the explicit opt-out. Required. */
171
+ readonly budget: BudgetPolicy;
172
+ /** The only transport dependency (AC-API-4). */
173
+ readonly transport: TransportContract;
174
+ readonly stores: ClientStores;
175
+ readonly relays: RelayOptions;
176
+ readonly verifier?: EventVerifier;
177
+ /**
178
+ * The application's decision on a staged proposal another member sent,
179
+ * asked before this client builds a commit carrying it (AC-INVITE-4).
180
+ * Omitted: a non-admin member's Add or Remove is rejected, every other
181
+ * proposal accepted. A `defer` lasts at most
182
+ * `options.proposalDeferralTimeoutMs` (then `reject`, `proposalExpired`).
183
+ */
184
+ readonly onProposal?: ProposalCallback;
185
+ /**
186
+ * Receives every inbox rumor `marmot` does not handle itself and no
187
+ * `registerInboxHandler` handler claimed — unmodified (AC-INBOX-2). Same
188
+ * delivery contract as an {@link InboxHandler}: at-least-once, so it MUST
189
+ * tolerate redelivery. Omitted: such rumors are dropped (`unhandled`).
190
+ *
191
+ * Handlers run on the inbox queue and block all inbox dispatch until they
192
+ * settle: do not await `group.send` or other long work — persist what you
193
+ * need and return, or fire-and-forget. Delivery is at-least-once; a throw
194
+ * counts toward the 10-retry cap and each retry re-decrypts the wrap.
195
+ */
196
+ readonly onApplicationRumor?: InboxHandler;
197
+ /**
198
+ * S10 (AC-HIST-3): the rumor history backend — where accepted application messages are retained for
199
+ * `group.history()`, withdrawn on a rewind and purged on teardown. Optional: live delivery
200
+ * (`group.onNotification`) never depends on it.
201
+ */
202
+ readonly history?: HistoryBackend;
203
+ /** S10 (AC-MEDIA-2): the media cache seam `encryptMedia`/`decryptMedia` keep ciphertexts in (no network, ever). */
204
+ readonly mediaCache?: MediaCache;
205
+ readonly options?: ClientOptions;
206
+ }
207
+ export interface MarmotClientEvents {
208
+ /** AC-INBOX-6: fires after the enrolment-approval transaction commits. */
209
+ enrolmentApproved: LifecycleEventPayloads['enrolmentApproved'];
210
+ /** AC-INBOX-6: fires after the forget transaction commits. */
211
+ deviceForgotten: LifecycleEventPayloads['deviceForgotten'];
212
+ /** AC-INBOX-6: fires after the created group's state and account index entry committed. */
213
+ groupCreated: LifecycleEventPayloads['groupCreated'];
214
+ /**
215
+ * A peer removed this device from the group and the removal settled (no longer revisable) — `{ groupId, actor? }`,
216
+ * `actor` the hex account identity of the admin whose removing commit was selected (as `group-disbanded` names it);
217
+ * absent when the committer cannot be resolved. The group and its history stay held, read-only; the application decides whether to `abandon()` it. Not fired for a
218
+ * removal this device requested (`leave()`, an own-leaf `devices.forget`, a teardown in progress or given up). At
219
+ * most once: a crash between the settle and the emit loses it (do not depend on it for correctness). A removal whose
220
+ * window passed while the client was not running is announced when the group is first loaded after the restart, so
221
+ * attach the listener before loading groups. A fenced group still announces its settled removal.
222
+ */
223
+ groupRemoved: {
224
+ readonly groupId: string;
225
+ readonly actor?: string;
226
+ };
227
+ /**
228
+ * Epic marmot-device-key-rotation (S7, AC-ROT-8): `devices.rotateKey()` committed its prepare transaction — `{ rotationId, from,
229
+ * to, groups }`. Fires once per rotation, never for a failed prepare, at most once across a crash (a crash between the commit
230
+ * and the emit loses it: do not depend on it for correctness).
231
+ */
232
+ deviceKeyRotated: LifecycleEventPayloads['deviceKeyRotated'];
233
+ /** Epic marmot-device-key-rotation (S7, AC-ROT-8): every group of the rotation is terminal — `{ rotationId, perGroupOutcome }`; fires once. */
234
+ deviceKeyRotationSettled: LifecycleEventPayloads['deviceKeyRotationSettled'];
235
+ /**
236
+ * S8 (AC-DEV-5, AC-DEV-9): an enrolment request of a new device of this
237
+ * account passed the replay, expiry and rate checks and is recorded — the
238
+ * approval prompt. Answer with `devices.approveEnrolment(requestId)`;
239
+ * `devices.pendingEnrolments()` lists the open ones.
240
+ */
241
+ enrolmentRequested: EnrolmentPrompt;
242
+ /** S8 (AC-KP-7): another account offered a KeyPackage for a group this client holds (recorded; see `invitations.offers()`). */
243
+ keyPackageOffered: KeyPackageOffer;
244
+ authFailed: {
245
+ readonly relayUrl: string;
246
+ readonly error: unknown;
247
+ };
248
+ /**
249
+ * marmot-transport-connected-signal: the transport adapter reported a (re)connect to `relayUrl` through
250
+ * `transportEvents.connected` — the raw relay string as reported (ADR-014). How an extension such as
251
+ * `account-sync` learns of reconnects without its own wiring into the adapter.
252
+ */
253
+ transportConnected: {
254
+ readonly relayUrl: string;
255
+ };
256
+ confirmBlocked: {
257
+ readonly groupId: string;
258
+ readonly intentId: string;
259
+ readonly error: unknown;
260
+ };
261
+ /**
262
+ * AC-HOOK-6, AC-BAR-2: an own commit was published although an `onBeforePublish` hook threw (`hook-error`), a
263
+ * barrier rejected (`barrier-failed`, with the `error`) or the `beforePublishTimeoutMs` deadline passed with a
264
+ * barrier pending (`barrier-timeout`). Best-effort by decision: the commit is never held back by a hook.
265
+ */
266
+ beforePublishSkipped: BeforePublishSkipped;
267
+ /**
268
+ * A relay is excluded from this group's history requests for the session
269
+ * (AC-PIPE-14): `timeout` — it caused `historySilenceThreshold` consecutive
270
+ * history timeouts; `no-progress` — for that many consecutive passes it
271
+ * answered, but with nothing inside the requested window (e.g. it ignores
272
+ * `until`), so the history walk could not advance past it.
273
+ */
274
+ relaySilent: {
275
+ readonly groupId: string;
276
+ readonly relayUrl: string;
277
+ readonly reason: 'timeout' | 'no-progress';
278
+ };
279
+ /**
280
+ * A relay returned a full page of history events all stamped with one
281
+ * second and then proved to hold more: events of that second beyond its
282
+ * cap cannot be paged to (NIP-01 `until` has one-second resolution) and
283
+ * may never be fetched from it. Fires once per relay and second per session.
284
+ */
285
+ historyGap: {
286
+ readonly groupId: string;
287
+ readonly relayUrl: string;
288
+ readonly createdAt: number;
289
+ };
290
+ storeIncompatible: {
291
+ readonly key: string;
292
+ readonly error: MarmotError;
293
+ };
294
+ /**
295
+ * A durable intent went `terminal` with no `send()` caller left to reject: resumed after reload (AC-PIPE-3), or
296
+ * accepted `awaiting-sync` and then fenced (`fenced`) or refused after its release (AC-PIPE-15).
297
+ */
298
+ intentFailed: {
299
+ readonly groupId: string;
300
+ readonly intentId: string;
301
+ readonly error: MarmotError;
302
+ };
303
+ /**
304
+ * A failed group operation could not roll the group's in-memory state back
305
+ * (`store-failed`, `cause` = the rollback failure); the group reloads its
306
+ * durable state before its next operation.
307
+ */
308
+ groupStateFailed: {
309
+ readonly groupId: string;
310
+ readonly error: MarmotError;
311
+ };
312
+ /**
313
+ * A Welcome delivery went `failed` (no inbox relay, every relay refused it,
314
+ * or `maxPublishAttempts` publishes failed); `group.retryWelcome(inviteeRef)`
315
+ * re-delivers it (S5). Reasons from a rewind: `commit-withdrawn` (the invite commit lost a race; the Welcome was not yet published) and
316
+ * `delivered-on-abandoned-branch` (additive, epic marmot-rewound-own-commit-no-signal S4: the Welcome WAS delivered, its invite
317
+ * commit was abandoned and NOTHING re-delivers it automatically -- fired only (a) for an invite re-drive's commit whose root a restore of the
318
+ * original just brought back (the invitee holds the re-drive's branch, which the group left), and (b) for an own invite whose withdrawal writes no
319
+ * re-drive record (unreadable diff, or a marker without changes). Decided once, in the abandoning transition: when a re-drive that was written
320
+ * later loses the change, the application hears `own-change-lost` `{ member-added }` with its reason instead, not this. Never when the library
321
+ * re-drives the invite (the new Welcome can move the invitee), for an enrolment approval it re-issues, or for a forget. `retryWelcome` on such a
322
+ * delivery is refused (`send-rejected`, `details.reason: 'abandoned-branch'`). The invitee may sit on a branch the group left: remove it and invite it again with a
323
+ * fresh KeyPackage; `retryWelcome` does not apply, nothing failed to publish).
324
+ */
325
+ welcomeFailed: {
326
+ readonly groupId: string;
327
+ readonly inviteeRef: string;
328
+ readonly reason: string;
329
+ };
330
+ /**
331
+ * A Welcome delivery that a rewind had failed (`welcomeFailed` with reason `commit-withdrawn`) was put back to
332
+ * `pending` because its invite commit is on the canonical path again; it is delivered in the background.
333
+ */
334
+ welcomeRestored: {
335
+ readonly groupId: string;
336
+ readonly inviteeRef: string;
337
+ };
338
+ /**
339
+ * Reconciling the group's undelivered invite Welcomes with a rewind (or with the stored window on load) failed;
340
+ * the deliveries are left as they were and the next load tries again.
341
+ */
342
+ welcomeReconcileFailed: {
343
+ readonly groupId: string;
344
+ readonly error: unknown;
345
+ };
346
+ /**
347
+ * S7 (AC-HYG-3): the invitee of a Welcome delivery declined it — a DECLINE rumor sealed by the delivery's
348
+ * invitee account, naming that Welcome's id (SHA-256 of the MLS Welcome) and group. Fires once per delivery,
349
+ * after it went `declined` durably (terminal: no further automatic or `retryWelcome` publish); a redelivered or
350
+ * repeated decline does not fire it again, nor does a decline from any other account. The rumor itself still
351
+ * reaches `onApplicationRumor` unchanged.
352
+ */
353
+ welcomeDeclined: {
354
+ readonly groupId: string;
355
+ readonly inviteeRef: string;
356
+ };
357
+ /**
358
+ * What the inbox did with one inbound kind-1059 wrap (S6): `joined`,
359
+ * `already-member`, `pending` (an unexpected Welcome, see
360
+ * `invitations.pending()`), `no-matching-keypackage`, `rejected` (terminal,
361
+ * with `reason`), `deferred` (retried by the next inbox pass; a throwing
362
+ * handler's `handler-failed` counts toward the processing-failure cap),
363
+ * `delivered` (S7: a `registerInboxHandler` handler or `onApplicationRumor`
364
+ * took it, `to` saying which) or `unhandled` (nothing takes that rumor
365
+ * kind). A wrap already in the seen-set produces none.
366
+ */
367
+ inboxDisposition: InboxDisposition;
368
+ /**
369
+ * inbox-handler-time-budget: an inbox consumer callback (`surface`: a `registerInboxHandler` handler or
370
+ * `onApplicationRumor`) is still running `budgetMs` (`inboxHandlerBudgetMs`) after it was called for the rumor of
371
+ * `wrapId`. Diagnostic only — the handler keeps running and the inbox queue (Welcomes included) keeps waiting for
372
+ * it; fires at most once per call.
373
+ */
374
+ handlerSlow: {
375
+ readonly surface: 'inboxHandler' | 'onApplicationRumor';
376
+ readonly rumorKind: number;
377
+ readonly wrapId: string;
378
+ readonly budgetMs: number;
379
+ };
380
+ /**
381
+ * A proposal `onProposal` deferred passed its deadline
382
+ * (`proposalDeferralTimeoutMs` after `deferredAt`, its first deferral, in
383
+ * client-clock ms) and was treated as `reject`: dropped from the staged set
384
+ * (durably, before this fires), so own commits are no longer refused
385
+ * `proposal-deferred` and queued rumors go out after the next commit
386
+ * (AC-INVITE-4). Once per proposal; a crash between the drop and the emit
387
+ * still emits it (on the next evaluation, at the latest the reload), and a
388
+ * crash right after the emit may emit it once more with the same payload —
389
+ * deduplicate by `(groupId, proposalRef)`.
390
+ */
391
+ proposalExpired: {
392
+ readonly groupId: string;
393
+ readonly proposalRef: string;
394
+ readonly deferredAt: number;
395
+ };
396
+ /** A Welcome was joined (inbox auto-accept under `expectWelcome`, `accept(id)`), after the join committed. */
397
+ groupJoined: {
398
+ readonly groupId: string;
399
+ readonly invitationId: string;
400
+ };
401
+ /**
402
+ * A competing Welcome moved a group this client already held onto its branch (epic `marmot-welcome-race-joiner`):
403
+ * a second valid Welcome for the group named a branch the MIP-03 rule ranks above the held one, so the group was
404
+ * rebased onto it. `from` and `to` are the hex confirmation tags of the abandoned tip and of the Welcome's state;
405
+ * `invitationId` is the competing Welcome's. What the abandoned branch applied is withdrawn (`withdrawn`,
406
+ * `message-withdrawn` notifications) — messages sent on it are NOT re-sent; the application re-sends them. Fires
407
+ * once per switch (a crash between this report and the invitation's confirmation reports it again on the next pass:
408
+ * deduplicate by `invitationId`), also when the switch was decided in an inbox pass with no wrap in hand (the inbox
409
+ * disposition `branch-switched` is reported only when the switch ran inside a Welcome's dispatch); `groupJoined`
410
+ * does not fire again.
411
+ */
412
+ groupBranchSwitched: {
413
+ readonly invitationId: string;
414
+ readonly groupId: string;
415
+ readonly from: string;
416
+ readonly to: string;
417
+ };
418
+ /**
419
+ * An invitation's maintenance — rotate-after-consume of the consumed
420
+ * KeyPackage, the decline rumor's delivery, or completing an interrupted
421
+ * join — failed permanently 10 times (the signer or user refused, a
422
+ * malformed record) and is given up: no further retries or signer prompts.
423
+ */
424
+ maintenanceFailed: {
425
+ readonly invitationId: string;
426
+ readonly kind: MaintenanceKind | DeviceMaintenanceKind;
427
+ readonly reason: string;
428
+ /** `enrolment-approval` only: the groups the device joined before the approval was given up (enrolmentApproved names them too). */
429
+ readonly groups?: readonly string[];
430
+ };
431
+ }
432
+ export type MarmotClientEventName = keyof MarmotClientEvents;
433
+ /** What `group.send()` accepts: an application rumor, a proposal, a commit of pending proposals, or a self-update. */
434
+ export type GroupIntent = {
435
+ readonly type: 'application';
436
+ readonly rumor: Rumor;
437
+ } | {
438
+ readonly type: 'proposal';
439
+ readonly proposal: unknown;
440
+ } | {
441
+ readonly type: 'commit';
442
+ } | {
443
+ readonly type: 'self-update';
444
+ };
445
+ /** Per-event ingest outcome (AC-PIPE-4..7). */
446
+ export type IngestDisposition = {
447
+ readonly kind: 'applied';
448
+ readonly eventId: string;
449
+ } | {
450
+ readonly kind: 'application';
451
+ readonly eventId: string;
452
+ readonly rumor: Rumor;
453
+ readonly orderingKey: OrderingKey;
454
+ } | {
455
+ readonly kind: 'duplicate';
456
+ readonly eventId: string;
457
+ } | {
458
+ readonly kind: 'retryable';
459
+ readonly eventId: string;
460
+ readonly reason: string;
461
+ } | {
462
+ readonly kind: 'rejected';
463
+ readonly eventId: string;
464
+ readonly reason: string;
465
+ };
466
+ export type { OrderingKey } from '../history/index.js';
467
+ export type { GroupSnapshot } from './group-snapshot.js';
468
+ export type { InboxRumorDelivery } from './inbox-send.js';
469
+ /** `MarmotGroup.disbanded`: the selected disband (the `group-disbanded` notification's fields). */
470
+ export interface GroupDisbanded {
471
+ /** Hex account identity of the admin whose disband commit was selected. */
472
+ readonly actor: string;
473
+ /** The MLS epoch the disband commit was made at (its parent's epoch). */
474
+ readonly epoch: bigint;
475
+ /** Hex MLS confirmation tag of that parent state. */
476
+ readonly nodeTag: string;
477
+ /** Hex digest of the selected disband commit. */
478
+ readonly commitDigest: string;
479
+ /** Client-clock milliseconds at which this client recorded the settlement. */
480
+ readonly at: number;
481
+ }
482
+ export interface PendingIntent {
483
+ readonly intentId: string;
484
+ /**
485
+ * `awaiting-sync` (AC-PIPE-15): accepted by `send()` after the group was loaded, before its first post-load sync
486
+ * completed — nothing has been encrypted for it yet. Released (encrypted and published) once that sync completes;
487
+ * failed `fenced` via `intentFailed`, never published, when the sync fences the group (AC-HIST-4).
488
+ */
489
+ readonly state: 'pending-publish' | 'pending-confirm' | 'queued' | 'awaiting-sync';
490
+ /** The `GroupIntent` type the record was created for. */
491
+ readonly kind: GroupIntent['type'];
492
+ }
493
+ export type { AppliedNotification, GroupDisbandedNotification, GroupNotification, HistoryBackend, HistoryEntry, LeafEquivocationNotification, MessageNotification, MessageWithdrawnNotification, WithdrawnNotification, } from '../history/index.js';
494
+ /**
495
+ * Why an `onConfirm` hook runs (AC-MX-1): the confirmed own intent's `GroupIntent` type, or `'create'` /
496
+ * `'join'` for a group this client just created (`groups.create`) or adopted from a Welcome. Its own union —
497
+ * `GroupIntent['type']` (what `send()` accepts) is not widened.
498
+ */
499
+ export type ConfirmKind = GroupIntent['type'] | 'create' | 'join';
500
+ /**
501
+ * What an `onConfirm` hook receives. It runs INSIDE the transaction that persists the group state —
502
+ * a confirmation's, `groups.create`'s (`kind: 'create'`) or a Welcome adoption's (`kind: 'join'`, only when
503
+ * the adoption wrote the group): writes through `tx` commit atomically with that state, and a throw aborts the
504
+ * whole transaction — the confirmation (retried, AC-PIPE-2, AC-PIPE-13), the creation (`groups.create` rejects
505
+ * with the hook's error, nothing is stored) or the adoption (nothing is stored; the join is completed by a later
506
+ * inbox pass). Use `tx`, never the store itself (storage re-entrancy rule). Never run for a foreign commit's
507
+ * ingest, nor for a `groups.restore` adoption: a restore produces no `'create'`/`'join'` — its first hook run is
508
+ * the confirmation of the restore's own self-update (`kind: 'self-update'`).
509
+ */
510
+ export interface ConfirmContext {
511
+ readonly groupId: string;
512
+ /** The confirmed intent's id; the group id for `'create'` / `'join'`. */
513
+ readonly intentId: string;
514
+ readonly kind: ConfirmKind;
515
+ /** Epoch of the persisted state. */
516
+ readonly epoch: bigint;
517
+ readonly tx: GroupStoreTx;
518
+ /** Notifications the confirmed commit produces (empty for application messages, `'create'` and `'join'`). */
519
+ readonly notifications: readonly AppliedNotification[];
520
+ /**
521
+ * AC-MX-1: the state this transaction persists (with its retained rewind window), as an opaque enveloped
522
+ * {@link GroupSnapshot} — what `groups.restore(groupId, snapshot)` needs to resume as this leaf. Store it
523
+ * through `tx` to keep it atomic with the state it describes. Built lazily on the first read and memoized (a
524
+ * hook that never reads it costs no serialization); readable only while the hooks run — a first read after the
525
+ * hook returned throws `transaction-closed`.
526
+ */
527
+ readonly snapshot: GroupSnapshot;
528
+ /**
529
+ * AC-MX-6: set only on the confirmation of the commit `devices.forget` issues to remove another device's leaves
530
+ * from this group — the signature keys (hex) of the leaves it removes. Present while the hooks run, so a hook can
531
+ * act before anything of this confirmation leaves the device: `deviceForgotten` fires only once every group of
532
+ * the forget is settled, after this confirmation's own hooks (and the publishes they scheduled) ran.
533
+ */
534
+ readonly forgetting?: {
535
+ readonly leafKeys: readonly string[];
536
+ };
537
+ }
538
+ export type ConfirmHook = (confirmation: ConfirmContext) => void | Promise<void>;
539
+ export interface LeafInfo {
540
+ readonly leafIndex: number;
541
+ readonly leafKey: string;
542
+ }
543
+ export type { EncryptedMedia, EncryptMediaOptions, MediaCache } from '../media/index.js';
544
+ export interface MarmotGroup {
545
+ readonly id: string;
546
+ readonly nostrGroupId: string;
547
+ readonly name: string;
548
+ /** The group's description (`marmot.group.profile.v1`); `''` for a group created without one. Changes with a committed `rename`. */
549
+ readonly description: string;
550
+ readonly admins: readonly string[];
551
+ readonly relays: readonly string[];
552
+ readonly epoch: bigint;
553
+ /**
554
+ * The peer disband that ended this group, once the convergence settlement selected it (BACKLOG
555
+ * `marmot-disband-settled-store-divergence`) — `undefined` while the group is live. Durable: a reload keeps it.
556
+ * A disbanded group does not sync, rejects input (`rejected`, reason `group-disbanded`) and refuses `send` and the
557
+ * other own-commit operations as well as `synced()` with `not-a-member` (details `reason: 'disbanded'`); reads,
558
+ * `history()`, `equivocations()` and `abandon()` / `destroy()` still work. The stored state stays the disband's
559
+ * parent (`epoch` does not move). Announced once by a `group-disbanded` notification.
560
+ */
561
+ readonly disbanded: GroupDisbanded | undefined;
562
+ /**
563
+ * Intent -> publish -> confirm (AC-PIPE-1..3). An application rumor sent while proposals are staged
564
+ * is queued and resolves once published after the next confirmed commit (AC-INVITE-3); queued
565
+ * rumors go out in order, and one queued before an `invite()` is released at that commit's new
566
+ * epoch — readable by the new invitee. When the commit the queue makes goes terminal, it emits
567
+ * `intentFailed` and the send that triggered it rejects `send-rejected`; the rumor stays queued.
568
+ *
569
+ * AC-PIPE-15: on a group handle obtained by loading stored state (`groups.get`/`groups.list`), a send issued
570
+ * before the group's first post-load sync completed resolves once the intent is durably recorded
571
+ * `awaiting-sync` — nothing is encrypted yet (the stored state may be a restored, rolled-back snapshot). It
572
+ * is encrypted and published once that sync completes; its terminal failure is reported by `intentFailed`
573
+ * (`fenced` when the sync fences the group, AC-HIST-4).
574
+ */
575
+ send(intent: GroupIntent): Promise<void>;
576
+ /**
577
+ * AC-PIPE-15: resolves once the group has completed its first sync since this client loaded it — every group
578
+ * relay returned EOSE or was excluded as silent (AC-PIPE-14); at once for a group this client instance created
579
+ * or joined, or that already synced. Until then `send()` records `awaiting-sync` intents and `invite`,
580
+ * `setAdmins`, `rename`, `removeMember`, `departAsAdmin`, `leave` and `devices.forget` are refused `commit-pending` (reason
581
+ * `awaiting-sync`). Never settles while no sync can complete (offline). Rejects `fenced` when the group is or
582
+ * becomes fenced (AC-HIST-4), `disposed` / `not-a-member` when the client is disposed / the group abandoned.
583
+ */
584
+ synced(): Promise<void>;
585
+ ingest(events: readonly NostrEvent[]): Promise<readonly IngestDisposition[]>;
586
+ /**
587
+ * The durable outbound intents, read directly — NOT serialised behind the group's operation queue: an intent can
588
+ * vanish from the list a moment before `epoch` reflects its confirmed commit (the confirmation transaction deletes
589
+ * the record, then the confirming operation applies the state). Every group operation runs on that per-group queue,
590
+ * so `await group.ingest([])` afterwards is a barrier: once it resolves the confirmation is fully applied.
591
+ */
592
+ pendingIntents(): Promise<readonly PendingIntent[]>;
593
+ members(): readonly string[];
594
+ memberCount(): number;
595
+ leaves(account: string): readonly LeafInfo[];
596
+ /**
597
+ * One commit adding every KeyPackage, then one Welcome per invitee; resolves with each invitee's
598
+ * Welcome outcome (AC-INVITE-1/2). Rumors queued before it (AC-INVITE-3) are released at the
599
+ * invite commit's new epoch, so the invitees can read them.
600
+ *
601
+ * Fork loss: a withdrawn invite commit is re-driven automatically from the retained KeyPackage events (`welcomeFailed`
602
+ * `commit-withdrawn`, `own-change-withdrawn` `{ member-added }`, then `own-change-reapplied` or `own-change-lost`); the re-driven
603
+ * Welcome has a new `inviteId` and the same `inviteeRef`. A manual re-invite of the same KeyPackage after the re-drive is refused
604
+ * `send-rejected` (the engine rejects a second leaf under that signature key); wait for the terminal.
605
+ */
606
+ invite(keyPackages: readonly NostrEvent[]): Promise<readonly WelcomeOutcome[]>;
607
+ /**
608
+ * Re-wraps and re-publishes `inviteeRef`'s Welcome (its KeyPackageRef) — never a new commit (AC-INVITE-2). A delivery marked
609
+ * `welcomeFailed` `delivered-on-abandoned-branch` is refused `send-rejected` (`details.reason: 'abandoned-branch'`): remove the
610
+ * member and invite it again with a fresh KeyPackage.
611
+ */
612
+ retryWelcome(inviteeRef: string): Promise<WelcomeOutcome>;
613
+ activeAdmins(): readonly string[];
614
+ isActiveAdmin(account: string): boolean;
615
+ isLastActiveAdmin(account: string): boolean;
616
+ /**
617
+ * Sets the admin list in ONE durable commit. Fork loss: re-driven per account (only the flips nobody else changed since the fork
618
+ * point survive, applied to the current tip's list); reported through `own-change-*` (`{ admin }` changes). `departAsAdmin`'s demotion
619
+ * commit is re-driven the same way; if the device's own leave lands first the flip is lost `stranded`.
620
+ */
621
+ setAdmins(accounts: readonly string[]): Promise<void>;
622
+ /**
623
+ * Renames the group: ONE admin commit that replaces the group profile (`marmot.group.profile.v1`: name AND
624
+ * description). `description` omitted keeps the CURRENT description; `description: ''` clears it. An omitted
625
+ * description is resolved when the call is made and stored by value. A concurrent change is never merged: if another
626
+ * admin's profile commit is applied before this commit is built, the rename rejects `send-rejected` (stale epoch) and
627
+ * that profile stands; in a same-epoch race the fork rule keeps one whole profile. An unchanged profile still
628
+ * commits. `onConfirm` hooks see `kind: 'commit'`.
629
+ *
630
+ * Refusals, each with nothing recorded and the epoch unchanged: `invalid-options` for a `name` that is not a
631
+ * non-empty string of at most 256 UTF-8 bytes or a `description` that is not a string of at most 4096 UTF-8 bytes
632
+ * (byte limits, not character counts); `invalid-options` with `details.reason: 'not-admin'` for a caller that is
633
+ * not an admin (a non-admin proposes the rename instead: send `{ type: 'proposal', proposal:
634
+ * groupProfileProposal(...) }` and let an admin send `{ type: 'commit' }`); `commit-pending` while an own commit
635
+ * is pending. A caller that is not a member, or whose pre-sync gate is closed, is refused first, as for every own
636
+ * commit (`not-a-member`, `commit-pending` with `details.reason: 'awaiting-sync'`). An admin demoted between the
637
+ * call and the build is rejected `send-rejected`, like `setAdmins`.
638
+ *
639
+ * Fork loss: re-driven per component; if anyone else changed the profile since the fork point it is lost `concurrent-change`
640
+ * (never merged) and reported through `own-change-*`.
641
+ *
642
+ * While a group-profile (`0x8001`) proposal is staged on the group (another member's, or one of your own), `rename`
643
+ * is rejected `send-rejected` (`details.reason: 'staged-profile-update'`) with nothing recorded and the state
644
+ * unchanged, because a commit that carried the staged proposal and this rename would hold two profile updates;
645
+ * commit the staged proposal first (`send({ type: 'commit' })`).
646
+ */
647
+ rename(name: string, options?: {
648
+ readonly description?: string;
649
+ }): Promise<void>;
650
+ /**
651
+ * Removes `account`: ONE admin commit that removes every leaf the account holds when the commit is built (the stored intent
652
+ * names the account). An admin may remove another admin in the same commit, with no demotion first: the engine's coupling
653
+ * splice drops the removed admin's entry atomically.
654
+ *
655
+ * Refusals, nothing recorded, epoch unchanged: `invalid-options` with `details.reason` `'malformed-account'`, `'self'`
656
+ * (use `departAsAdmin()` or `leave()`) or `'not-admin'`; `commit-pending` while an own commit is pending; `not-a-member` /
657
+ * `commit-pending` (`awaiting-sync`) first, as for every own commit. An account that holds no leaf (never a member, or
658
+ * already removed) resolves as a no-op. An admin demoted between the call and the build is rejected `send-rejected`.
659
+ *
660
+ * Staged proposals: a staged Remove or SelfRemove of the account's leaf is skipped (carried by reference). `send-rejected`,
661
+ * nothing recorded, when a staged Add admits a leaf of the account (`'staged-add-of-removed-account'`), when a staged Update
662
+ * names the account's leaf, or when a staged admin-list change still names a removed admin
663
+ * (`'staged-admin-policy-update'`): commit the staged proposal first (`send({ type: 'commit' })`) and retry. A staged
664
+ * admin-list change is committed together with the removal.
665
+ *
666
+ * Removed side (Q1 option a): each device keeps a tombstoned group (read-only, `members()` without the account, own
667
+ * commits refused `not-a-member`); its own group emits no `leaf-removed` notification (the remaining members' groups do).
668
+ * The app calls `abandon()` / `destroy()`. Success is final once the commit is canonical, or re-driven: if a same-epoch fork loss withdraws it, this device (only it)
669
+ * re-checks the removal against the winning tip and re-drives it as a fresh commit; the application hears `own-change-withdrawn`
670
+ * `{ member-removed }`, then `own-change-reapplied` or `own-change-lost` (`already-applied`, `reversed`, `concurrent-change`, `not-admin`,
671
+ * `stranded`, `attempts-exhausted`). `leaf-removal-withdrawn` is unchanged. A record that outlives a concurrent remove-and-re-add of the same device by another admin removes the account again.
672
+ */
673
+ removeMember(account: string): Promise<void>;
674
+ departAsAdmin(): Promise<void>;
675
+ leave(): Promise<void>;
676
+ abandon(): Promise<void>;
677
+ destroy(): Promise<void>;
678
+ /**
679
+ * Encrypts `bytes` as `encrypted-media-v1` under the current epoch's key (AC-MEDIA-1): `{ ciphertext, imeta,
680
+ * locator }` — `locator` the ciphertext's SHA-256 (hex), under which the media cache (if configured) keeps it.
681
+ * Nothing is uploaded: the application stores the ciphertext (e.g. Blossom) and sends a rumor carrying `imeta`.
682
+ */
683
+ encryptMedia(bytes: Uint8Array, options?: EncryptMediaOptions): Promise<EncryptedMedia>;
684
+ /**
685
+ * Decrypts media described by `media.imeta`, trying every epoch the group retains. An empty `ciphertext` is
686
+ * looked up in the media cache by `locator` (`invalid-options` / `not-found` when absent).
687
+ */
688
+ decryptMedia(media: EncryptedMedia): Promise<Uint8Array>;
689
+ /** The retained application rumors (the history backend's, in delivery order); none without a backend (AC-HIST-3). */
690
+ history(): AsyncIterable<Rumor>;
691
+ /**
692
+ * Live notifications (AC-HIST-2/3), each after the state it describes was persisted: `applied` / `withdrawn`
693
+ * (a commit's state changes, keyed by its digest; a rewind withdraws them under the same digest), `message`
694
+ * (an accepted application message with its `OrderingKey`) and `message-withdrawn`. Also `own-change-withdrawn` (at most once)
695
+ * and `own-change-reapplied` / `own-change-lost` (at least once, retained until the group's first listener) for own commits a fork
696
+ * loss withdrew. Returns an unsubscribe.
697
+ */
698
+ onNotification(listener: (notification: GroupNotification) => void): () => void;
699
+ /**
700
+ * Every leaf equivocation this member has recorded for the group (ADR-016) — the durable source of truth behind the
701
+ * live `leaf-equivocation` notification, which is a hint delivered at most once per `(nodeTag, leafIndex)` and lost
702
+ * when no listener is attached or the process ends before dispatch. Ordered by `(epoch, nodeTag, leafIndex)`;
703
+ * `[]` when none. A direct read of the group store (not serialised behind the group's operation queue), available
704
+ * on a fenced group; rejects `disposed` / `not-a-member` like every other accessor.
705
+ */
706
+ equivocations(): Promise<readonly LeafEquivocationNotification[]>;
707
+ }
708
+ export interface WelcomeManifest {
709
+ /** Hex MLS group id. */
710
+ readonly groupId: string;
711
+ /** Hex KeyPackageRef of the local KeyPackage the Welcome must consume. */
712
+ readonly keyPackageRef: string;
713
+ /** The account expected to send the Welcome (a member of the group). */
714
+ readonly sponsorAccount: string;
715
+ /** Client-clock milliseconds; a Welcome processed at or after it is not auto-accepted. */
716
+ readonly deadline: number;
717
+ }
718
+ /**
719
+ * A `registerInboxHandler` handler (and the shape of `onApplicationRumor`):
720
+ * receives the rumor as unwrapped and its kind-1059 wrap, both frozen.
721
+ *
722
+ * Handlers run on the inbox queue and block all inbox dispatch (Welcomes
723
+ * included) until they settle: do not await `group.send` or other long work —
724
+ * `send` resolves only once published, which can take as long as the next
725
+ * admin commit or a remote signer's approval. Persist what you need and
726
+ * return, or fire-and-forget.
727
+ *
728
+ * Delivery is at-least-once — the wrap is marked seen only after the handler
729
+ * resolved, so a crash or reload in between, or the wrap id's eviction from
730
+ * the bounded seen-set, redelivers the rumor: handlers MUST tolerate
731
+ * redelivery (AC-INBOX-4). A throw counts toward the 10-retry cap (then the
732
+ * wrap is dropped, `rejected('processing-failed')`) and each retry
733
+ * re-decrypts the wrap. Account-scope client operations called from inside a
734
+ * handler reject `reentrant` (ADR-013).
735
+ */
736
+ export type InboxHandler = InboxRumorHandler;
737
+ export interface MarmotClient {
738
+ /** The account-key signer: the construction `signer` behind `withSignerBudget(signer, budget)`. Every account-key call goes through it. */
739
+ readonly signer: Signer;
740
+ /** Same value as the module export `permissions` (AC-API-7). */
741
+ readonly permissions: PermissionDeclaration;
742
+ readonly groups: {
743
+ create(name: string, options?: {
744
+ readonly relays?: readonly string[];
745
+ readonly admins?: readonly string[];
746
+ }): Promise<MarmotGroup>;
747
+ get(groupId: string): Promise<MarmotGroup | undefined>;
748
+ list(): Promise<readonly MarmotGroup[]>;
749
+ /**
750
+ * AC-MX-2: resumes as the leaf `snapshot` (an `onConfirm` hook's `ConfirmContext.snapshot`) was taken from:
751
+ * adopts it with its rewind window, runs the group's first sync (replaying every commit since from the group
752
+ * relays), commits a self-update and resolves the handle only once that self-update is confirmed — so the
753
+ * relays hold it before any application message from this client. Rejects `envelope-mismatch` (another engine
754
+ * / ts-mls build — a snapshot is restorable only by the build that took it —, or not a well-formed snapshot:
755
+ * a serialized state of another group than its payload names, a rewind window that is no tree below its tip
756
+ * within the rollback horizon), `invalid-options` (a snapshot whose serialized MLS state is of another group
757
+ * than `groupId`), `already-member` (the group is held or being restored) and
758
+ * `reentrant` (from an account-scope surface or a group's `onConfirm` hook) before anything is written; any
759
+ * later failure (`fenced` — also when the group is fenced after its first sync —, `not-a-member` — torn down
760
+ * meanwhile —, `send-rejected`, `disposed`) removes the adopted group again. Until it settles, `groups.get`
761
+ * of it waits (rejecting `reentrant` from inside a consumer surface) and `groups.list` skips it. Never settles
762
+ * while no sync can complete (offline), like `MarmotGroup.synced()`.
763
+ */
764
+ restore(groupId: string, snapshot: GroupSnapshot): Promise<MarmotGroup>;
765
+ };
766
+ readonly keyPackages: {
767
+ create(options?: {
768
+ readonly relays?: readonly string[];
769
+ readonly lastResort?: boolean;
770
+ }): Promise<NostrEvent>;
771
+ list(): Promise<readonly NostrEvent[]>;
772
+ count(): Promise<number>;
773
+ rotate(ref: string): Promise<NostrEvent>;
774
+ forget(ref: string): Promise<void>;
775
+ observe(account: string, listener: (event: NostrEvent) => void): () => void;
776
+ /**
777
+ * S8 (AC-KP-7): mints a fresh KeyPackage and offers it to sponsor `to` for
778
+ * `groupId` — a gift-wrapped offer rumor on `to`'s inbox relays; the group
779
+ * id never appears outside the wrap.
780
+ */
781
+ offer(options: {
782
+ readonly groupId: string;
783
+ readonly to: string;
784
+ }): Promise<{
785
+ readonly offerId: string;
786
+ readonly keyPackageEvent: NostrEvent;
787
+ }>;
788
+ };
789
+ readonly invitations: {
790
+ expectWelcome(manifest: WelcomeManifest): Promise<void>;
791
+ pending(): Promise<readonly PendingInvitation[]>;
792
+ accept(id: string): Promise<MarmotGroup>;
793
+ decline(id: string, options?: {
794
+ readonly declineRumor?: boolean;
795
+ }): Promise<void>;
796
+ /** S8: KeyPackage offers received for groups this client holds (optionally one group's), oldest first; admit one with `group.invite([offer.keyPackageEvent])`. */
797
+ offers(groupId?: string): Promise<readonly KeyPackageOffer[]>;
798
+ };
799
+ readonly inbox: {
800
+ start(): Promise<void>;
801
+ stop(): Promise<void>;
802
+ };
803
+ /** S8: the account's devices (one leaf signature key per client instance) and same-account enrolment (ADR-003). */
804
+ readonly devices: {
805
+ list(): Promise<readonly DeviceInfo[]>;
806
+ requestEnrolment(options: EnrolmentRequestOptions): Promise<EnrolmentRequestHandle>;
807
+ pendingEnrolments(): Promise<readonly EnrolmentPrompt[]>;
808
+ /**
809
+ * Approves a prompted enrolment request (ADR-003). Call it from application (UI) code: from inside an
810
+ * inbox handler or `onApplicationRumor` it inherits their account-scope frame and its `group.invite`
811
+ * rejects `reentrant` (ADR-013).
812
+ */
813
+ approveEnrolment(requestId: string): Promise<EnrolmentApprovalOutcome>;
814
+ label(leafKey: string, label: string): Promise<void>;
815
+ forget(leafKey: string): Promise<DeviceForgetOutcome>;
816
+ /**
817
+ * Epic marmot-device-key-rotation (S7): re-keys this device. A fresh device signing key (its account identity proof signed
818
+ * once) becomes the device key in one transaction; every held group's own leaf is then re-keyed to it (a self-update commit
819
+ * per group), the KeyPackages signed with the old key are replaced and deleted, and `deviceKeyRotationSettled` fires when
820
+ * every group is terminal. Resolves after the prepare committed and one pass drove every group (`settled` tells whether it
821
+ * is finished; the rest continues in the background and after a restart). A rotation already open is returned. Rejects
822
+ * `invalid-options` with `details.reason`: `no-device-key` (nothing minted, no group), `device-forgetting` (this device's
823
+ * own forget is open), `rotation-unavailable`.
824
+ */
825
+ rotateKey(): Promise<DeviceKeyRotationOutcome>;
826
+ /** The open rotation, else the last one (`status`: `rotating` / `rotated` / `gave-up`); `undefined` when the device never rotated. */
827
+ rotation(): Promise<DeviceKeyRotationOutcome | undefined>;
828
+ };
829
+ readonly extensions: {
830
+ /**
831
+ * Routes every inbox rumor of `kind` to `handler` instead of
832
+ * `onApplicationRumor` (AC-INBOX-5); `handler-exists` / `reserved-kind`.
833
+ * Handlers run on the inbox queue and block all inbox dispatch until they
834
+ * settle: do not await `group.send` or other long work — persist what you
835
+ * need and return, or fire-and-forget. Delivery is at-least-once; a throw
836
+ * counts toward the 10-retry cap and each retry re-decrypts the wrap.
837
+ */
838
+ registerInboxHandler(kind: number, handler: InboxHandler): () => void;
839
+ onConfirm(hook: ConfirmHook): () => void;
840
+ /**
841
+ * AC-HOOK-1: registers a hook that runs for every own `commit` / `self-update` between its staging and its first
842
+ * publish, in its own transaction, handed the pending-tagged snapshot of the state the commit produces; the
843
+ * `PublishBarrier` it may return is awaited (best-effort, `beforePublishTimeoutMs`) before the publish. Returns
844
+ * the unregister function; throws `disposed` on a disposed client. A hook that throws, a barrier that rejects or
845
+ * times out never holds the commit back (`beforePublishSkipped`). From inside the hook or the barrier, a mutating
846
+ * operation on the group, `groups.restore`, `devices.*` and `sendInboxRumor` reject `reentrant`.
847
+ */
848
+ onBeforePublish(hook: BeforePublishHook): () => void;
849
+ /**
850
+ * `groups.create()` waits until `gate()` resolves and aborts with its
851
+ * rejection; a gate resolving `{ once: true }` is not asked again by this
852
+ * client instance (AC-INBOX-7). Returns the unregister function.
853
+ */
854
+ beforeCreateGroup(gate: CreateGroupGate): () => void;
855
+ /**
856
+ * AC-MX-3: gift-wraps `rumor` (the account's own, with its NIP-01 id) to `to` through the budgeted signer and
857
+ * publishes it once on `to`'s inbox relays (marmot's inbox resolution). Persists nothing, retries nothing:
858
+ * `{ status: 'delivered' | 'retryable' | 'failed', reason?, relays? }`. Rejects `reserved-kind` for a
859
+ * `RUMOR_KINDS` value (before any signer or transport call), `invalid-options` for a malformed input and
860
+ * `reentrant` from an account-scope surface or a group's `onConfirm` hook.
861
+ */
862
+ sendInboxRumor(input: {
863
+ readonly to: string;
864
+ readonly rumor: Rumor;
865
+ }): Promise<InboxRumorDelivery>;
866
+ };
867
+ /**
868
+ * Sinks for transport-adapter callbacks the narrowed `TransportContract`
869
+ * cannot carry: wire `authFailed` into the adapter's `onAuthFailed` option
870
+ * and `connected` into its (re)connect callback. Re-emitted as client
871
+ * events (`authFailed`, `transportConnected`) with the raw relay string
872
+ * (ADR-014); no-ops once the client is disposed.
873
+ */
874
+ readonly transportEvents: {
875
+ authFailed(relayUrl: string, error: unknown): void;
876
+ connected(relayUrl: string): void;
877
+ };
878
+ on<E extends MarmotClientEventName>(event: E, listener: (payload: MarmotClientEvents[E]) => void): () => void;
879
+ /** Releases listeners; every later call on this client throws `disposed`. Idempotent. */
880
+ dispose(): void;
881
+ }
882
+ /**
883
+ * Internal (tests only): the defects the integration properties' negative controls reintroduce into the commit re-drive (epic
884
+ * marmot-rewound-own-commit-no-signal, S6). Each one is a single guarded line in the production path; none is reachable from the public API.
885
+ */
886
+ export interface RedriveFaultsForTest {
887
+ /** AC-PROP-2 (b): the re-drive commit is built WITHOUT the surviving changes' payload, while `own-change-reapplied` is still dispatched for them. */
888
+ readonly dropPayload?: boolean;
889
+ /** AC-PROP-4: the lost verdicts of a re-drive build are dispatched BEFORE the mint transaction commits (and again once it has). */
890
+ readonly dispatchLostBeforeMint?: boolean;
891
+ }
892
+ /** Resolved construction state later client-module stories build on. */
893
+ export interface ClientContext {
894
+ readonly signer: Signer;
895
+ readonly transport: TransportContract;
896
+ readonly stores: ClientStores;
897
+ readonly relays: RelayOptions;
898
+ readonly verifier: EventVerifier | undefined;
899
+ readonly onProposal: ProposalCallback | undefined;
900
+ readonly clock: ClientClock;
901
+ readonly historySilenceThreshold: number;
902
+ readonly graceWindowMs: number;
903
+ readonly timers: ClientTimers;
904
+ readonly historyTimeoutMs: number;
905
+ readonly maxPublishAttempts: number;
906
+ /** AC-HOOK-1, AC-BAR-2: the `extensions.onBeforePublish` hooks and the barrier deadline. */
907
+ readonly beforePublish: BeforePublishRegistry;
908
+ readonly seenSetCap: number;
909
+ readonly enrolmentPromptRateLimit: number;
910
+ readonly maxGiftWrapBytes: number;
911
+ readonly leaveTimeoutMs: number;
912
+ /** S15 (AC-INVITE-4): deferral deadline of an `onProposal`-deferred proposal (ms; 0 = never). */
913
+ readonly proposalDeferralTimeoutMs: number;
914
+ /** S10: the optional history backend and media cache seams. */
915
+ readonly history: HistoryBackend | undefined;
916
+ readonly mediaCache: MediaCache | undefined;
917
+ /** Internal, tests only: rewrites the engine seams (see {@link createMarmotClientWith}). */
918
+ readonly engineSeamsOverride: EngineSeamsOverride | undefined;
919
+ /** Internal, tests only: see {@link InternalClientOptions.engineOptions}. */
920
+ readonly engineOptionsForTest: InternalClientOptions['engineOptions'];
921
+ /** Internal: see {@link InternalClientOptions.finishPurgeBeforeJoin}. */
922
+ readonly finishPurgeBeforeJoin: boolean;
923
+ /** How long one history backend call may take before it counts as a failed attempt (ms). */
924
+ readonly historyBackendTimeoutMs: number;
925
+ /** S20: how long a removal of the local leaf stays revisable (client-clock ms; see client/group-removal.ts). */
926
+ readonly removalSettleMs: number;
927
+ /** S5 (AC-RACE-2): the elected-SelfRemove-committer bounded wait (client-clock ms; see client/pipeline.ts). */
928
+ readonly selfRemoveElectionWaitMs: number;
929
+ /** S7 (AC-HYG-2): how long a settled invite record is kept (client-clock ms; see invitations/invite.ts). */
930
+ readonly inviteRetentionMs: number;
931
+ /** inbox-handler-time-budget: when a running inbox consumer callback is reported `handlerSlow` (client-clock ms; 0 = never). */
932
+ readonly inboxHandlerBudgetMs: number;
933
+ /** S8 (AC-RATCH-1): own application ratchet skip at the first own message after a load (see client/pipeline.ts). */
934
+ readonly ratchetSkipMargin: number;
935
+ /** Internal (tests only): see {@link InternalClientOptions.disableSelfUpdateReenqueueForTest}. */
936
+ readonly disableSelfUpdateReenqueueForTest: boolean;
937
+ /** Internal (tests only): see {@link InternalClientOptions.disableRestoreRotationForTest}. */
938
+ readonly disableRestoreRotationForTest: boolean;
939
+ /** Internal (tests only): see {@link InternalClientOptions.disableRatchetSkipForTest}. */
940
+ readonly disableRatchetSkipForTest: boolean;
941
+ /** Internal (tests only): see {@link InternalClientOptions.redriveFaultsForTest}. */
942
+ readonly redriveFaultsForTest: RedriveFaultsForTest | undefined;
943
+ /** Internal (tests only): see {@link InternalClientOptions.exposeRuntimesForTest}. */
944
+ readonly exposeRuntimesForTest: InternalClientOptions['exposeRuntimesForTest'];
945
+ emit<E extends MarmotClientEventName>(event: E, payload: MarmotClientEvents[E]): void;
946
+ /** AC-INBOX-6: the only emit path of every `LifecycleEventPayloads` member — after the commit. */
947
+ readonly lifecycle: LifecycleEvents;
948
+ /** AC-INBOX-7: the `beforeCreateGroup` gates `groups.create()` passes first. */
949
+ readonly beforeCreateGroup: BeforeCreateGroupGates;
950
+ /**
951
+ * Epic marmot-device-key-rotation (S6, AC-NOTIF-6): where a group operation reads the device lineage from — the
952
+ * account's recorded links, as the synchronous {@link DeviceLineage} snapshot `devices.lineage()` hands out (`isRetired`, `keysOf`). Late-bound
953
+ * (the device service is built after the group registry that holds `ctx`): `read` is `undefined` until then, and
954
+ * a failing or absent read only means no `retired-key-readded` is emitted.
955
+ */
956
+ readonly deviceLineage: DeviceLineageSource;
957
+ isDisposed(): boolean;
958
+ }
959
+ /** See {@link ClientContext.deviceLineage}. */
960
+ export interface DeviceLineageSource {
961
+ read: (() => Promise<DeviceLineage>) | undefined;
962
+ }
963
+ /** Internal accessor for tests; not re-exported. */
964
+ export declare function getGroupRegistry(client: MarmotClient): GroupRegistry;
965
+ /** Internal accessor for other client-module files and tests; not re-exported. */
966
+ export declare function getClientContext(client: MarmotClient): ClientContext;
967
+ export declare const BUDGET_NUMERIC_FIELDS: readonly ["concurrency", "minSpacingMs", "timeoutMs", "leaseMs"];
968
+ export declare function createMarmotClient(options: MarmotClientOptions): MarmotClient;
969
+ /** What {@link createMarmotClientWith} takes beyond the public options — never reachable from the package root. */
970
+ export interface InternalClientOptions {
971
+ /**
972
+ * Rewrites the seams every engine of this client is built with — how a
973
+ * test builds a client on the engine defaults to prove that a seam is
974
+ * load-bearing (AC-ADMIN-8, AC-ADMIN-9).
975
+ */
976
+ readonly engineSeams?: EngineSeamsOverride;
977
+ /**
978
+ * Extra options every engine of this client is built with, spread over marmot's own (never over `removal` or
979
+ * `opaque`, the persisted records) — how a test chooses an engine option marmot does not expose (the OQ-1 hidden-credit
980
+ * policy, or the opaque seam switched off). The opt-in itself is the one literal in `group-runtime.ts`, never an option.
981
+ */
982
+ readonly engineOptions?: Partial<MarmotGroupEngineOptions<NostrEvent>>;
983
+ /**
984
+ * `false` skips finishing an interrupted purge before a Welcome's group is adopted — ONLY for the negative
985
+ * control that shows why it is there (a resumed purge would delete the re-joined group). Default `true`.
986
+ */
987
+ readonly finishPurgeBeforeJoin?: boolean;
988
+ /** Internal (tests only): the history backend call timeout; default {@link HISTORY_BACKEND_TIMEOUT_MS}. */
989
+ readonly historyBackendTimeoutMs?: number;
990
+ /**
991
+ * Internal (tests only), AC-RACE-3's negative control: `true` disables every drive of a re-enqueued
992
+ * self-update (`driveReenqueuedSelfUpdate`, reached from the scheduled drive and from `resumePending`) — the withdrawn self-update's re-enqueued record is still written atomically
993
+ * (group-history.ts `recordTransition`; that durability cannot be disabled from outside), but nothing
994
+ * ever drives it, reproducing the pre-AC-RACE-1 symptom (the rotation never lands on the winning branch,
995
+ * and no `intentFailed` is ever reported either — it is simply stuck, the "silently lost" bug this story
996
+ * fixes). Default `false`.
997
+ */
998
+ readonly disableSelfUpdateReenqueueForTest?: boolean;
999
+ /**
1000
+ * Tests only: a successful `groups.restore` owes no device-key rotation (owner decision 13), for suites that count the
1001
+ * signer calls and relay events of a restore and are not about the rotation.
1002
+ */
1003
+ readonly disableRestoreRotationForTest?: boolean;
1004
+ /**
1005
+ * Internal (tests only), AC-RATCH-1/3's negative control: `true` never asks the engine for the post-load ratchet
1006
+ * skip, so the first own application message after a load uses the restored state's next generation (the
1007
+ * behaviour before AC-RATCH-1). Default `false`.
1008
+ */
1009
+ readonly disableRatchetSkipForTest?: boolean;
1010
+ /**
1011
+ * Internal (tests only), the negative controls of epic marmot-rewound-own-commit-no-signal's integration properties
1012
+ * (AC-PROP-2 (b), AC-PROP-4): each flag reintroduces ONE defect the corresponding property exists to catch. Absent: no effect.
1013
+ */
1014
+ readonly redriveFaultsForTest?: RedriveFaultsForTest;
1015
+ /**
1016
+ * Internal (tests only), a mutation-gate test seam: called once at client construction with a read-only lookup
1017
+ * of the live per-group runtimes, so a test can drive pipeline internals on a real runtime. Absent: no effect.
1018
+ */
1019
+ readonly exposeRuntimesForTest?: (get: (groupId: string) => GroupRuntime | undefined) => void;
1020
+ }
1021
+ /** Internal (tests only): `createMarmotClient` with {@link InternalClientOptions}. */
1022
+ export declare function createMarmotClientWith(options: MarmotClientOptions, internal: InternalClientOptions): MarmotClient;