@minca/core 0.1.17 → 0.2.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 (120) hide show
  1. package/README.md +2 -1
  2. package/dist/files/space-files.d.ts +2 -2
  3. package/dist/files/space-files.d.ts.map +1 -1
  4. package/dist/files/space-files.js +7 -5
  5. package/dist/files/space-files.js.map +1 -1
  6. package/dist/inbox/names.d.ts +1 -1
  7. package/dist/inbox/names.js +1 -1
  8. package/dist/index.d.ts +3 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/node/actions.d.ts +3 -0
  13. package/dist/node/actions.d.ts.map +1 -1
  14. package/dist/node/actions.js.map +1 -1
  15. package/dist/node/api.d.ts +1 -0
  16. package/dist/node/api.d.ts.map +1 -1
  17. package/dist/node/api.js +1 -0
  18. package/dist/node/api.js.map +1 -1
  19. package/dist/node/carrier.js +1 -1
  20. package/dist/node/carrier.js.map +1 -1
  21. package/dist/node/index.d.ts +1 -1
  22. package/dist/node/index.d.ts.map +1 -1
  23. package/dist/node/node-contacts.d.ts.map +1 -1
  24. package/dist/node/node-contacts.js +1 -0
  25. package/dist/node/node-contacts.js.map +1 -1
  26. package/dist/node/node-records.d.ts.map +1 -1
  27. package/dist/node/node-records.js +6 -1
  28. package/dist/node/node-records.js.map +1 -1
  29. package/dist/node/node.d.ts.map +1 -1
  30. package/dist/node/node.js +13 -1
  31. package/dist/node/node.js.map +1 -1
  32. package/dist/node/remote.d.ts.map +1 -1
  33. package/dist/node/remote.js +7 -1
  34. package/dist/node/remote.js.map +1 -1
  35. package/dist/node/space-runtime.d.ts +5 -3
  36. package/dist/node/space-runtime.d.ts.map +1 -1
  37. package/dist/node/space-runtime.js +3 -1
  38. package/dist/node/space-runtime.js.map +1 -1
  39. package/dist/node/types.d.ts +112 -36
  40. package/dist/node/types.d.ts.map +1 -1
  41. package/dist/node/watch-notifications.d.ts +6 -0
  42. package/dist/node/watch-notifications.d.ts.map +1 -1
  43. package/dist/node/watch-notifications.js +47 -9
  44. package/dist/node/watch-notifications.js.map +1 -1
  45. package/dist/query/types.d.ts +1 -0
  46. package/dist/query/types.d.ts.map +1 -1
  47. package/dist/query/types.js.map +1 -1
  48. package/dist/records/contract-builder.d.ts +22 -6
  49. package/dist/records/contract-builder.d.ts.map +1 -1
  50. package/dist/records/contract-builder.js.map +1 -1
  51. package/dist/schemas/automations.d.ts +6 -2
  52. package/dist/schemas/automations.d.ts.map +1 -1
  53. package/dist/schemas/automations.js.map +1 -1
  54. package/dist/schemas/connectors.d.ts +4 -3
  55. package/dist/schemas/connectors.d.ts.map +1 -1
  56. package/dist/schemas/connectors.js +4 -3
  57. package/dist/schemas/connectors.js.map +1 -1
  58. package/dist/schemas/library/media.js +1 -1
  59. package/dist/schemas/library/media.js.map +1 -1
  60. package/dist/session/account-hint.d.ts +2 -2
  61. package/dist/session/account-hint.d.ts.map +1 -1
  62. package/dist/session/account-hint.js +3 -3
  63. package/dist/session/account-hint.js.map +1 -1
  64. package/dist/session/auth.d.ts +7 -3
  65. package/dist/session/auth.d.ts.map +1 -1
  66. package/dist/session/auth.js.map +1 -1
  67. package/dist/session/connection.d.ts +18 -0
  68. package/dist/session/connection.d.ts.map +1 -1
  69. package/dist/session/connection.js +11 -0
  70. package/dist/session/connection.js.map +1 -1
  71. package/dist/session/index.d.ts +2 -2
  72. package/dist/session/index.d.ts.map +1 -1
  73. package/dist/session/index.js +2 -2
  74. package/dist/session/index.js.map +1 -1
  75. package/dist/storage/blob-store.d.ts +3 -0
  76. package/dist/storage/blob-store.d.ts.map +1 -1
  77. package/dist/types.d.ts +11 -2
  78. package/dist/types.d.ts.map +1 -1
  79. package/dist/types.js.map +1 -1
  80. package/docs/README.md +86 -93
  81. package/docs/actions.md +213 -152
  82. package/docs/agents.md +198 -167
  83. package/docs/automations.md +296 -204
  84. package/docs/blueprints-and-guides.md +405 -311
  85. package/docs/bots.md +208 -134
  86. package/docs/building-an-app.md +86 -159
  87. package/docs/collections.md +248 -328
  88. package/docs/computed.md +112 -89
  89. package/docs/contacts.md +151 -112
  90. package/docs/contracts.md +299 -120
  91. package/docs/direct-messages.md +80 -65
  92. package/docs/inbox.md +138 -93
  93. package/docs/node.md +1081 -996
  94. package/docs/permissions.md +142 -0
  95. package/docs/proposing-collections.md +74 -55
  96. package/docs/query-format.md +150 -126
  97. package/docs/records-and-queries.md +205 -126
  98. package/docs/sign-in.md +487 -416
  99. package/docs/spaces.md +261 -246
  100. package/docs/standard-library.md +487 -526
  101. package/docs/storage.md +325 -348
  102. package/docs/usernames.md +164 -97
  103. package/docs/warrants.md +100 -67
  104. package/package.json +1 -6
  105. package/dist/elements/auth-styles.d.ts +0 -18
  106. package/dist/elements/auth-styles.d.ts.map +0 -1
  107. package/dist/elements/auth-styles.js +0 -206
  108. package/dist/elements/auth-styles.js.map +0 -1
  109. package/dist/elements/dom.d.ts +0 -29
  110. package/dist/elements/dom.d.ts.map +0 -1
  111. package/dist/elements/dom.js +0 -91
  112. package/dist/elements/dom.js.map +0 -1
  113. package/dist/elements/index.d.ts +0 -13
  114. package/dist/elements/index.d.ts.map +0 -1
  115. package/dist/elements/index.js +0 -11
  116. package/dist/elements/index.js.map +0 -1
  117. package/dist/elements/minca-auth.d.ts +0 -55
  118. package/dist/elements/minca-auth.d.ts.map +0 -1
  119. package/dist/elements/minca-auth.js +0 -768
  120. package/dist/elements/minca-auth.js.map +0 -1
package/docs/node.md CHANGED
@@ -1,1090 +1,1175 @@
1
1
  # The node
2
2
 
3
- `createNode` and what it returns: configuration, root signers and notes, renewing
4
- the session note, stores, holding spaces, following the account, events, live
5
- messages, the rest of its surface, the network, acting as an agent, the
6
- app-side client, carriers and hosting, the inbox, and the React and element
7
- conveniences.
8
-
9
- > Not protocol. This page describes the reference library, and another
10
- > implementation may do it differently and still interoperate. What peers must
11
- > agree on is in the [spec](https://github.com/leifriksheim/minca/blob/main/spec/README.md).
3
+ A node is what takes part in Minca for an account. It holds the account's
4
+ spaces, signs what it writes, checks what peers send, and keeps everything in
5
+ sync. Most apps never make one: the connection starts it for you
6
+ ([building an app](building-an-app.md)). You make one yourself in a program
7
+ that holds the account's keys, such as a script, a server or a test.
8
+
9
+ ```ts
10
+ import { createNode, deriveAccountKey, generateSeed, indexedDBStores, rootFromSeed } from '@minca/core';
11
+
12
+ const seed = generateSeed();
13
+ const { signer } = await rootFromSeed(seed);
14
+
15
+ const node = await createNode({
16
+ signer,
17
+ accountKey: await deriveAccountKey(seed),
18
+ stores: indexedDBStores('my-app'),
19
+ network: { relays: ['wss://relay.minca.social'] },
20
+ });
21
+
22
+ const space = await node.spaces.create({ name: 'Notes', visibility: 'private' });
23
+ await node.records.put(space.id, 'app.note', { text: 'Hello' });
24
+ ```
12
25
 
13
26
  ## Configuration
14
27
 
15
- `createNode(config)` takes (`NodeConfig`):
16
-
17
- | Field | Type | Meaning |
18
- | ------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
19
- | `signer` | `RootSigner` | Who the node acts for. Asked only for session notes ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
20
- | `accountKey` | bytes, optional | The account key (`deriveAccountKey(seed)`). Enables the account registry and the contacts space ([spec 06 §1.3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
21
- | `contactKey` | bytes, optional | The contact key's secret. Opens knocks, in shared spaces and, through the keys derived from it, in the inbox; published on profiles. |
22
- | `contactsSpace` | string, optional | The contacts space's id, for a node given it without the account key (an app granted `contacts`, [spec 06 §2.5](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
23
- | `stores` | `StoreFactory` | Where the registry and each space's store live ([stores](#stores)). |
24
- | `provider` | `CryptoProvider`, optional | Default: P-256 over WebCrypto. |
25
- | `collections` | `CollectionDef[]`, optional | Schemas the node knows, used when a space does not describe a collection itself. Writes are checked against them; reads are flagged `conforms`. Nothing is refused on arrival for its shape ([02](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)). |
26
- | `network` | optional | `relays` (where peers meet: Minca `wss://` and Nostr `nostr+wss://` relays), `nodes` (always-on nodes to dial, `wss://host/peer#<DID>`; the fragment pins the node, spec 04 §5.2; `ws://` only on this machine), `iceServers`, `transports` (extra transports per space). Omitted: offline. |
27
- | `sessionTtlSeconds` | number, optional | Lifetime of each session note. Default `3600`. |
28
- | `sessionKey` | `CryptoKeyPair`, optional | Sign with this key instead of a fresh one. Used when the signer's note names a specific key (an app's key, an agent's key, [spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md), [spec 06 §3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
29
- | `writerKey` | `WriterKeySource`, optional | Keep a signing key across runs, so this device keeps one log in each space ([writer keys](#writer-keys)). Ignored with `sessionKey`. |
30
- | `watchIntervalMs` | number, optional | How often to look for writes another app, device or process made: a data folder's segments, a store file another process shares. `0` disables. Default `2000`. _Implementation detail._ |
31
- | `cache` | `CacheConfig`, optional | Hold only the collections used, in spaces that name a keeper ([holding part of a space](#holding-part-of-a-space)). |
32
- | `mailbox` | `MailboxClient`, optional | How the inbox and short links reach mailboxes ([07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md)). Default: a WebSocket to each relay. |
33
-
34
- _Source: `packages/core/src/node/types.ts` (`NodeConfig`, `NodeNetworkConfig`, `CacheConfig`). Tests: `packages/core/tests/node.test.ts`, `packages/core/tests/caches.test.ts`._
28
+ `createNode(config)` takes a [`NodeConfig`](https://minca.dev/api/core/interfaces/NodeConfig/),
29
+ whose page gives each field's meaning and default. The sections below explain
30
+ the ones that work together: [root signers](#root-signers-and-notes),
31
+ [stores](#stores), [writer keys](#writer-keys) and
32
+ [holding part of a space](#holding-part-of-a-space).
33
+
34
+ ### Collections the node knows
35
+
36
+ `collections` gives the node schemas to use when a space doesn't describe a
37
+ collection itself. Writes are checked against them, and reads are flagged
38
+ `conforms`. Nothing arriving from a peer is refused for its shape.
39
+
40
+ ### Network options
41
+
42
+ `network` is a [`NodeNetworkConfig`](https://minca.dev/api/core/interfaces/NodeNetworkConfig/):
43
+ the relays where peers meet, always-on nodes to dial, hosts to look for the
44
+ account registry at, and more. Omitted, the node stays offline.
45
+ [The network](#the-network) says how the node uses them.
35
46
 
36
47
  ## Lifecycle
37
48
 
38
- Starting a node does the following, in order:
39
-
40
- 1. Uses `config.sessionKey`; else claims a lasting key from `config.writerKey`
41
- ([writer keys](#writer-keys)); else generates a fresh P-256 key pair for this
42
- run. Its DID (`did:key`, P-256 multicodec) is `sessionDid`.
43
- 2. Asks `config.signer.delegate` for a session note ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)) and waits for it.
44
- If the signer refuses, `createNode` fails.
45
- 3. Schedules renewal of the note ([renewing the session note](#renewing-the-session-note)).
46
- 4. Opens the `registry` store, sealed ([stores](#stores)).
47
- 5. With an account key: derives the account registry space and the contacts
48
- space ([03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)). The contacts space is added to the node's own
49
- registry like a joined space (so it can be granted to an app like any other
50
- space), and both are _hidden_ from `spaces.list` ([following the account](#following-the-account)).
51
- 6. With an account key: opens the account registry space and reconciles
52
- ([following the account](#following-the-account)) before `createNode` returns.
53
-
54
- A node acts for one account (`node.did`) and signs with one session key
55
- (`node.sessionDid`) for its whole lifetime. To act for another account, start
56
- another node.
57
-
58
- `revokeKey(key, { spaces?, waitMs? })` revokes a key of the account, each
59
- revoke with a cutoff at what the key wrote: in `spaces`, or by default
60
- wherever the account writes (every space it lists, its carry spaces, the
61
- contacts space and the account registry). It says whether a peer took each in
62
- within `waitMs`. The account home's disconnect calls it for an app's key.
63
- `revokeSelf()` does the same for the node's own session key, and forgets a
64
- lasting key at once; the account home's sign-out calls it
65
- ([spec 01 §7.4](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md)).
66
- A record is judged with no time, so a revoke, not the note running out, is
67
- what ends what a key can write. An agent's view refuses both.
68
-
69
- `close()` stops renewal, closes every open space (flushing what each keeps,
70
- stopping sync and disconnecting its transports), closes the registry store,
71
- and drops all event listeners. After `close()`, any call that needs a space
72
- fails with `Node is closed`. Closing twice does nothing.
73
-
74
- _Source: `packages/core/src/node/node.ts` (`createNode`, `close`). Tests: `packages/core/tests/node.test.ts`._
49
+ When it starts, a node picks its signing key: `sessionKey` if given, else one
50
+ claimed from `writerKey`, else a fresh P-256 key for this run. Its DID is
51
+ `node.sessionDid`. Then it asks the signer for a session note and waits. If
52
+ the signer refuses, `createNode` fails.
53
+
54
+ With an account key, the node also opens the account registry and makes its
55
+ spaces match it before `createNode` returns
56
+ ([following the account](#following-the-account)).
57
+
58
+ A node acts for one account (`node.did`) and signs with one key for its whole
59
+ life. To act for another account, start another node.
60
+
61
+ ### Revoking keys
62
+
63
+ `revokeKey(key, { spaces?, waitMs? })` revokes one of the account's keys, with
64
+ a cutoff at what that key wrote. By default it does this wherever the account
65
+ writes: every space it lists, its carry spaces, the contacts space and the
66
+ account registry. It says whether a peer took each revoke in within `waitMs`.
67
+ The account home calls it when you disconnect an app.
68
+
69
+ `revokeSelf()` does the same for the node's own key, and forgets a lasting
70
+ key at once. The account home calls it on sign-out.
71
+
72
+ A record is judged with no clock, so it is a revoke, not the note running out,
73
+ that ends what a key can write. An agent can't call either.
74
+ [Spec 01 §7.4](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md).
75
+
76
+ ### Closing
77
+
78
+ `close()` stops renewing the note, closes every open space and the registry,
79
+ and drops all event listeners. After that, any call that needs a space fails
80
+ with `Node is closed`. Closing twice does nothing.
75
81
 
76
82
  ## Root signers and notes
77
83
 
78
- A node never holds the root key. It is given a **root signer** (`RootSigner`),
79
- which hides where the key lives and is asked only for notes. This is an
80
- in-process interface, not a wire format; what a note must be is
81
- [spec 01 §7](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md).
82
-
83
- | Member | Type | Meaning |
84
- | -------------------------------------------------------------- | -------------- | ------------------------------------------- |
85
- | `did` | string | The account DID |
86
- | `delegate({audience, command, subject?, policy?, expiration})` | → `Delegation` | Issue a note from the account to `audience` |
87
-
88
- - The **local** signer (`createLocalRootSigner`) calls `issueDelegation` with
89
- the root key. `subject` defaults to the account's own DID (the whole
90
- account), `policy` to none. It never sets `meta`.
91
- - The **grant** signer an app uses returns the one note the account home
92
- already issued to the app's key, unchanged, and refuses once the grant's
93
- `expiresAt` has passed. It cannot mint new notes
94
- ([spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
95
- - A signer **across a port** (`serveSigner` on the side that holds the key,
96
- `remoteSigner` on the node's, as a page signs for its worker's node) signs
97
- only notes of the session note's shape below: `command` `/`, no `subject`,
98
- no `policy`. It refuses anything else without asking the signer behind it.
99
- The audience and expiration are the far end's to pick, so it bounds
100
- neither.
101
-
102
- The **session note** a node asks for when it starts:
84
+ A node never holds the account's root key. It gets a **root signer**, which
85
+ hides where the key lives and is only asked for notes.
86
+
87
+ Its interface is [`RootSigner`](https://minca.dev/api/core/interfaces/RootSigner/): the
88
+ account's DID, and `delegate`, which issues a note from the account to a key.
89
+
90
+ There are three kinds:
91
+
92
+ - **Local**, `createLocalRootSigner`, signs with the root key itself.
93
+ `subject` defaults to the whole account and `policy` to none.
94
+ - **Grant**, `grantSigner`, is what an app uses. It returns the one note the
95
+ account home gave the app, and refuses once the grant has expired. It can't
96
+ make new notes.
97
+ - **Across a port**, `serveSigner` on the side with the key and
98
+ `remoteSigner` on the node's side, as a page signs for its worker. It signs
99
+ only session notes (command `/`, no subject, no policy) and refuses anything
100
+ else without asking the signer behind it.
101
+
102
+ ### The session note
103
+
104
+ This is the note a node asks for when it starts:
103
105
 
104
106
  ```
105
107
  aud = session DID
106
108
  sub = the account's DID
107
- cmd = "/" (SESSION_COMMAND; a node acting as an agent signs under its grant, `/record`)
109
+ cmd = "/" (an agent's node signs under its grant, `/record`)
108
110
  pol = []
109
111
  exp = now + sessionTtlSeconds (default 3600)
110
- nbf = now − 300 (issueDelegation's default)
112
+ nbf = now − 300
111
113
  ```
112
114
 
113
- Its proof is that token. Peers check only that the note grants what each
114
- record needs, so the command is this node's choice, not a rule. The note is renewed before it runs out
115
- ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
116
-
117
- **Issuing.** `issueDelegation` defaults `exp` to now + 3600, `nbf` to now − 300
118
- (`UCAN_CLOCK_SKEW_SECONDS`, so a peer whose clock is a little behind still
119
- accepts it), `nonce` to 12 random bytes in base64url, `subject` to the
120
- issuer's own DID and `policy` to `[]`; it signs in the low-S form only.
121
- Only the account's root signer issues notes peers accept: a note is one
122
- token from the account, never passed on
123
- ([spec 01 §7.5](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md)).
124
- A key that needs another key (a helper, a key per tab) asks the account,
125
- through its home or root signer, for a note of its own.
126
-
127
- **What a home grants.** `grantTerms(access, spaces)` (and `noteTerms` under it)
128
- turns a grant into a note's terms: `/`, `/record` or `/record/read`; the
129
- whole account, or one space as the subject, or several named by a policy on
130
- `.space`; none, as a policy nothing satisfies. `noteSpaces(note)` reads that
131
- back, for showing which spaces a note reaches, and reaches no space for a
132
- policy statement it can't read that way, so it never offers more than the
133
- note grants; peers judge each use against the note itself
134
- ([spec 06 §2.5](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
135
-
136
- _Source: `packages/core/src/identity/root-signer.ts`, `packages/core/src/node/remote.ts` (`serveSigner`, `remoteSigner`), `packages/core/src/identity/ucan.ts` (`issueDelegation`, `verifyNote`), `packages/core/src/identity/abilities.ts` (`noteTerms`, `noteSpaces`), `packages/core/src/node/node.ts` (`SESSION_COMMAND`, `delegate`), `packages/core/src/session/connect.ts` (`grantSigner`, `grantTerms`). Tests: `packages/core/tests/ucan.test.ts`, `packages/core/tests/remote.test.ts` ("the page's signer, from a worker"), `packages/core/tests/node.test.ts`, `packages/core/tests/connect.test.ts`._
115
+ Peers only check that the note grants what each record needs, so the command
116
+ is the node's choice.
137
117
 
138
- ## Renewing the session note
118
+ ### Issuing notes
139
119
 
140
- The note format, and that every record carries it, are protocol
141
- ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). When to renew it is the node's own:
120
+ `issueDelegation` defaults `exp` to an hour from now, `nbf` to five minutes
121
+ ago so a peer with a slow clock still accepts it, `nonce` to 12 random bytes,
122
+ `subject` to the issuer and `policy` to `[]`. It signs in low-S form only.
142
123
 
143
- - The first renewal is asked for at `0.75 × ttl` seconds after start (2700 s
144
- with the default TTL), and each successful renewal schedules the next
145
- `0.75 × ttl` later.
146
- - If the signer refuses or cannot be reached, the node keeps the note it has
147
- and asks again after `min(60, ttl / 4)` seconds, repeating until it succeeds
148
- or the node closes. Once the held note expires, live checks (knocks, live
149
- messages, connecting to peers) refuse it; records it signs are judged with
150
- no time, so they count until its key is revoked.
124
+ Only the account's root signer issues notes that peers accept, and a note is
125
+ never passed on. A key that needs another key, such as a helper or a key per
126
+ tab, asks the account for a note of its own.
151
127
 
152
- A signer need not be able to sign. `grantSigner(grant)` answers every
153
- `delegate` call with the one note an account home granted, unchanged, and
154
- refuses once `grant.expiresAt` has passed. `grantSigner(() => grant)` answers
155
- with whichever grant the getter returns, as the desktop app's node does when
156
- a renewed grant replaces the last. A node started from a grant
157
- therefore never gets a fresh note: its "renewal" returns the same note, and when
158
- it runs out the app must connect again ([spec 06 §2.9](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
128
+ ### What a home grants
159
129
 
160
- `node.delegation()` returns the note the session key writes under now.
130
+ `grantTerms(access, spaces)` turns a grant into a note's terms: the command
131
+ `/`, `/record` or `/record/read`, and the whole account, one space, or several
132
+ spaces named by a policy. `noteSpaces(note)` reads that back, to show which
133
+ spaces a note reaches. It never claims more than the note grants.
134
+ [Spec 01 §7](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md),
135
+ [spec 06 §2.5](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
161
136
 
162
- _Source: `packages/core/src/node/node.ts` (`delegate`, `scheduleRenewal`, `SESSION_COMMAND`), `packages/core/src/session/connect.ts` (`grantSigner`). Tests: `packages/core/tests/node.test.ts` ("the delegation is renewed before it expires")._
137
+ ## Renewing the session note
163
138
 
164
- ## Stores
139
+ The node asks for a new note three quarters of the way through the old one:
140
+ 2700 seconds in, with the default lifetime. Each renewal schedules the next.
165
141
 
166
- A node asks for stores by path through its `StoreFactory`:
167
-
168
- | Path | Holds | Sealed |
169
- | ------------------ | ---------------------------------------------------- | --------------------------------------- |
170
- | `registry` | the node's list of spaces and their keys | yes: the node asks for `{ seal: true }` |
171
- | `spaces/<spaceId>` | one space's records and what the node keeps about it | no |
172
- | `writers` | the last place each lasting key took in each line | no |
173
-
174
- What a path means is the factory's choice:
175
-
176
- - `indexedDBStores(prefix)` — one IndexedDB database per path, named
177
- `<prefix>:<path with / replaced by :>`. Never sealed: the browser profile
178
- already guards it.
179
- - `folderStores(directory, { basePath?, localKey?, local? })` — a data folder
180
- ([sync and storage](storage.md#data-folders)): the `registry` in the folder
181
- under `basePath`, sealed under `localKey` (`deriveLocalKey(seed)`) when one
182
- is given; every other path in `local`; and each space mirrored to the
183
- folder's segments, which the factory names as `folder`.
184
- - `directoryStores(directory, { localKey? })` — a directory on this device,
185
- one file per entry and per version; the `registry` sealed as above.
186
-
187
- Every version a node signs in a space takes the next place in its key's line
188
- for that collection there ([spec 02 §4.10](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
189
- Writes by one key in one space go one at a time, and the place is remembered
190
- before the version leaves the node. Where the places are kept depends on the key:
191
-
192
- - **A key made for this run** lives only as long as the node, so its places
193
- are kept in memory.
194
- - **A claimed writer key** (`config.writerKey`) keeps them in its slot, beside
195
- the key.
196
- - **A key handed in** (`config.sessionKey`, an agent's) or a carrier's own key
197
- keeps them in the `writers` store, and a restart carries on where it left off.
198
- Such a key may be signing in several nodes at once: every tab of an app
199
- signs with the app's key. So each place is taken under a Web Lock
200
- (`minca-writer:lines/<did>/<space>`) every tab and worker of the origin
201
- shares, and read afresh from the store inside it, never from a copy in
202
- memory. Nodes that share a key must share that store too, as tabs of one
203
- origin share IndexedDB; two nodes signing with one key from separate stores,
204
- or in separate processes without a shared lock, fork its lines, and every
205
- peer then withdraws what it signed in a forked collection from the fork on.
206
-
207
- _Source: `packages/core/src/node/writers.ts` (`createWriters`, `exclusively`). Tests: `packages/core/tests/writer-logs.test.ts` ("a writer’s log", "two nodes sharing a handed-in key…")._
142
+ If the signer refuses or can't be reached, the node keeps its note and asks
143
+ again after `min(60, ttl / 4)` seconds, until it succeeds or the node closes.
144
+ Once the note expires, live checks refuse it: knocks, live messages and
145
+ connecting to peers. Records it signed still count until its key is revoked.
208
146
 
209
- ### Writer keys
147
+ A node started from a grant never gets a fresh note. `grantSigner(grant)`
148
+ answers every renewal with the same note, and when that runs out the app must
149
+ connect again. `grantSigner(() => grant)` answers with whatever grant the
150
+ getter returns, so a renewed grant can replace the last.
151
+
152
+ `node.delegation()` returns the note the node writes under now.
153
+ [Spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
210
154
 
211
- A node given `writerKey` claims a lasting key at start and signs with it
212
- until it closes, so the device keeps one log in each space instead of a new
213
- one each run. The source hands a key to one node at a time; a node that
214
- finds every key taken, or a source that can't lock one, gets none, and the
215
- node makes a key for this run as it would without a source.
216
-
217
- - `browserWriterKeys(name)` keeps keys in this origin's IndexedDB, one
218
- database per slot (`<name>:writer:<slot>`, up to 32), each claimed under a Web
219
- Lock of the same name. A tab or worker that finds a slot taken tries the
220
- next; one that closes, or crashes, frees its slot. The private key is
221
- non-extractable: a script in the page can sign with it while it runs, but
222
- can't take it away. Without IndexedDB or Web Locks it gives none.
223
- - A node started from a store description (`startPageNode`, a node in a
224
- worker) claims from `browserWriterKeys` under the account's IndexedDB prefix,
225
- whether its stores are in IndexedDB or a data folder, so signing out
226
- (`deleteBrowserData`) deletes the keys too. The key never goes in the data
227
- folder, which other apps and devices share.
228
- - `forget()` drops the key but keeps its places, which still count while it
229
- signs this run; the slot's next claim makes a new key and clears them.
230
- `revokeSelf` forgets the claimed key before it writes a single revoke, so a
231
- page closed while the revokes wait leaves no revoked key to claim again.
232
- With a peer connected in any open space, each revoke waits up to
233
- `waitMs` for one to take it in; with none, none wait. A node that claims a
234
- key the account registry has revoked anyway (one forgotten by an older
235
- version, say) forgets it and starts again on a key for this run alone; the
236
- next start claims a new lasting one.
237
- - A node never signs at a place behind one it took itself this run: if the
238
- slot has lost them (site data cleared while the page was open), every
239
- write fails until the page reloads, since signing on would fork the line
240
- and withdraw what the key wrote. A slot whose connection the browser
241
- closed opens again only while it still holds the key.
242
- - The CLI keeps them outside its home, in `<local>/writer-keys/slot-<n>/` (`localPath` in `packages/cli/src/home.ts`, [sync and storage](storage.md#data-folders)): the key as
243
- JWK in an envelope (spec 01 §9.1) under the account's local key, with label
244
- `minca/writer-key/v1` and bound `{ did: <account DID>, slot: <n> }`
245
- (`key.sealed`, mode 600), so a copy of the files can't sign, and a key file
246
- moved to another slot or account is refused rather than used; its places in
247
- `heads/`; and numbered `lock.<n>` files naming the process that holds the
248
- highest, taken over once that process is gone.
249
-
250
- _Source: `packages/core/src/node/writer-keys.ts` (`browserWriterKeys`), `packages/core/src/node/writers.ts` (`createWriters`), `packages/core/src/node/node.ts` (`createNode`, `revokeSelf`), `packages/core/src/node/stores.ts` (`writerKeysFor`), `packages/core/src/node/worker.ts` (`withWriterKey`), `packages/cli/src/writer-keys.ts` (`fileWriterKeys`), `packages/cli/src/home.ts` (`unlock`, `nodeFor`). Tests: `packages/core/tests/writer-logs.test.ts` ("a writer key that outlives the node"), `packages/cli/tests/writer-keys.test.ts` ("a key file moved to another slot, or to another account, does not open")._
251
-
252
- Sign-in ([sign-in](sign-in.md)) uses `storesFor(account)`: IndexedDB with prefix
253
- `minca:<dataPath with : for />` in the browser, or `folderStores(pod,
155
+ ## Stores
156
+
157
+ A node asks its `StoreFactory` for stores by path:
158
+
159
+ | Path | Holds | Sealed |
160
+ | ------------------ | ----------------------------------------------------- | ------ |
161
+ | `registry` | the node's list of spaces and their keys | yes |
162
+ | `spaces/<spaceId>` | one space's records, and what the node keeps about it | no |
163
+ | `writers` | each lasting key's place in each line | no |
164
+
165
+ It also opens `mirrors/<spaceId>/<n>` for a [mirror](storage.md#mirrors),
166
+ `folder/<spaceId>` for a data folder, and `host` for a host's subscriptions.
167
+
168
+ What a path means is up to the factory:
169
+
170
+ - `indexedDBStores(prefix)` makes one IndexedDB database per path, named
171
+ `<prefix>:<path with / replaced by :>`. It never seals, since the browser
172
+ profile already guards it.
173
+ - `folderStores(directory, { basePath?, localKey?, local? })` uses a
174
+ [data folder](storage.md#data-folders). The `registry` goes in the folder
175
+ under `basePath`, sealed under `localKey` (`deriveLocalKey(seed)`) when
176
+ given. Every other path goes in `local`, and each space is mirrored to the
177
+ folder's segments.
178
+ - `directoryStores(directory, { localKey? })` uses a directory on this
179
+ device, one file per entry and per version, sealing the `registry` the same
180
+ way.
181
+
182
+ [Sign-in](sign-in.md) picks stores with `storesFor(account)`: IndexedDB with
183
+ prefix `minca:<dataPath with : for />` in the browser, or `folderStores(pod,
254
184
  { basePath: account.dataPath, localKey })` in a pod, where `dataPath` is
255
- `accounts/<id>/stores`. A connected app uses `indexedDBStores('minca-app:<account DID>')`
256
- by default. These names are _implementation details_ ([sync and storage](storage.md#indexeddb));
257
- a pod's layout is in
258
- [05](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
259
- A node also opens `mirrors/<spaceId>/<n>` for a mirror's writer state
260
- ([mirrors](storage.md#mirrors)), `folder/<spaceId>` for a data folder's, and
261
- a host `host` for its subscriptions.
185
+ `accounts/<id>/stores`. A connected app uses
186
+ `indexedDBStores('minca-app:<account DID>')`. These names may change
187
+ ([sync and storage](storage.md#indexeddb)). A pod's layout is in
188
+ [spec 05](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
262
189
 
263
- `copyAccountData({ from, to, did, accountKey? })` copies every space an
264
- account holds, with its key and records, from one set of stores to another —
265
- the account registry too, when `accountKey` is given. It is a union: every
266
- version goes through the same ordering rule as sync, so copying into a store
267
- that holds some of it already is safe, and copying twice changes nothing.
190
+ ### Copying an account
268
191
 
269
- Copied versions are meant to pass the same checks as versions arriving by
270
- sync ([02 — Records](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md), validation) before they are stored.
192
+ `copyAccountData({ from, to, did, accountKey? })` copies every space an
193
+ account holds, with its keys and records, from one set of stores to another.
194
+ With `accountKey` it copies the account registry too. It merges by the same
195
+ rule as sync, so copying into a store that has some of it already is safe,
196
+ and copying twice changes nothing.
197
+
198
+ > **Known defect:** `copyAccountData` stores versions without validating
199
+ > them, so a pod another origin wrote to can
200
+ > bring in versions a peer's would have been refused. Tracked in
201
+ > [#20](https://github.com/leifriksheim/minca/issues/20).
202
+
203
+ ### Places in a key's line
204
+
205
+ Every version a key signs in a space takes the next place in that key's line
206
+ for the collection. Writes by one key in one space go one at a time, and the
207
+ place is saved before the version leaves the node. Where it is saved depends
208
+ on the key:
209
+
210
+ - **A key made for this run** keeps its places in memory.
211
+ - **A writer key** (`config.writerKey`) keeps them beside the key.
212
+ - **A key handed in** (`config.sessionKey`) or a carrier's key keeps them in
213
+ the `writers` store, so a restart carries on.
214
+
215
+ A handed-in key may sign in several nodes at once: every tab of an app signs
216
+ with the app's key. So each place is taken under a Web Lock
217
+ (`minca-writer:lines/<did>/<space>`) shared by the origin's tabs and workers,
218
+ and read fresh from the store each time. Nodes that share a key must share
219
+ that store too. Two nodes signing with one key from separate stores fork its
220
+ lines, and every peer then withdraws what it signed in a forked collection
221
+ from the fork on.
222
+ [Spec 02 §4.10](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md).
271
223
 
272
- > **Known defect:** `copyAccountData` stores each version with
273
- > `addVersion` directly, without running it through the validation
274
- > pipeline (`packages/core/src/node/copy.ts`). A pod or data folder that another origin
275
- > wrote to can bring versions this node would have refused from a peer. A fix
276
- > will validate on copy, as sync does.
277
- > Tracked in [#20](https://github.com/leifriksheim/minca/issues/20).
224
+ ### Writer keys
278
225
 
279
- _Source: `packages/core/src/node/stores.ts`, `packages/core/src/node/copy.ts`, `packages/core/src/session/places.ts` (`storesFor`). Tests: `packages/core/tests/account.test.ts`, `packages/core/tests/folder-adapter.test.ts`._
226
+ With `writerKey`, a node claims a lasting key when it starts and signs with
227
+ it until it closes. The device then keeps one log in each space, instead of
228
+ a new one each run. A key goes to one node at a time. If every key is taken,
229
+ or none can be locked, the node makes a key for this run instead.
230
+
231
+ In the browser, `browserWriterKeys(name)` keeps up to 32 keys in IndexedDB,
232
+ one database per slot (`<name>:writer:<slot>`), each claimed under a Web Lock
233
+ of the same name. A tab that finds a slot taken tries the next. A tab that
234
+ closes or crashes frees its slot. The private key can't be extracted: a
235
+ script in the page can sign with it while it runs, but can't take it away.
236
+ Without IndexedDB or Web Locks there are no writer keys.
237
+
238
+ A node started from a store description, such as `startPageNode` or a node in
239
+ a worker, claims its key under the account's IndexedDB prefix, even when its
240
+ stores are in a data folder. So signing out (`deleteBrowserData`) deletes the
241
+ keys too, and a key never goes in a data folder that other apps share.
242
+
243
+ What happens when a key goes away:
244
+
245
+ - `forget()` drops the key but keeps its places, which still count for this
246
+ run. The slot's next claim makes a new key and clears them.
247
+ - `revokeSelf` forgets the claimed key before it writes a single revoke, so a
248
+ page closed mid-way leaves no revoked key to claim again. With a peer
249
+ connected in any open space, each revoke waits up to `waitMs` for one to
250
+ take it in.
251
+ - A node that claims a key the account registry has revoked forgets it, and
252
+ uses a key for this run. The next start claims a new lasting one.
253
+ - A node never signs at a place behind one it already took this run. If the
254
+ slot lost its places (site data cleared while the page was open), every
255
+ write fails until the page reloads, since signing on would fork the line.
256
+ A slot whose connection the browser closed reopens only while it still
257
+ holds the key.
258
+
259
+ The CLI keeps its writer keys outside its home, in
260
+ `<local>/writer-keys/slot-<n>/` ([data folders](storage.md#data-folders)).
261
+ The key is sealed under the account's local key in `key.sealed` (mode 600,
262
+ label `minca/writer-key/v1`, bound to `{ did, slot }`), so a copy of the files
263
+ can't sign, and a key moved to another slot or account is refused. Its places
264
+ are in `heads/`, and numbered `lock.<n>` files name the process holding it,
265
+ taken over once that process is gone.
280
266
 
281
267
  ## Opening and holding spaces
282
268
 
283
- A space is opened (its store read, its peers joined, sync started) the first
284
- time anything asks for it — a read, a write, a status — and stays open until
285
- it is released or the node closes. Opening a space also: publishes the
286
- account's profile in it ([following the account](#following-the-account)), checks whether the session note was revoked
287
- there ([events](#events), `revoked`), and names the account's carriers as keepers if the
288
- account manages it ([spec 06 §4.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
269
+ A space opens the first time anything asks for it: a read, a write, a status.
270
+ Opening reads its store, joins its peers and starts syncing. It also
271
+ publishes the account's profile there, checks whether the node's note was
272
+ revoked there ([`revoked`](#events)), and names the account's carriers as
273
+ keepers if the account manages the space.
289
274
 
290
- `spaces.hold(id)` keeps a space open until released. It returns a function
291
- that lets go of that one hold:
275
+ The space stays open until it is released or the node closes.
276
+ `spaces.hold(id)` keeps it open, and resolves to a function that lets go:
292
277
 
293
- - Holds are counted per space. When the count reaches zero, the space closes.
294
- - Releasing twice does nothing.
295
- - A hold made before the space was closed for another reason (leaving it) is
296
- tied to that stretch of being held: releasing it later does nothing to a hold
297
- made after rejoining.
298
- - Reading or writing needs no hold.
278
+ ```ts
279
+ const release = await node.spaces.hold(space.id);
280
+ // later
281
+ await release();
282
+ ```
299
283
 
300
- > Rationale: anything that needs a space live holds it — a screen showing it, a
301
- > call in it — so a screen going away never cuts off a call in the same space.
284
+ - Holds are counted per space. At zero, the space closes.
285
+ - Releasing twice does nothing.
286
+ - A hold from before the space was left is tied to that time. Releasing it
287
+ later doesn't touch a hold made after rejoining.
288
+ - Reading and writing need no hold.
302
289
 
303
- _Source: `packages/core/src/node/node.ts` (`runtime`, `hold`, `closeRuntime`). Tests: `packages/core/tests/live.test.ts` ("holding a space")._
290
+ Anything that needs a space live holds it, such as a screen or a call. That
291
+ way a screen going away never cuts off a call in the same space.
304
292
 
305
293
  ## Leaving a space
306
294
 
307
- `spaces.leave(id)` first gives up the account's place in the space
308
- ([spec 03 §6.2](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)):
309
- it writes the account's own removal, `sys.remove` naming itself, so the
310
- others stop counting it a reader and a private space's key changes. Leaving
311
- needs no grant. A founder who leaves is a founder no more, for good; to stay
312
- without being one, `spaces.stepDown`
313
- ([spaces](spaces.md#the-top-and-founders)). Then it deletes
314
- the space's `sys.joined` record in the account registry, closes the space and
315
- forgets it with its keys. The account registry, the contacts space and carry
316
- spaces cannot be left.
317
-
318
- - The removal goes out only while the space is open, so `leave` waits up to
319
- 5 s for a peer of another account to say it has it. With nobody reachable,
320
- it leaves anyway.
321
- - Another device of the account that follows the deleted `sys.joined`, and
322
- still sees the account holding a place, writes the removal itself, and waits
323
- the same way.
324
- - Shared to view, or the only reader left, there is nothing to write and
295
+ `spaces.leave(id)` first gives up the account's place. It writes a
296
+ `sys.remove` naming the account, so the others stop counting it a reader and a
297
+ private space's key changes. Leaving needs no grant. Then it deletes the
298
+ space's `sys.joined` record, closes the space and forgets it with its keys.
299
+
300
+ A founder who leaves is a founder no more, for good. To stay without being
301
+ one, use [`spaces.stepDown`](permissions.md#the-top-and-founders).
302
+
303
+ - The removal waits up to 5 seconds for a peer of another account to have
304
+ it. With nobody reachable, the node leaves anyway.
305
+ - Another device of the account that sees the `sys.joined` record go, while
306
+ the account still holds a place, writes the removal itself.
307
+ - Shared to view, or the last reader left, there's nothing to write, and
325
308
  `leave` returns at once.
326
- - A note that may not change access (a narrow app note) can't write the
327
- removal; `leave` still forgets the space, and another device writes it.
309
+ - A narrow app note that may not change access can't write the removal.
310
+ `leave` still forgets the space, and another device writes it.
328
311
 
312
+ The account registry, the contacts space and carry spaces can't be left.
329
313
  `contacts.remove` and `contacts.block` leave the space for two this way.
330
-
331
- _Source: `packages/core/src/node/node.ts` (`spaces.leave`, `giveUpPlace`, `forget`, `LEAVE_WAIT_MS`), `packages/core/src/node/space-membership.ts` (`giveUpPlace`), `packages/core/src/node/space-peers.ts` (`writeUntilStored`). Tests: `packages/core/tests/key-change.test.ts` ("leaving a private space"), `packages/core/tests/contacts.test.ts` ("removing a contact gives up your place"), `packages/core/tests/node.test.ts` ("the account registry"), `packages/core/tests/carrier.test.ts` ("its carry space cannot be left…")._
314
+ [Spec 03 §6.2](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md).
332
315
 
333
316
  ## Holding part of a space
334
317
 
335
- With `config.cache`, and once a space names at least one keeper
336
- ([03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md), `sys.keepers`), the node holds only the collections it
337
- uses, besides the space's own `sys.*` collections. Everything about this is the
338
- node's own choice; how it tells peers what it holds is in
339
- [05](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md). As implemented:
340
-
341
- - Collections listed in `cache.collections` are held from the start and never
342
- dropped.
343
- - A query marks the collections it reads (its own and every `include … from`)
344
- as used, and a write the collection it writes in; sync then fetches them. A
345
- writer holds its own earlier writes that way, and the rest beside them. A query's result has `complete: false`
346
- until, for every collection it reads, the node has once been level with a
347
- node holding the whole space, **and** it lacks nothing a writer's line in
348
- that collection names
349
- ([spec 02 §4.10](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
350
- A version naming one not here adds it to `missing` and asks every peer for
351
- it by id; when it arrives it comes off. They are asked again whenever the
352
- collection is level with a peer.
353
- - Until the node has once caught up fully with a node holding the whole space,
354
- it cannot know whether the space names keepers, so it holds only what it uses.
355
- - A collection holding a pending write (below) is never dropped.
356
- - A collection unused for `cache.unusedAfterDays` (default 30) days is dropped
357
- when the space opens and every 6 hours while it stays open. It stops being
358
- held _before_ its versions are removed, so nothing syncs it back meanwhile.
359
- - A space that names no keeper is held whole, and the node may itself be one
360
- of its copies.
361
- - When what it holds changes (whole or part, or a newly used collection), the
362
- node says hello to every peer.
363
-
364
- On every node, holding part of a space or all of it, its own writes in a
365
- space that names keepers are _pending_ until `min(keepers named, max(copies ??
366
- 2, cache.copies ?? 0))` of them have them; a keeper's own node counts as one.
367
- A node holding part of the space keeps them in its store, across runs; one
368
- holding all of it in memory, the latest 4096. A keeper confirms a write the way
369
- the spec says: by `stored`, or by being level with the writer on its
370
- collection. Only a peer named in `sys.keepers` counts
371
- ([spec 05 §9](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md)).
372
-
373
- `node.spaces.kept(spaceId, waitMs, since?)` waits up to `waitMs` (at most a
374
- minute) for this node's writes in a space to be kept elsewhere. In a space
375
- that names keepers, it says `'keepers'` once none of its writes from `since`
376
- (ms) on, or all of them, is pending. In one that names none, every member's
377
- node is a copy, so it says `'peer'` once a peer connected now holds all this
378
- node does: less sure, since that peer may be a device that goes away. Null
379
- when nobody had, in time. A node that may stop before it syncs again waits on
380
- it: a tab about to close, a command about to exit, a node a server runs for a
381
- while (the MCP service's).
382
-
383
- This state is kept in the space's own store (`spaces/<spaceId>`):
384
-
385
- | Key | Value (UTF-8 JSON) |
386
- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
387
- | `cache` | `{ "settled": boolean, "used": { [collection]: ms }, "level": { [collection]: ms }, "missing": { [collection]: [version id…] } }`. `settled`: has synced with a whole-space peer; `used`: when a query last used it; `level`: when it was first level with a whole-space peer; `missing`: what a writer's line there names that isn't here |
388
- | `pending/<version id>` | `{ "collection": string, "by": [keeper DID…], "at": ms }`, deleted once `by` reaches the target |
389
-
390
- What a keeper withholds from the middle of a writer's line shows up as
391
- missing, whichever peer the node was level with. A writer's newest versions
392
- are named by no line yet; holding those back needs every peer the node syncs
393
- with to do it.
394
-
395
- The account registry, the contacts space and carry spaces are always held
396
- whole. Apps connected to an account home use `cache: {}` by default ([the app-side client](#the-app-side-client)).
397
-
398
- _Source: `packages/core/src/node/space-holding.ts` (`openSpaceHolding`, `kept`), `packages/core/src/node/space-writing.ts` (`write`), `packages/core/src/node/types.ts` (`CacheConfig`). Tests: `packages/core/tests/caches.test.ts`, `packages/core/tests/reconcile.test.ts` ("holding part of a space")._
318
+ A node doesn't need every record in a space. With `config.cache`, once a space
319
+ names at least one keeper, the node holds only the collections it uses, plus
320
+ the space's own `sys.*` collections. Apps connected to an account home do this
321
+ by default.
322
+
323
+ ```ts
324
+ declare const signer: RootSigner;
325
+ // ---cut---
326
+ import { createNode, indexedDBStores, type RootSigner } from '@minca/core';
327
+
328
+ const node = await createNode({
329
+ signer,
330
+ stores: indexedDBStores('my-app'),
331
+ cache: { collections: ['app.todo.item'] },
332
+ });
333
+ ```
334
+
335
+ `cache` is a [`CacheConfig`](https://minca.dev/api/core/interfaces/CacheConfig/): the
336
+ collections to hold from the start, when to drop one nothing uses, and how
337
+ many keepers a write must reach.
338
+
339
+ ### What gets held
340
+
341
+ - A query marks every collection it reads as used, including each
342
+ `include … from`, and a write marks the one it writes. Sync then fetches
343
+ them.
344
+ - Until the node has caught up once with a node holding the whole space, it
345
+ can't know whether the space names keepers, so it holds only what it uses.
346
+ - An unused collection is dropped when the space opens, and every 6 hours
347
+ while it stays open. It stops being held before its versions go, so nothing
348
+ syncs it back meanwhile. A collection with a pending write is never dropped.
349
+ - A space that names no keeper is held whole.
350
+ - The account registry, the contacts space and carry spaces are always held
351
+ whole.
352
+ - When what it holds changes, the node says hello to every peer again.
353
+
354
+ ### Complete results
355
+
356
+ A query's result has `complete: false` until, for every collection it reads,
357
+ the node has been level once with a node holding the whole space, and it
358
+ lacks nothing a writer's line there names. A version that names one the node
359
+ doesn't have adds it to `missing`, and the node asks every peer for it by id.
360
+ It asks again whenever the collection is level with a peer.
361
+
362
+ So what a keeper withholds from the middle of a writer's line shows up as
363
+ missing. A writer's newest versions aren't named by any line yet, so holding
364
+ those back would take every peer the node syncs with.
365
+
366
+ ### Pending writes
367
+
368
+ In a space that names keepers, every node's own writes are _pending_ until
369
+ `min(keepers named, max(copies ?? 2, cache.copies ?? 0))` keepers have them. A
370
+ keeper's own node counts as one. A keeper confirms a write with `stored`, or by
371
+ being level with the writer on its collection. Only peers named in
372
+ `sys.keepers` count. A node holding part of a space keeps pending writes in
373
+ its store across runs. One holding all of it keeps the latest 4096 in memory.
374
+
375
+ `node.spaces.kept(spaceId, waitMs, since?)` waits up to `waitMs`, at most a
376
+ minute, for this node's writes to be kept elsewhere:
377
+
378
+ - In a space with keepers, it says `'keepers'` once none of its writes from
379
+ `since` (ms) on is pending.
380
+ - In a space without, it says `'peer'` once a connected peer holds all this
381
+ node does. That's less sure, since the peer may be a device that goes away.
382
+ - It says `null` if nobody had them in time.
383
+
384
+ Wait on it before a node stops: a tab about to close, a command about to exit,
385
+ a server's node at the end of its job.
386
+
387
+ ### What the node stores
388
+
389
+ This state lives in the space's own store, `spaces/<spaceId>`:
390
+
391
+ | Key | Value (JSON) |
392
+ | ---------------------- | -------------------------------------------------------------------- |
393
+ | `cache` | `{ settled, used, level, missing }`, below |
394
+ | `pending/<version id>` | `{ collection, by: [keeper DID…], at }`, deleted once `by` is enough |
395
+
396
+ In `cache`, `settled` says whether the node has synced with a whole-space
397
+ peer. `used` maps each collection to when a query last used it, `level` to
398
+ when it was first level with a whole-space peer, and `missing` to the version
399
+ ids a writer's line names that aren't here.
400
+ [Spec 05 §9](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
399
401
 
400
402
  ### Planned: caches that widen and trim
401
403
 
402
- > **Planned.** None of it changes what other nodes see. Fetching linked
403
- > records by key, and holding less than a collection, need new messages and
404
- > are planned in [spec 05 §9.1](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
405
-
406
- - **Widening.** A node holding part of a space starts holding all of it when
407
- too few keepers are online (Holochain's arcs: nodes grow their share when
408
- others go missing). Opt-in only (`cache.widen: true`), since done on its own
409
- it could fill a disk at a bad moment. Open: what "too few" is, and for how
410
- long. Today a cache only widens as queries use collections.
411
- - **Trimming by size.** `cache.maxBytes`: above it, drop least recently used
412
- collections first, undeclared ones before declared. Also trim when
413
- `navigator.storage.estimate()` says room is low, before the browser clears
414
- the site. Pending writes are never dropped.
404
+ > **Planned.** A node holding part of a space would hold all of it when too
405
+ > few keepers are online (opt-in, `cache.widen: true`), and drop least
406
+ > recently used collections above `cache.maxBytes` or when the browser runs
407
+ > low on room. Fetching linked records by key, and holding less than a
408
+ > collection, are planned in
409
+ > [spec 05 §9.1](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
415
410
 
416
411
  ## Following the account
417
412
 
418
- What counts in the account's list of spaces, and what a device with the
419
- account key must keep current for carriers, is protocol
420
- ([spec 06 §1.3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). How the reference node does it:
421
-
422
- The node's `registry` store ([stores](#stores)) lists every space it holds,
423
- with its key(s), its invite secret while one is waiting to be used, its place
424
- (`founder`, or a role it holds) as last seen, the relays the space names and, for an app without the account
425
- key, its member key. Its format is the node's own
426
- (`packages/core/src/space/space-manager.ts`).
427
-
428
- Three kinds of space are the account's own machinery and are hidden from
429
- `spaces.list`:
430
-
431
- | Space | Derived from | Notes |
432
- | -------------------- | ------------------------------------------ | -------------------------------------------------------------- |
433
- | The account registry | the account key | Never in the node's registry; opened directly. Cannot be left. |
434
- | The contacts space | the account key, or `config.contactsSpace` | Held in the registry, hidden. Cannot be left. |
435
- | Carry spaces | the account key and the carrier's key | Never in the node's registry; opened directly. Cannot be left. |
436
-
437
- **Reconciling.** With an account key, the node makes its spaces match the
438
- account's list of `sys.joined` records. This runs at start and whenever
439
- records change in the account registry, one run at a time. It:
440
-
441
- 1. joins every space a live `sys.joined` record names that the node does not
442
- hold, using the view-only invite in the record;
443
- 2. leaves every space whose `sys.joined` record is deleted;
444
- 3. writes a `sys.joined` record for any space held here that the account
445
- registry has never heard of (joined before the registry existed, or on a
446
- node without the account key);
447
- 4. brings every carrier's passes and wakes up to date
448
- ([spec 06 §4.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md));
449
- 5. names the account's carriers as keepers of the open spaces it manages
450
- (also whenever a space opens);
451
- 6. asks every host the account uses how it stands, handing it the spaces if it
452
- has been paid since ([carriers and hosting](#carriers-hosting-and-notifications)),
453
- without waiting for the answer.
454
-
455
- Creating or joining a space writes its `sys.joined` record; leaving deletes it.
456
-
457
- **Profiles.** When a space opens, when the node's account takes a place in it,
458
- and when the account's name changes on any device, the node publishes the
459
- account's profile in that space: `{ name, contactKey? }`, with the name taken
460
- from the account registry's `sys.profile` record and `contactKey` only when
461
- the node holds the contact key. It does this only in spaces other than the
462
- account registry and the contacts space, only with an account name to publish,
463
- and never under a note that lacks `/account/write`, such as an agent's. The profile record format is in
464
- [03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md).
465
-
466
- **Joining.** `spaces.join(invite)` accepts a bare invite or any link carrying
467
- `#invite=…`, `?invite=…` or `&invite=…`, long or short; a short one is
468
- fetched from its mailboxes first ([spaces](spaces.md#invites)). It stores the space (and its key, for
469
- a private space), stores `memberKey` when given, writes the `sys.joined`
470
- record, then tries to use the invite's role secret at once. If the space's
471
- invite record has not reached this device yet, the space is held with
472
- `joining: true` and the node tries again each time records arrive in it.
473
-
474
- **Leaving.** `spaces.leave(id)` gives up the account's place in the space,
475
- then deletes the `sys.joined` record, closes the space and forgets it with its
476
- key ([leaving a space](#leaving-a-space)).
477
-
478
- _Source: `packages/core/src/node/node.ts` (`reconcileOnce`, `remember`, `forget`, `finishJoining`, `spaces`), `packages/core/src/node/node-contacts.ts` (`publishProfile`), `packages/core/src/space/space-manager.ts`. Tests: `packages/core/tests/node.test.ts` ("the account registry"), `packages/core/tests/profiles.test.ts`, `packages/core/tests/space-access.test.ts`._
413
+ With the account key, a node keeps its spaces in step with the account's
414
+ list in the account registry. Join a space on your phone, and your laptop
415
+ joins it too.
416
+
417
+ The node's own `registry` store lists each space it holds: its keys, an
418
+ invite secret while one waits to be used, the account's place there as last
419
+ seen, the relays the space names, and, for an app without the account key,
420
+ its member key.
421
+
422
+ Three kinds of space are the account's own machinery, and `spaces.list`
423
+ hides them:
424
+
425
+ | Space | Derived from | Notes |
426
+ | -------------------- | ------------------------------------------ | ---------------------------------------------------------------------- |
427
+ | The account registry | the account key | Opened directly. Can't be left. |
428
+ | The contacts space | the account key, or `config.contactsSpace` | In the node's registry, so it can be granted to an app. Can't be left. |
429
+ | Carry spaces | the account key and the carrier's key | Opened directly. Can't be left. |
430
+
431
+ ### Reconciling
432
+
433
+ At start, and whenever the account registry changes, the node reconciles,
434
+ one run at a time:
435
+
436
+ 1. It joins every space a `sys.joined` record names that it doesn't hold,
437
+ with the view-only invite in the record.
438
+ 2. It leaves every space whose `sys.joined` record was deleted.
439
+ 3. It writes a `sys.joined` record for a space it holds that the registry
440
+ doesn't know.
441
+ 4. It brings every carrier's passes and wakes up to date.
442
+ 5. It names the account's carriers as keepers of the open spaces it manages.
443
+ 6. It asks each host the account uses how it stands, without waiting, and
444
+ hands it the spaces if it was paid ([hosting](#carriers-hosting-and-notifications)).
445
+
446
+ Creating or joining a space writes its `sys.joined` record. Leaving deletes it.
447
+
448
+ ### Profiles
449
+
450
+ The node publishes the account's profile, `{ name, contactKey? }`, in a space
451
+ when it opens, when the account takes a place there, and when the name
452
+ changes on any device. The name comes from the registry's `sys.profile`
453
+ record, and `contactKey` is included only when the node holds it. It skips
454
+ the account registry and the contacts space, an account with no name, and
455
+ any note without `/account/write`, such as an agent's.
456
+
457
+ ### Joining
458
+
459
+ `spaces.join(invite)` takes a bare invite, or any link with `#invite=…`,
460
+ `?invite=…` or `&invite=…`. A short link is fetched from its mailboxes first
461
+ ([invites](spaces.md#invites)). It stores the space and its key, and
462
+ `memberKey` when given, writes the `sys.joined` record, then uses the
463
+ invite's role secret. If the space's invite record hasn't arrived yet, the
464
+ space shows `joining: true`, and the node tries again each time records
465
+ arrive.
466
+ [Spec 06 §1.3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
479
467
 
480
468
  ## Events
481
469
 
482
- `node.subscribe(listener)` delivers `NodeEvent`s and returns an unsubscribe
483
- function. A listener that throws does not stop the others.
470
+ `node.subscribe(listener)` tells you what happens, and returns a function to
471
+ stop. A listener that throws doesn't stop the others.
484
472
 
485
- | `type` | Fields | When |
486
- | ---------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
487
- | `records` | `space` | Records were added, changed or deleted in a space, locally or by sync. |
488
- | `status` | `space` | Connection state or peers changed. A status change in the account registry is re-emitted for every open space (which peers are the account's own is read off the registry's peers). |
489
- | `spaces` | — | The node's list of spaces changed: created, joined, left, a role or waiting invite changed. |
490
- | `account` | — | The account's profile may have changed (records changed in the account registry, or `setName`). |
491
- | `rejected` | `space`, `peer`, `reason` | A peer sent a version that failed validation. |
492
- | `message` | `space`, `from`, `peer`, `recordsOnly`, `message` | A live message arrived ([live messages and status](#live-messages-and-status)). |
493
- | `revoked` | `space` | The note this node writes under was revoked in that space. Emitted at most once per space per node. |
473
+ ```ts
474
+ const stop = node.subscribe((event) => {
475
+ if (event.type === 'records') console.log('changed in', event.space);
476
+ });
477
+ ```
478
+
479
+ Each event is a [`NodeEvent`](https://minca.dev/api/core/type-aliases/NodeEvent/), told
480
+ apart by its `type`: records changed, status, the list of spaces, the account,
481
+ a refused version, a live message, a revoked note, or the network.
494
482
 
495
- _Source: `packages/core/src/node/types.ts` (`NodeEvent`), `packages/core/src/node/node.ts` (`fromRuntime`, `checkRevoked`). Tests: `packages/core/tests/node.test.ts` ("events announce local writes"), `packages/core/tests/connect.test.ts` ("disconnecting revokes the note")._
483
+ A `status` change in the account registry is sent for every open space too,
484
+ since that is where the node learns which peers are the account's own.
496
485
 
497
486
  ### Versions that wait or are refused
498
487
 
499
- A version from a peer stands, waits or is refused
500
- ([spec 02 §9.5](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
501
- What the node does with each is its own:
502
-
503
- - A batch from a peer is admitted `sys.collection` versions first, then by
504
- ascending `seq`, so definitions and first versions are in before what
505
- depends on them and little has to wait.
506
- - A version that waits is held in memory, at most 1,000, the oldest dropped
507
- when full, and judged again whenever something new is stored. A version
508
- waiting for its first version, or the one before it, asks the peer for
509
- them at once.
510
- - A withdrawn version (allowed when written, then taken away by a removal or
511
- a revoke it had not seen) is stored and passed on like one that stands,
512
- emits no `rejected` event, and never shows as a record: `records.get` and queries skip
513
- it. It is there for proofs that cite it ([spec 09 §6](https://github.com/leifriksheim/minca/blob/main/spec/09-contracts.md)).
514
- - A version that fails its collection's contract stands: it is stored and
515
- passed on, emits no `rejected` event, and `records.get` and queries skip
516
- it ([contracts](contracts.md)).
517
- - A refused version emits a `rejected` event with the peer and the reason,
518
- and is remembered as (peer, id), at most 10,000, so it is not asked of that
519
- peer again. Never by id alone: a copy with a mangled signature has the
520
- genuine version's id.
521
-
522
- _Source: `packages/core/src/sync/sync-engine.ts` (`admit`, `admitAll`, `rank`, `MAX_WAITING`, `MAX_REFUSED`). Tests: `packages/core/tests/reconcile.test.ts` ("a refused version is not asked for again", "a version that waits for its first version asks for it at once, and is acknowledged once in")._
488
+ A version from a peer stands, waits or is refused. What the node does with
489
+ each:
490
+
491
+ - A batch is taken in `sys.collection` versions first, then by `seq`, so
492
+ what others depend on is in first and little has to wait.
493
+ - A version that waits is held in memory, at most 1,000, oldest dropped
494
+ first, and judged again whenever something new is stored. One waiting for
495
+ an earlier version asks the peer for it at once.
496
+ - A withdrawn version, allowed when written but taken away by a removal or a
497
+ revoke it hadn't seen, is stored and passed on. It sends no `rejected`
498
+ event and never shows as a record. It is kept for proofs that cite it
499
+ ([spec 09 §6](https://github.com/leifriksheim/minca/blob/main/spec/09-contracts.md)).
500
+ - A version that breaks its collection's [contract](contracts.md) is also
501
+ stored and passed on, with no `rejected` event, and `records.get` and
502
+ queries skip it.
503
+ - A refused version sends a `rejected` event and is remembered by peer and
504
+ id, at most 10,000, so it isn't asked of that peer again. Never by id
505
+ alone: a copy with a mangled signature has the real version's id.
506
+
507
+ [Spec 02 §9.5](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md).
523
508
 
524
509
  ## Live messages and status
525
510
 
526
- `spaces.send(id, message, to?)` sends a JSON value to the peers connected in
527
- the space right now, kept nowhere and signed as nothing. The message is
528
- `JSON.stringify(message ?? null)`; if that is longer than 65 536 characters
529
- the call throws "A live message can be at most 64 KB". It goes as a `live`
530
- message to every connected peer of the space, once per peer, over whichever
531
- network that peer was last connected on. With `to`, it goes only to peers
532
- whose session DID equals `to` (one device), or whose account DID, as learned
533
- from their `who`, equals `to` (every device of that account); a peer whose
534
- `who` has not been checked yet is matched by session DID only. In a private
535
- space, nothing goes to someone removed or who left, and nothing from them is
536
- emitted. An agent's node
537
- refuses `send` ([acting as an agent](#a-node-acting-as-an-agent)). The wire
538
- format, the per-peer allowance (a burst of 60, then 20 per second) and how the
539
- sender's account is established are in
540
- [spec 04 §9](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md).
541
-
542
- A received live message is emitted as a `message` event,
543
- `{ type: "message", space, from, peer, recordsOnly, message }`:
544
-
545
- | Field | Meaning |
546
- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
547
- | `from` | The account behind the sending device, proven by the note it showed, made out to the key the connection proved. `null` for a peer that showed no note (a carrier, a node serving sockets). |
548
- | `peer` | The sending device's session DID — also where a reply to that device goes. |
549
- | `recordsOnly` | `true` when the sender's note grants writing records in this space and nothing more (`/record`): it can't define collections there ([spec 01 §8](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md)). `false` for a note that only reads. |
550
- | `message` | The value sent. |
551
-
552
- `spaces.status(id)` returns `SpaceStatus`:
553
-
554
- | Field | Meaning |
555
- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
556
- | `connection` | `offline` (no network), `connecting`, `connected` (while any one transport is connected: a relay socket open, or a peer), `error` (the first connect failed and nothing has connected since). A space whose relays all drop and whose peers leave is `connecting` again, not `connected`. |
557
- | `peers` | Session DIDs connected in the space. |
558
- | `own` | Of `peers`, the account's own other devices and apps: those also connected in the account registry, minus carriers. Empty without an account key. |
559
- | `carriers` | Of `peers`, the account's carriers, by the keys `sys.carrier` records name. |
560
- | `accounts` | Session DID → account, for each peer that showed a valid note. |
561
- | `fingerprint` | A fingerprint of every version held; equal on two nodes means identical data ([the store in memory](storage.md#the-store-in-memory)). |
562
- | `rejected` | How many versions peers sent failed validation. |
563
- | `holds` | `"all"`, or the sorted list of collections held ([holding part of a space](#holding-part-of-a-space)). |
564
- | `pending` | This node's writes still waiting for keepers ([holding part of a space](#holding-part-of-a-space)). |
565
-
566
- > Rationale: a peer's key does not say whose it is, but only the account's own
567
- > devices and apps can read its registry, so a peer there is one of ours.
568
-
569
- _Source: `packages/core/src/node/node.ts` (`spaces.send`, `spaces.status`), `packages/core/src/node/space-peers.ts` (`send`, `onLive`), `packages/core/src/node/space-runtime.ts` (`status`). Tests: `packages/core/tests/live.test.ts`._
511
+ `spaces.send(id, message, to?)` sends any JSON value to the peers connected
512
+ in the space right now. It isn't stored or signed. Use it for things like
513
+ "typing…" or a cursor.
514
+
515
+ ```ts
516
+ await node.spaces.send(space.id, { typing: true });
517
+ ```
518
+
519
+ - The message, as JSON, can be at most 65,536 characters. Longer throws
520
+ "A live message can be at most 64 KB".
521
+ - It goes once to each connected peer, over whichever network it last used.
522
+ - With `to`, it goes only to the peer with that session DID (one device), or
523
+ to every device of the account with that DID. A peer whose account isn't
524
+ checked yet is matched by session DID only.
525
+ - In a private space, nothing goes to someone removed or who left, and
526
+ nothing from them arrives.
527
+ - An agent's node refuses `send`.
528
+
529
+ Each peer may send a burst of 60, then 20 a second.
530
+
531
+ A message that arrives is a `message` [event](https://minca.dev/api/core/type-aliases/NodeEvent/),
532
+ with the value sent, the sender's account and the device it came from.
533
+
534
+ [Spec 04 §9](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md).
535
+
536
+ ### Status
537
+
538
+ `spaces.status(id)` tells you how a space is connected, as a
539
+ [`SpaceStatus`](https://minca.dev/api/core/interfaces/SpaceStatus/): its connection, the peers
540
+ connected and whose they are, a fingerprint of what it holds, and what it
541
+ holds and still has pending.
542
+
543
+ `connection` is `offline` with no network, and `connected` while any one
544
+ relay socket or peer is. A space whose relays all drop and whose peers leave
545
+ goes back to `connecting`. It is `error` only when the first connect failed
546
+ and nothing has connected since.
547
+
548
+ A peer's key doesn't say whose it is. But only the account's own devices and
549
+ apps can read its registry, so a peer there is one of ours. That is how `own`
550
+ is worked out.
570
551
 
571
552
  ## The rest of the node's surface
572
553
 
573
- The node's other parts are specified where their data lives; the node only
574
- exposes them. Every value a node method returns is JSON-serialisable, so the
575
- same calls can be exposed over a command line, MCP and WebMCP
576
- ([actions](actions.md)).
577
-
578
- - `node.spaces` — create, invite, preview, join, leave, access, `may`,
579
- `holdsRole`, `defineRole`, `assign`, `unassign`, `removeMember`, `stepDown`,
580
- `succeed`, `closeInvite`,
581
- `changeKey`, `setRelays`, `setKeepers`, `revoke`, `profiles`,
582
- `authenticator` ([03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md),
583
- [04](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)). Default invite role: `member` when
584
- the inviter may assign it, else the first role by name it may assign; with
585
- none, a view-only invite ([spaces](spaces.md#invites)).
586
- - `access(id)` answers `{ roles, members, invites, founder, top, headless,
587
- successors, mine, heads, key, relays, keepers, copies, forks, flagged }`
588
- ([spaces](spaces.md#the-top-and-founders)). Each role has its
589
- current `definitions` (one, or rivals that hold only the grants they
590
- share), each with `event`, `by` (null for the constitution's), `grants`
591
- and `nests`. Each member is `{ did, founder, roles }`. `founder` and
592
- `mine` say what this account is here.
593
- - `may(id, cmd, args?, account?)` asks whether this account, or another,
594
- may invoke a command with these arguments now, as the replay judges it
595
- ([spec 03 §2](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)).
596
- Apps use it to show what someone can do; peers judge each version on
597
- its own.
598
- - `holdsRole(id, role, account?)` asks whether this account, or another,
599
- holds every grant a role gives, each as wide or wider: its own grant's
600
- command covers it, and every statement of its policy is among the
601
- role's. Only the words are compared, so it can say no where the
602
- policies would allow, never yes where they wouldn't. Apps use it before
603
- giving a bot a role, and `minca agent` before taking instructions.
604
- - `defineRole(id, { name, title?, grants, nests? })` writes the role's
605
- definition, each grant a delegation from this account to the role. It
606
- holds only what this account could invoke itself.
607
- - `assign(id, did, role)` and `unassign(id, did, role)` give and take a
608
- role; taking your own needs no grant. `removeMember(id, did)` removes an
609
- account with every role it holds; removing yourself is leaving. Taking
610
- power away writes a cutoff of what this node holds of theirs
611
- ([spec 03 §6.3](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)).
612
- - `node.records`, `node.collections` — [02](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md). `records.watch`
613
- re-runs a query after every `records` event for its space, one run at a time,
614
- with at most one more queued.
615
- - `node.account` — `profile()`, `setName(name)` (writes `sys.profile`, key
616
- `profile`, in the account registry, then republishes the profile in every
617
- open space), `setAvatar({ bytes, mime } | null, { name? })` and `picture()`
618
- (the account's picture, likewise; see [spaces](spaces.md)), `revoke(key, { waitMs? })` (one of the account's keys, by DID, in the account registry). All need the account
619
- key.
620
- - `spaces.revoke(space, key, { waitMs? })` and `account.revoke` resolve once the revoke is written; with
621
- `waitMs`, once a peer says it has taken it in, or that long has passed (`true` when one did). A node
622
- with no network configured can't send it anywhere, so that is `false` at once. A node about
623
- to stop waits like that: it sends nothing afterwards.
624
- - `node.contacts` — [contacts.md](contacts.md). `ask` and `accept` make or join a space
625
- for two, so they need a note granting `/account/write` over the whole
626
- account (whole-account access).
627
- - `node.direct` — [direct-messages.md](direct-messages.md): `reachable`, `send`
628
- and `list`. Needs the account's member key for the space.
629
- - `node.inbox` — [inbox.md](inbox.md), [07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md). Needs the contact key; knocking and
554
+ Every value a node method returns can be turned into JSON. So the same calls
555
+ work over a command line, MCP and WebMCP ([actions](actions.md)).
556
+
557
+ ### Spaces
558
+
559
+ `node.spaces` creates, invites, previews, joins and leaves spaces, and
560
+ manages who is in them: `access`, `may`, `holdsRole`, `defineRole`, `assign`,
561
+ `unassign`, `removeMember`, `stepDown`, `succeed`, `closeInvite`,
562
+ `changeKey`, `setRelays`, `setKeepers`, `revoke`, `profiles` and
563
+ `authenticator` ([spaces](spaces.md)).
564
+
565
+ An invite is for `member` when the inviter may give that role. Otherwise it's
566
+ for the first role by name the inviter may give, or view-only with none
567
+ ([invites](spaces.md#invites)).
568
+
569
+ - `access(id)` gives a [`SpaceAccess`](https://minca.dev/api/core/interfaces/SpaceAccess/):
570
+ the roles with their current definitions, the members, invites, founders,
571
+ successors, keepers and more
572
+ ([the top and founders](permissions.md#the-top-and-founders)).
573
+ - `may(id, cmd, args?, account?)` asks whether an account may run a command
574
+ with these arguments now. Apps use it to show what someone can do. Peers
575
+ still judge each version on its own.
576
+ - `holdsRole(id, role, account?)` asks whether an account holds every grant a
577
+ role gives, each as wide or wider. It compares the words only, so it may
578
+ say no where the policies would allow, but never yes where they wouldn't.
579
+ Apps use it before giving a bot a role.
580
+ - `defineRole(id, { name, title?, grants, nests? })` writes a role. It can
581
+ hold only what this account could do itself.
582
+ - `assign(id, did, role)` and `unassign(id, did, role)` give and take a role.
583
+ Taking your own needs no grant. `removeMember(id, did)` removes an account
584
+ with all its roles, and removing yourself is leaving. Taking power away
585
+ writes a cutoff at what this node holds of theirs.
586
+
587
+ [Spec 03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md).
588
+
589
+ ### Revokes
590
+
591
+ `spaces.revoke(space, key, { waitMs? })` and `account.revoke(key, { waitMs? })`
592
+ resolve once the revoke is written. With `waitMs`, they wait until a peer has
593
+ taken it in or that time has passed, and say `true` when one did. With no
594
+ network, that is `false` at once. A node about to stop should wait like
595
+ this, since it sends nothing afterwards.
596
+
597
+ ### Records and the account
598
+
599
+ - `node.records` and `node.collections` read and write records
600
+ ([records and queries](records-and-queries.md), [collections](collections.md)).
601
+ `records.watch` runs a query again after each `records` event for its
602
+ space, one run at a time, with at most one more queued.
603
+ - `node.account` needs the account key. `profile()` reads the profile.
604
+ `setName(name)` writes it to the registry, then publishes it in every open
605
+ space. `setAvatar({ bytes, mime } | null, { name? })` and `picture()` do the
606
+ same for the account's picture ([spaces](spaces.md)). `revoke` revokes one
607
+ of the account's keys in the registry.
608
+ - `account.space()` is the registry's id. Keep what is the person's own
609
+ across their devices there, like an app's settings: define a collection of
610
+ yours and write records, as in any space. Every device of the account and
611
+ every app given the whole account reads them. Writing there needs the
612
+ whole account's write access: what an agent writes there counts for
613
+ nothing. Keep it small, settings and not files or lists that grow: every
614
+ device holds the registry whole, and carriers carry it. Leave the `sys.*`
615
+ records alone, and give a collection one definition, shared by every app
616
+ that uses it. An app given only some spaces has no registry: it keeps its
617
+ settings in a space it was given, or on the device.
618
+ - `node.contacts` ([contacts](contacts.md)). `ask` and `accept` make a space
619
+ for two, so they need whole-account access (`/account/write`).
620
+ - `node.direct` ([direct messages](direct-messages.md)): `reachable`, `send`
621
+ and `list`. It needs the account's member key for the space.
622
+ - `node.inbox` ([the inbox](#the-inbox)) needs the contact key. Knocking and
630
623
  accepting also need whole-account access.
631
- - `node.carriers`, `node.hosting`, `node.notifications` — [carriers and hosting](#carriers-hosting-and-notifications), [spec 06 §4](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
632
- - `node.iceServers()` — the configured ICE servers plus TURN servers a relay
633
- offers ([the network](#the-network)); what [calls](../../calls/README.md#connections) use.
634
- - `node.network` — `status()`: each relay's state (open, or waiting to redial,
635
- when and why), the connections open and those still being made, and whether
636
- a relay offered TURN; `reconnect()` redials a waiting relay now
637
- ([the network](#the-network), [spec 04 §2](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)). A `network` event follows every change.
638
- Local only: nothing here goes over the wire.
639
- - `node.asAgent({ keys, note })` — [acting as an agent](#a-node-acting-as-an-agent).
640
-
641
- _Source: `packages/core/src/node/types.ts`, `packages/core/src/node/node.ts` (`spaces`), `packages/core/src/node/space-membership.ts` (`access`, `may`, `holdsRole`, `defineRole`, `assign`, `removeAccount`), `packages/core/src/space/roles.ts` (`holdsRole`). Tests: `packages/core/tests/roles.test.ts` ("holding what a role gives"), `packages/core/tests/node.test.ts`, `packages/core/tests/space-access.test.ts`, `packages/core/tests/contacts.test.ts`, `packages/core/tests/direct.test.ts`, `packages/core/tests/profiles.test.ts`._
624
+ - `node.carriers`, `node.hosting` and `node.notifications`
625
+ ([carriers and hosting](#carriers-hosting-and-notifications)).
626
+
627
+ ### The network and agents
628
+
629
+ - `node.iceServers()` gives the ICE servers for your own connections, such as
630
+ [calls](../../calls/README.md#connections) ([the network](#the-network)).
631
+ - `node.network.status()` shows each relay's state, the connections open and
632
+ being made, and whether a relay offered TURN. `reconnect()` redials a
633
+ waiting relay now. A `network` event follows each change. This is local
634
+ only.
635
+ - `node.asAgent({ keys, note })` ([acting as an agent](#a-node-acting-as-an-agent)).
642
636
 
643
637
  ## The network
644
638
 
645
- How the node uses relays, always-on nodes and WebRTC, where
646
- [spec 04](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)
647
- leaves it the choice. Another implementation may pick other values and still
648
- meet this one.
649
-
650
- **Redialling a relay** (spec 04 §2.1). The client waits 1, 2, 4, 8, 16 s and
651
- then 30 s between attempts, each ±25% so peers that dropped together do not
652
- return together, and never stops until `disconnect`. It tries at once when the page becomes visible again, and when asked
653
- (`reconnect`). A successful open resets the count. A socket can die without
654
- closing, and after a sleep it has: so the client looks at the clock every
655
- 5 s, and a look more than 30 s after the last means the device slept; it
656
- then lets go of its socket and dials again at once, as it does when the
657
- browser reports `online`. An open socket to a Minca relay that has heard
658
- nothing for 30 s also sends `ping`; once its relay has answered one, two going unanswered end
659
- the socket ("The relay stopped answering.") and it redials. Each relay's state
660
- (`connecting`, `open`, `waiting` with the time of the next attempt and why the
661
- last one failed, `stopped`) is readable as `RelayStatus`, and through a node
662
- as `network.status()`.
663
-
664
- **Meeting** (spec 04 §2, §3). A node says hello in each room when it joins,
665
- on every relay as its socket opens, and every 2 minutes. It remembers, per
666
- room, the times it acted on from each peer in the last 2 minutes (at most
667
- 256 a peer), and the failed tries of the last 512 peers. It
668
- says hello back in a room at most once every 10 s; one due sooner waits
669
- for the 10 s, once for everyone who said hello meanwhile. Each socket
670
- sends at most 20 messages a second, in bursts of 40, and queues the rest. A
671
- connection attempt that times out is retried on the peer's next hello. `requestIce`
672
- asks every connected relay whose kind can hand out TURN passwords. Each WebRTC
673
- offer or answer waits for ICE gathering to finish, or 2 s, and carries what it
674
- found.
675
-
676
- **Kinds of relay** (spec 04 §1.2). `network.relays` may mix kinds:
677
- `['wss://relay.minca.social', 'nostr+wss://relay.damus.io']`. A relay of a kind
678
- this library doesn't speak is left out of `network.status()`. On a Nostr
679
- relay, each event is signed with a key made for it and forgotten.
680
-
681
- **A space's relays** (spec 04 §4). A relay socket opened only for spaces'
682
- own relays is closed once no room needs it. A node whose account may invoke
683
- `/space/relays` in a space that names no relays names its own configured relays (the valid ones,
684
- at most 8) by itself.
685
-
686
- **Always-on nodes** (spec 04 §5.2). `network.nodes` lists the node URLs to
687
- dial, one socket per node per space. After an unexpected close the client
688
- redials without limit, waiting `min(1 s · 2ⁿ, 30 s)`, ±25%, like a relay
689
- (`backoff` in `packages/core/src/utils/backoff.ts`); a deliberate close is
690
- never redialled. The
691
- `/peer` endpoint waits 10 s for the hello (configurable).
692
-
693
- **In-process links** (spec 04 §5.4). `createLocalHub()` links every
694
- transport made from it that has connected, delivering on a later task with
695
- the bytes copied, as on a real wire. It performs no handshake. A carrier uses
696
- it to link its own copy of a space with the copy in the person's pod folder,
697
- so the usual sync keeps the two level.
698
-
699
- **The mesh** (spec 04 §7). Admission raises `peer-connected` for the room. A
700
- newly opened connection that no room takes up within 10 s is closed. A
701
- connection attempt is given 20 s, doubling with each failed attempt at the
702
- same peer up to 5 min. The node remembers the last 512 relayed signals it passed on, by their signatures.
703
- When a node that must prove read access holds no read key, the handshake
704
- throws and the room times out.
705
-
706
- **ICE servers** (spec 04 §10). The defaults are STUN only:
707
- `stun:stun.l.google.com:19302` and `stun:stun1.l.google.com:19302`.
708
- `network.iceServers` replaces them. Each new WebRTC connection uses the
709
- configured servers plus the TURN servers relays offered, the latter only while
710
- `expiresAt` is in the future. `node.iceServers()` returns the same list for
711
- the application's own connections (a call's). Before answering it refreshes:
712
- if any relay is connected and the TURN passwords held are missing or expire
713
- within 10 minutes, and it has not asked in the last 10 minutes, it asks every
714
- connected relay that can and waits up to 1.5 s for an answer (relays without
715
- TURN never answer), then returns what it has. A node with no relays returns
716
- the configured servers.
717
-
718
- _Source: `packages/core/src/network/relay-socket.ts` (`createRelaySocket`, `RelayStatus`), `packages/core/src/network/rendezvous.ts` (`createRendezvous`, `HELLO_MS`, `release`), `packages/core/src/network/relay-nostr.ts`, `packages/core/src/network/rtc-transport.ts` (`GATHER_MS`), `packages/core/src/network/ws-transport.ts`, `packages/core/src/network/local-transport.ts` (`createLocalHub`), `packages/core/src/node/carrier.ts` (`carry`), `packages/core/src/network/mesh.ts` (`CONNECT_TIMEOUT_MS`, `closeIfIdle`, `iceServers`, `ICE_REFRESH_MS`, `ICE_WAIT_MS`), `packages/core/src/network/introductions.ts` (`createSeenSignals`), `packages/core/src/network/rtc-transport.ts` (`DEFAULT_ICE_SERVERS`), `packages/core/src/node/space-keys.ts` (`nameRelays`), `packages/core/src/node/node.ts` (`iceServers`), `packages/cli/src/serve.ts` (`onPeer`). Tests: `packages/core/tests/relay-socket.test.ts`, `packages/core/tests/rendezvous.test.ts`, `packages/core/tests/relay-nostr.test.ts`, `packages/core/tests/introductions.test.ts`, `packages/core/tests/space-relays.test.ts`, `packages/core/tests/ws-transport.test.ts`, `packages/core/tests/carrier.test.ts`; the client-side ICE refresh is untested._
639
+ How this node uses relays, always-on nodes and WebRTC. Another
640
+ implementation may pick other numbers and still talk to this one
641
+ ([spec 04](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)).
642
+
643
+ ### Relays
644
+
645
+ Network settings can mix kinds of relay:
646
+
647
+ ```ts
648
+ import type { NodeNetworkConfig } from '@minca/core';
649
+
650
+ const network: NodeNetworkConfig = {
651
+ relays: ['wss://relay.minca.social', 'nostr+wss://relay.damus.io'],
652
+ };
653
+ ```
654
+
655
+ A relay of a kind the library doesn't speak is left out of
656
+ `network.status()`. On a Nostr relay, each event is signed with a throwaway
657
+ key.
658
+
659
+ When a relay drops, the node redials after 1, 2, 4, 8 and 16 seconds, then
660
+ every 30, each ±25% so peers that dropped together don't return together. It
661
+ never stops until `disconnect`. It tries at once when the page becomes
662
+ visible, when the browser reports `online`, and on `reconnect()`. A
663
+ successful open resets the count.
664
+
665
+ A socket can die without closing, as it does when the device sleeps. So the
666
+ node checks the clock every 5 seconds, and a gap over 30 seconds means it
667
+ slept: it drops the socket and dials again. A socket to a Minca relay that
668
+ has heard nothing for 30 seconds sends `ping`. Once the relay has answered
669
+ one, two unanswered pings end the socket ("The relay stopped answering.").
670
+
671
+ Each relay's state is a [`RelayStatus`](https://minca.dev/api/core/interfaces/RelayStatus/):
672
+ connecting, open, waiting to try again (with when and why), or stopped.
673
+
674
+ A socket opened only for a space's own relays closes once no space needs it.
675
+ A node that may change a space's relays (`/space/relays`), in a space that
676
+ names none, names its own relays there, up to 8.
677
+
678
+ ### Meeting peers
679
+
680
+ A node says hello in each space's room when it joins, on each relay as it
681
+ opens, and every 2 minutes.
682
+
683
+ - It says hello back at most once every 10 seconds, to everyone who said
684
+ hello meanwhile.
685
+ - It remembers, per room, the hellos it acted on from each peer in the last 2
686
+ minutes (up to 256 a peer), and failed tries for the last 512 peers.
687
+ - Each socket sends at most 20 messages a second, in bursts of 40, and queues
688
+ the rest.
689
+ - A connection attempt that times out is tried again at the peer's next
690
+ hello.
691
+ - Each WebRTC offer or answer waits up to 2 seconds for ICE gathering.
692
+
693
+ ### Connections
694
+
695
+ - A connection no room takes up within 10 seconds is closed.
696
+ - An attempt gets 20 seconds, doubling with each failure at the same peer, up
697
+ to 5 minutes.
698
+ - The node remembers the last 512 signals it relayed, by their signatures.
699
+ - A node that must prove read access but holds no read key fails the
700
+ handshake, and the room times out.
701
+
702
+ ### Always-on nodes
703
+
704
+ `network.nodes` lists nodes to dial, one socket per node per space. After an
705
+ unexpected close the node redials forever, waiting `min(1 s · 2ⁿ, 30 s)`,
706
+ ±25%, like a relay. A deliberate close is never redialled. The node's `/peer`
707
+ endpoint waits 10 seconds for the hello.
708
+
709
+ ### In-process links
710
+
711
+ `createLocalHub()` links every transport made from it, delivering bytes on a
712
+ later task, copied, as on a real wire. There is no handshake. A carrier uses
713
+ it to keep its copy of a space level with the copy in the person's pod folder.
714
+
715
+ ### ICE servers
716
+
717
+ The default ICE servers are STUN only, `stun:stun.l.google.com:19302` and
718
+ `stun:stun1.l.google.com:19302`. `network.iceServers` replaces them. Each new
719
+ WebRTC connection also uses the TURN servers relays offered, while they
720
+ haven't expired.
721
+
722
+ `node.iceServers()` returns the same list, for your own connections. If a
723
+ relay is connected and the TURN passwords are missing or expire within 10
724
+ minutes, it first asks each relay that can, at most once every 10 minutes,
725
+ and waits up to 1.5 seconds. With no relays, it returns the configured
726
+ servers.
719
727
 
720
728
  ## A node acting as an agent
721
729
 
722
- `node.asAgent({ keys, note })` returns the same node acting as an agent. It
723
- throws unless the note verifies, grants records only (its command is under
724
- `/record`), is made out to `keys`, and was issued by `node.did`. The agent:
725
-
726
- - signs with its own key, under its note, so what it writes is `recordsOnly`;
727
- - reaches only spaces its note names (`noteSpaces`: its subject, or a policy
728
- on `.space`), or every space for a note about the whole account;
729
- events for other spaces are filtered out;
730
- - refuses, locally, everything that needs a person: making, inviting, joining
731
- or leaving spaces; changing members, roles, invites or revocations; changing
732
- a space's key, relays or keepers; defining
733
- or deleting collections; live messages (`send`, which a person's devices
734
- would take as theirs); renaming or revoking at the account level; adding or
735
- removing carriers; notifications; hosting; changing, blocking, asking or
736
- accepting contacts; everything about the inbox (it has none);
737
- `delegate`; `asAgent`;
738
- - sees the contact list only if the contacts space is within its note.
739
-
740
- Closing the agent leaves the underlying node running. A node used across a
741
- port (`remoteNode`) starts no agent: the agent's keys would have to cross, so
742
- an agent is started on the node itself.
743
-
744
- An agent granted `scope: account` gets a records-only note for every space
745
- (`/record`, about the whole account) and the account key in its
746
- grant ([spec 06 §2.8](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)), so the contact list is within its note to read. A home never
747
- gives a records-only key the contact key: with it, it could open the
748
- account's knocks, in shared spaces and in its inbox ([inbox.md](inbox.md)).
749
-
750
- Which of these each method of the node is — passed through, held to the note's spaces, or refused — is one table, `API` in `packages/core/src/node/api.ts`; a new method does not type-check until it is decided there. The same table lists what `remoteNode` forwards.
751
-
752
- _Source: `packages/core/src/node/node-records.ts` (`startAgent`), `packages/core/src/node/api.ts` (`API`). Tests: `packages/core/tests/records-only.test.ts` ("an agent acting for a person"), `packages/core/tests/remote.test.ts` ("no agent is started across the port…")._
730
+ An agent writes for a person, but only records, and only where it was let in.
731
+ `node.asAgent({ keys, note })` gives you the same node acting as one:
732
+
733
+ ```ts
734
+ import type { Delegation } from '@minca/core';
735
+ declare const keys: CryptoKeyPair;
736
+ declare const note: Delegation;
737
+ // ---cut---
738
+ const agent = await node.asAgent({ keys, note });
739
+ await agent.records.put(space.id, 'app.note', { text: 'Written by the agent' });
740
+ ```
741
+
742
+ It throws unless the note verifies, grants records only (under `/record`), is
743
+ made out to `keys`, and was issued by `node.did`. The agent:
744
+
745
+ - signs with its own key under its note, so what it writes is `recordsOnly`;
746
+ - reaches only the spaces its note names, or every space for a note about
747
+ the whole account, and hears no events from others;
748
+ - sees the contact list only if its note covers the contacts space.
749
+
750
+ It refuses everything that needs a person: making, inviting, joining or
751
+ leaving spaces; changing members, roles, invites, revokes, keys, relays or
752
+ keepers; defining or deleting collections; live messages, which a person's
753
+ devices would take as theirs; renaming or revoking at the account level;
754
+ carriers, notifications and hosting; contacts and the inbox; `delegate` and
755
+ `asAgent`.
756
+
757
+ Closing the agent leaves the node running. A node used across a port
758
+ (`remoteNode`) starts no agent, since the agent's keys would have to cross.
759
+
760
+ An agent granted `scope: account` gets a records-only note for every space,
761
+ and the account key, so it can read the contact list. A home never gives a
762
+ records-only key the contact key, which would open the account's knocks
763
+ ([the inbox](inbox.md)).
764
+
765
+ One table in the library says which methods an agent passes through, limits
766
+ to its spaces or refuses, and what `remoteNode` forwards. A new method
767
+ doesn't type-check until it's listed there.
768
+ [Spec 06 §2.8](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
753
769
 
754
770
  ## The app-side client
755
771
 
756
- What an app and an account home send each other, and what each checks, is
757
- protocol ([spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). The reference app side:
758
-
759
- **The app's key.** `appKey(name = 'default')` makes the app's P-256 key once
760
- and keeps it, non-extractable, in the IndexedDB database `minca-app-key`,
761
- object store `keys`, under `name`. `forgetAppKey` deletes it; the next
762
- connection makes a new one.
763
-
764
- **An app's node outside the page.** The desktop app (`apps/desktop`) runs its
765
- app's node in a process of its own, `minca app-node`, so it keeps running with
766
- the window closed; the window uses it over a port, as a page uses its worker,
767
- carried on a WebSocket to the shell's own server at the app's origin, which
768
- opens only for the app's window, with a token made for it.
769
- That process holds the key, so the window and the menu bar are one node: two
770
- signing with one key would fork its lines, and a lock on the folder keeps a
771
- second from starting. Its key and grant can't stay in a page there, so they
772
- rest in its folder, sealed under a key the shell keeps in the system's
773
- keychain and hands to it on stdin: `key.sealed` and `grant.sealed` as
774
- `sealValue` envelopes (labels `minca/desktop-app-key/v1` and
775
- `minca/desktop-grant/v1`, each bound to `{ file }`), and the stores with their
776
- registry sealed as an account's is (spec 05 §15), one folder of stores per
777
- account: connecting as another account deletes the last one's, so its
778
- spaces never reach the new one's registry. Copied without the keychain, the
779
- folder yields no key, grant or private body, only what a carrier sees; a
780
- program running as the person can ask the keychain, as it can read a
781
- browser profile. Renewing keeps the key (a page's app asks with a new one each time, below).
782
- The key changes only when the app leaves an account: disconnecting, from the
783
- app or at the home, forgets it (`forgetAppKey` in a page), so a revoked key
784
- stays revoked. A home that answers as another account than the one connected
785
- is not used: the app leaves the last account, dropping what it wrote there
786
- that no peer had taken yet, and asks to be connected again with a new key,
787
- so one key never holds two accounts' notes. A folder that doesn't open with the keychain's
788
- key is moved aside, and the node starts again unconnected. The window is shown the grant
789
- without its account, contact or member keys. It asks the home for a 30-day
790
- note, where a page asks for the home's default.
791
-
792
- _Source: `packages/cli/src/app-node.ts` (`runAppNode`), `apps/desktop/src/bun/app-node.ts` (`createAppNode`, `keychainKey`), `apps/desktop/src/bun/node-link.ts` (`createNodeLink`), `apps/example/src/desktop.ts` (`desktopConnection`). Tests: `packages/cli/tests/app-node.test.ts`, `apps/desktop/tests/app-node.test.ts`, `apps/desktop/tests/bridge.test.ts` ("only the app’s own window gets a node token…"), `apps/desktop/tests/node-link.test.ts`._
793
-
794
- **The home's address.** `homeAddress(input)` turns what a person typed into the
795
- home's connect page:
796
-
797
- - no scheme → `https://`, or `http://` for `localhost`, `127.0.0.1`, `[::1]`;
798
- - the host must be a loopback name or a domain name with a TLD of two or more
799
- letters;
800
- - the scheme must be `https:`, or `http:` on loopback;
801
- - a path of `/` or empty becomes `/connect`; query and fragment are dropped.
802
-
803
- Example: `minca.example.com` → `https://minca.example.com/connect`.
804
-
805
- **Asking the home.** `connectToHome` (and `proposeToHome`, for a proposal)
806
- opens the home in a popup named `minca-home` with features
807
- `popup,width=460,height=720`, listens from that moment, answers a hello once its
808
- request is made and sends the request again every 500 ms, to the home's origin
809
- only, until the home answers, polls every 500 ms to see whether the person
810
- closed it, and gives up after 10 minutes by default.
811
-
812
- **Starting the node.** `startConnectedNode({ grant, key?, network?, stores?, cache? })`
813
- starts a node with:
814
-
815
- - `signer = grantSigner(grant)` ([renewing the session note](#renewing-the-session-note)):
816
- `did` = `grant.did`;
817
- - `sessionKey` = the app's key;
818
- - stores `indexedDBStores('minca-app:<grant.did>')` unless given;
819
- - `cache: {}` unless `cache: false` ([holding part of a space](#holding-part-of-a-space));
820
- - `accountKey`, `contactKey`, `contactsSpace` from the grant when present (never `contactKey` under a records-only note), and
821
- relays = the app's relays ∪ `grant.relays` (`nodeOptionsFromGrant`).
822
-
823
- It then joins each granted space it does not hold yet, passing its `memberKey`
824
- (`joinGranted`). The desktop app's node (`minca app-node`) and the agent on a
825
- computer start theirs from a grant the same way, from their own folders.
826
-
827
- **The connection.** `createMincaConnection({ home, request, network?, storage?, stores?, worker?, keys?, account? })`
828
- is the app's twin of [sign-in](sign-in.md): statuses `starting`, `disconnected`,
829
- `connecting`, `ready`, `expired`. With `worker`, it runs the node there
830
- (`startNodeInWorker`); a worker that reports a load error, or does not say the
831
- node started within 30 s (`WorkerNotStarted`), is given up on and the node
832
- runs in the page. A worker that started and refused passes its reason on.
833
- It switches to `expired` at `expiresAt` (`watchGrant`). When the node sees its
834
- own note revoked in a space it emits `revoked` ([events](#events)), and the
835
- connection forgets that account's grant and key. `propose(automations)` sends
836
- a proposal to the grant's home
837
- ([spec 06 §2.11](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
838
-
839
- **Several accounts.** The connection keeps a grant for every account the
840
- person connects, and acts for one at a time; `state.accounts` lists them
841
- (`did`, the `name` the home gave, `expiresAt`), in the order they were first
842
- connected. Each grant is made out to a key of its own, named
843
- `account-<uuid>` in `appKey`'s store (or `keys`, given), so peers never see
844
- one key act for two accounts. They are kept in `localStorage` under
845
- `minca.grants` (`[{ grant, keyName }]`), the account acted for last under
846
- `minca.account`, and the person's chosen home under `minca.home` (`home` in
847
- the config is only a default). A grant of another format (`v` other than
848
- `GRANT_VERSION`, 2) is dropped when read; one that ran out stays, and opens
849
- as `expired`.
850
-
851
- - `start()` acts for the account `account(accounts)` names, else the one used
772
+ An app connects to an account home with `createMincaConnection`
773
+ ([building an app](building-an-app.md)). These are the pieces underneath.
774
+ [Spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)
775
+ says what the app and the home send each other.
776
+
777
+ ### The app's key
778
+
779
+ `appKey(name = 'default')` makes the app's P-256 key once and keeps it,
780
+ non-extractable, in the IndexedDB database `minca-app-key`, store `keys`,
781
+ under `name`. `forgetAppKey` deletes it, and the next connection makes a new
782
+ one.
783
+
784
+ ### An app's node outside the page
785
+
786
+ The desktop app runs its app's node in a process of its own,
787
+ `minca app-node`, so it keeps running with the window closed. The window
788
+ talks to it over a WebSocket to the shell's server, which opens only for the
789
+ app's window, with a token made for it. One process holds the key, so the
790
+ window and the menu bar share one node. A lock on the folder stops a second
791
+ one, since two nodes signing with one key would fork its lines.
792
+
793
+ Its key and grant rest in its folder as `key.sealed` and `grant.sealed`
794
+ (labels `minca/desktop-app-key/v1` and `minca/desktop-grant/v1`, bound to
795
+ `{ file }`), sealed under a key the shell keeps in the system keychain. Its
796
+ registry is sealed as an account's is. Copied without the keychain, the
797
+ folder gives up no key, grant or private body. A program running as the
798
+ person can still ask the keychain, as it could read a browser profile. A
799
+ folder that doesn't open with the keychain's key is moved aside, and the node
800
+ starts again unconnected.
801
+
802
+ - There's one folder of stores per account. Connecting as another account
803
+ deletes the last one's.
804
+ - Renewing keeps the key. Disconnecting, from the app or the home, forgets it,
805
+ so a revoked key stays revoked.
806
+ - If the home answers as a different account, the app leaves the last one,
807
+ dropping what no peer had taken yet, and asks again with a new key. One key
808
+ never holds two accounts' notes.
809
+ - The window sees the grant without its account, contact or member keys.
810
+ - It asks the home for a 30-day note, where a page asks for the home's
811
+ default.
812
+
813
+ ### The home's address
814
+
815
+ `homeAddress(input)` turns what a person typed into the home's connect page:
816
+
817
+ ```ts
818
+ import { homeAddress } from '@minca/core/session';
819
+
820
+ homeAddress('minca.example.com'); // 'https://minca.example.com/connect'
821
+ ```
822
+
823
+ - With no scheme it adds `https://`, or `http://` for `localhost`,
824
+ `127.0.0.1` and `[::1]`.
825
+ - The host must be a loopback name, or a domain with a TLD of two letters or
826
+ more.
827
+ - The scheme must be `https:`, or `http:` on loopback.
828
+ - An empty path or `/` becomes `/connect`. Query and fragment are dropped.
829
+
830
+ ### Asking the home
831
+
832
+ `connectToHome`, and `proposeToHome` for a proposal, open the home in a popup
833
+ named `minca-home` (`popup,width=460,height=720`). They send the request to
834
+ the home's origin only, every 500 ms, until the home answers. They check every
835
+ 500 ms whether the person closed the popup, and give up after 10 minutes by
836
+ default.
837
+
838
+ ### Starting the node
839
+
840
+ [`startConnectedNode`](https://minca.dev/api/session/functions/startConnectedNode/) starts a
841
+ node with:
842
+
843
+ - `signer`: `grantSigner(grant)`, so `did` is `grant.did`;
844
+ - `sessionKey`: the app's key;
845
+ - stores: `indexedDBStores('minca-app:<grant.did>')` unless given;
846
+ - `cache: {}` unless `cache: false`;
847
+ - `accountKey`, `contactKey` and `contactsSpace` from the grant when there,
848
+ never `contactKey` under a records-only note;
849
+ - relays: the app's plus `grant.relays`.
850
+
851
+ It then joins each granted space it doesn't hold yet, with its `memberKey`.
852
+ The desktop app's node and the agent on a computer start the same way, from
853
+ their own folders.
854
+
855
+ ### The connection
856
+
857
+ `createMincaConnection(config)` is the app's version of [sign-in](sign-in.md).
858
+ It takes a [`MincaConnectionConfig`](https://minca.dev/api/session/interfaces/MincaConnectionConfig/),
859
+ and its status is a [`ConnectionStatus`](https://minca.dev/api/session/type-aliases/ConnectionStatus/).
860
+
861
+ - With `worker`, the node runs in a worker. If the worker fails to load or
862
+ doesn't start the node within 30 seconds (`WorkerNotStarted`), the node runs
863
+ in the page instead. A worker that started and refused passes its reason on.
864
+ - It turns `expired` when the grant's `expiresAt` passes.
865
+ - When the node sees its note revoked (`revoked`), the connection forgets that
866
+ account's grant and key.
867
+ - `propose(automations)` sends a proposal to the grant's home.
868
+
869
+ ### Several accounts
870
+
871
+ A person can connect more than one account. The connection keeps a grant for
872
+ each and acts for one at a time. `state.accounts` lists them as
873
+ [`ConnectedAccount`](https://minca.dev/api/session/interfaces/ConnectedAccount/)s, in the order
874
+ first connected.
875
+
876
+ - `start()` acts for the account `account(accounts)` picks, else the one used
852
877
  last, else the first.
853
- - `use(did)` acts for another connected account. Its grant is here, so the
854
- home is not asked; the node acting for the last one closes, and one for
855
- this one starts, with its own stores.
856
- - `connect(home?)` asks with a new key, and acts for whichever account the
857
- person chooses at the home: a new one, or one connected already, whose grant
858
- it renews. A key that asked once may hold a note from whatever account the
859
- home was signed in as, so no key is asked with twice. An account connected
860
- again gets the new key and the app forgets the old one; the home revokes
861
- nothing, and what the old key wrote stands
862
- ([spec 06 §2.10](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
863
- While it waits, an app acting for an account stays `ready`; a grant whose
864
- node won't start is kept, and the connection says `disconnected` with why.
865
- - `disconnect(did?)` forgets an account's grant and key (default the one
866
- acted for) and acts for the next connected account, or none. Disconnected
867
- at the home instead, it acts for none, with `error` saying why, rather than
868
- another account the person didn't choose.
869
-
870
- Another tab's changes reach `state.accounts` by `storage` events; each tab
871
- acts for its own account. A tab whose account another tab connected again
872
- goes on with its key until it starts again, then takes the newer grant; one
873
- whose key is revoked takes up a newer grant rather than forgetting it. A
874
- shared worker runs a node per key, not only per account, so tabs on two keys
875
- never share one. Switching again before a node has started closes it.
876
-
877
- **Showing notifications.** The app shows its own notifications.
878
- `watchNotifications(node, { origin?, onNotify })` needs the account key (an
879
- app with `scope: account`): it reads the account's own automations naming the
880
- app's origin from the registry and hands the app each record that arrives
881
- matching one, as `{ automation, record }`, with the body in hand
882
- (`matchesRecord`): not paused, the collection, one of the spaces, created at
883
- or after `since` and within the last 24 hours, by another account when
884
- `others`, and for which its `where` holds, with `$me` the account. What the
885
- node held before it started is never news, and neither is what a collection
886
- held the first time an automation made it look there; anything arriving after that
887
- is, even while the account or the list of spaces changes. How the app shows a match is its own
888
- to decide; a "Notify me" button is where a proposal usually starts.
889
-
890
- _Source: `packages/core/src/session/connect.ts` (`appKey`, `forgetAppKey`, `homeAddress`, `connectToHome`, `proposeToHome`, `startConnectedNode`, `nodeOptionsFromGrant`, `joinGranted`, `grantSigner`, `usableGrant`, `watchGrant`, `grantStore`), `packages/cli/src/app-node.ts` (`startDesktopNode`), `packages/core/src/session/connection.ts`, `packages/core/src/node/watch-notifications.ts`, `packages/core/src/space/own-automations.ts` (`matchesRecord`). Tests: `packages/core/tests/connect.test.ts` ("an account home typed by a person", "watching a grant", "an app connected to several accounts", "an app showing its own notifications"), `packages/core/tests/topics.test.ts` ("an automation of the account’s own: its where"), `packages/core/tests/watch-notifications.test.ts`._
878
+ - `use(did)` switches to another connected account without asking the home.
879
+ The old node closes, and one for this account starts, with its own stores.
880
+ - `connect(home?)` asks with a new key, for whichever account the person
881
+ picks at the home: a new one, or one already connected, whose grant it
882
+ renews. No key is ever used to ask twice, since a key that asked once may
883
+ hold a note from any account the home was signed in as. The renewed account
884
+ gets the new key and the old one is forgotten. The home revokes nothing, and
885
+ what the old key wrote stands.
886
+ - While `connect` waits, an app acting for an account stays `ready`. A grant
887
+ whose node won't start is kept, and the status is `disconnected` with why.
888
+ - `disconnect(did?)` forgets an account's grant and key, by default the
889
+ current one, and acts for the next account, or none. Disconnected at the
890
+ home instead, it acts for none, with `error` saying why.
891
+
892
+ Each grant is made out to a key of its own, `account-<uuid>` in `appKey`'s
893
+ store (or `keys`), so peers never see one key act for two accounts. Grants
894
+ live in `localStorage` under `minca.grants` (`[{ grant, keyName }]`), the
895
+ current account under `minca.account`, and the chosen home under `minca.home`
896
+ (the config's `home` is only a default). A grant whose `v` isn't
897
+ `GRANT_VERSION` (2) is dropped. An expired one stays, and opens as `expired`.
898
+
899
+ Each tab acts for its own account, and sees other tabs' changes to
900
+ `state.accounts`. A tab whose account was connected again elsewhere keeps
901
+ its key until it restarts, then takes the newer grant. One whose key was
902
+ revoked takes up a newer grant rather than forgetting it. A shared worker
903
+ runs a node per key. Switching again before a node has started closes it.
904
+ [Spec 06 §2.10](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
905
+
906
+ ### Showing notifications
907
+
908
+ An app shows its own notifications with
909
+ `watchNotifications(node, { origin?, onNotify })`. It needs the account key,
910
+ so an app with `scope: account`. It reads the account's automations for the
911
+ app's origin, and calls `onNotify({ automation, record })` for each record
912
+ that arrives matching one.
913
+
914
+ A record matches when the automation isn't paused, and the record is in its
915
+ collection and one of its spaces, created after `since` and within the last
916
+ 24 hours, by another account when `others` is set, and its `where` holds,
917
+ with `$me` the account. What the node held before it started is never news,
918
+ and nor is what a collection held when an automation first looked there.
919
+
920
+ How to show a match is up to the app. A "Notify me" button is usually where a
921
+ proposal starts.
922
+
923
+ For a list of what happened, pass `onActivity` too. After each change it gets
924
+ what the automations match now, newest first, up to 50, each record once under
925
+ the automation that asks about it most particularly. A match is dated by what
926
+ set it off, and listed if it would have notified when that was written, so
927
+ the 24 hours don't apply. It comes from the records, so it holds what arrived
928
+ while the app was closed, and devices holding the same records list the same.
929
+ Like notifications, it looks at the newest 50 records of a collection, by the
930
+ time their writers gave them, so an older match drops out under newer ones. A
931
+ match dated more than five minutes ahead waits for its time.
932
+
933
+ ```js
934
+ watchNotifications(node, {
935
+ onNotify: ({ automation, record }) => showPopup(automation, record),
936
+ onActivity: (matches) => setActivity(matches),
937
+ });
938
+ ```
939
+
940
+ What the person has read of it is the app's to keep: a time in the account
941
+ registry, say, and what is newer counts as new. A record that arrives late,
942
+ dated before that time, then isn't new, though it still notifies within its
943
+ 24 hours.
891
944
 
892
945
  ## Carriers, hosting and notifications
893
946
 
894
- What goes into a carry space, what a carrier checks and the host's HTTP API
895
- are protocol ([spec 06 §4](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). The reference node's side:
896
-
897
- **Carriers.** `node.carriers.add({ did, name })` (needs the account key)
898
- derives the carry space, writes the `sys.carrier` record (name trimmed to 80,
899
- default `Carrier`), fills the carry space, and returns `{ space, invite }` for
900
- the carrier to join with; for a carrier it already has, by `did`, it returns
901
- that one's. Carry spaces are never kept in the node's own list: each is
902
- derived again from its record. A node that starts, or hears the registry change,
903
- refills every carrier's carry space in the background: it opens every space
904
- the account holds, which from a data folder is slow, and signing in doesn't
905
- wait for it. Adding an automation doesn't either (adding a carrier writes that
906
- carrier's passes before it returns):
907
- `node.carriers.settled(waitMs)` waits up to `waitMs` for the refill under way
908
- and says whether it finished, for a window about to close. `node.carriers.reached(carrySpace, waitMs)`
909
- waits up to `waitMs` for the node to be level with the carrier in the carry
910
- space and then the account registry, and says whether it was: a node about to
911
- close (the home's window, once it has answered) waits on it, so what it wrote
912
- for the carrier is not left with nobody (spec 06 §4.3). `node.carriers.remove(carrySpace)`
913
- writes `carry:closed` and marks the record removed; the node keeps the carry
914
- space open until it closes, so the carrier hears it.
915
-
916
- **A space made just now.** Until a carrier opens it from its pass and syncs
917
- it, a new space is only on the device that made it: an invite handed out and
918
- the device closed can't be used. `node.spaces.carried(spaceId, { waitMs? })`
919
- is a short loading step: when a carrier of the account is connected now, it
920
- names it a keeper, writes its pass at once, and waits up to `waitMs`
921
- (default 3 s) until it is level with this node in the space, so it holds the
922
- genesis and any invite opened before the call. It says whether it was: false
923
- at once when no carrier is connected. `contacts.ask` and `inbox.knock` wait on it before the knock goes
924
- out, and pass what it said on as `carried`, for the app to tell the person.
925
-
926
- `node.spaces.reached(spaceId, peer, waitMs)` is the same wait for one peer
927
- named by its key, such as an app's key from the request it connected with:
928
- true once that peer holds all this node does of the space, false when
929
- `waitMs` (at most a minute) passed first or the peer never came. For a node about to close,
930
- like a connect page waiting for the app to have what it wrote.
931
-
932
- _Source: `packages/core/src/node/node.ts` (`spaces.carried`, `spaces.reached`), `packages/core/src/node/node-contacts.ts` (`makePair`). Tests: `packages/core/tests/carrier.test.ts` ("a space made just now, carried before its invite goes out…", "carried is false at once with no carrier…"), `packages/core/tests/usernames.test.ts` ("spaces.reached is true once a peer holds the space…")._
933
-
934
- **The account's own automations.** `node.automations` (needs the account
935
- key) lists, adds, updates (`name`, `paused`) and removes the account's own
936
- automations, kept in its registry ([automations](automations.md#the-accounts-own)),
937
- and copies a wake for each into every carry space. The reference home adds
938
- them when a person keeps an app's proposal, and lists them by app for the
939
- person to pause or remove ([sign-in](sign-in.md#the-account-homes-side)).
940
-
941
- **A carrier's matches.** `CarrierNode` reports a version that wakes one of
942
- the account's wakes through a `wake` event, with only the wake, the space and
943
- the record's key, collection and `createdAt`; `wakes()` lists the wakes it
944
- holds. The desktop app shows them as notifications (`apps/desktop/src/bun/notify.ts`); the browser extension shows none yet.
945
-
946
- **Hosting.** `node.hosting`:
947
-
948
- | Call | Does |
949
- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
950
- | `use(url)` | Reads the host's description, makes the subscription key and writes the `sys.hosting` record. |
951
- | `list()` | Asks each host for its status and hands over the carry space when paid and not carrying, making the carrier first if needed (named after the host's address). At most once a minute per host; a second look waits for a handover in flight. |
952
- | `pay(url, { amount, method, monthly? })` | Adds to the account's balance at the host (dollars, by `checkout` or `request`, monthly by card, as its `HostingView.fund` says): a pay answer, `checkout` (a page to open in a new tab with no opener) or `request` (a payment for a wallet, shown by the app). Call `list()` until the balance moves. |
953
- | `remind(url, email)` | Asks the host to email a reminder before paid time runs out; it mails a link to confirm first. |
954
- | `stop(url)` | Sends `DELETE …/carry` (ignoring failure), removes the carrier and deletes the `sys.hosting` record. |
955
- | `space(id)` | The hosts a space names in `std.host`, each asked how the space's own subscription stands, with how its fund is paid into (below). |
956
- | `over(id)` | The account's hosts whose last status says the space is over their free line, each `{ url, name, over }` (`over.until`, `over.reasons`), from the receipts in `sys.hosting`: asks no host. An agent may call it for a space it was given. |
957
- | `payForSpace(id, url, { amount, method, monthly? })`, `remindForSpace(id, url, email)` | Adds to a space's fund at a host it names (dollars, by `checkout` or `request`, monthly by card), and asks for reminders before it runs out. Anyone in it may. `space(id)` gives each host's `fund` offer, and in its status the `balance`, `daily` spend and `bots`. |
958
- | `startBot(id, url, { name, role? })` | Asks a host the space names to run a bot there ([spec 08 §3](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)): makes an invite for `role` (by default as `spaces.invite` picks one) and hands it over. The host holds the bot's keys, so an app says so first. |
959
- | `stopForSpace(id, url)` | Stops a space using a host it names: deletes its `std.host` record, removes the host's bots and changes the key (below). |
960
-
961
- Every device runs `list()` after each reconciliation ([following the account](#following-the-account)).
962
- A device reaches a host at the socket its description names (`peer`,
963
- [spec 08 §1](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)): every
964
- open space holds one to each host in `sys.hosting`, and to each host the space
965
- names in `std.host`, and follows as those change. `network.hosts` names hosts
966
- to look for the account registry at before the account says which it uses, so
967
- an app built with a default host restores an account from its recovery code
968
- alone. `network.nodes` still adds sockets of its own, to every space.
969
-
970
- `network.reach` says where a node may connect, asked of every address it
971
- found rather than was given: a host or node a record or an invite names, a
972
- relay a space or an invite names, a place a short link names, a host it asks
973
- to describe itself. Its own `relays`, `nodes` and `hosts` are taken as given;
974
- without `reach`, anywhere. Refused, a host is not asked (`hosting` calls fail),
975
- a node or relay not dialled, a short link's place not asked. It is for a node
976
- a server runs for someone else, such as the MCP service's for chat apps: what
977
- that node reads, and the invites it is handed, are the other's to write, and
978
- must not make the server connect inside its own network.
979
-
980
- A device waits 15 seconds for a host to answer any call, and a minute for
981
- `startBot`. A host that gives no answer, or none in time, is a `HostError`
982
- with status 0 whose message names the address (`describeHost(url, timeoutMs?)`
983
- takes another limit). `list()` and `space(id)` do not throw it: they return
984
- that host's view with `error` set, so one host that is down does not hide the
985
- others, and an app can say so and offer to ask again or to stop using it.
986
-
987
- The reference host (`minca host`, `packages/cli/src/host.ts`) keeps a lapsed
988
- subscription for `graceDays` (default 30) after `paidUntil`, and drops lapsed
989
- ones in a sweep every hour (`sweepMs`). It measures each carried space's
990
- folder at most every ten minutes, and each status gives the sum as `bytes`,
991
- with `quotaBytes` as `quota` (`MINCA_HOST_QUOTA_GB`, none unless set, at a
992
- host without limits). At its quota, an account's carry space takes no new space
993
- (`full`, in `createCarryCore`): what it carries stays and keeps syncing, and a
994
- space that waited is taken once a later measure finds room. All of this is the
995
- host's own policy.
996
-
997
- With `limits` ([spec 08 §1.1](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md),
998
- `MINCA_HOST_FREE_GB`), an account's subscription is active with nothing paid,
999
- its `plan` `free` until it pays, and its quota by plan; a device hands such a
1000
- host its carry space as it would a free one. A space its own fund pays for
1001
- takes none of its members' room. The host counts each carried space's writers
1002
- as versions arrive (`onArrived`, in `createCarryCore`) and its readers as
1003
- sockets prove themselves (`onPeer`, `packages/cli/src/serve.ts`), and once an
1004
- hour (`evaluate`) holds each to the free line. Past a space's `until`, every
1005
- account's carry space stops carrying it (`skip`, in `createCarryCore`), while
1006
- its own subscription still may. Each change is a line in the host's log.
1007
-
1008
- _Source: `packages/core/src/node/node-carriers.ts` (`carriers`, `fetchInvite`), `packages/core/src/node/node-hosting.ts` (`hosting`, `describeAt`), `packages/core/src/node/space-peers.ts` (`useNodes`, `meshFor`), `packages/core/src/node/carrier.ts` (`arrived`, `skip`, `onArrived`), `packages/core/src/node/host.ts` (`evaluate`), `packages/core/src/session/hosting.ts`, `packages/cli/src/host.ts`. Tests: `packages/core/tests/carrier.test.ts`, `packages/core/tests/host-limits.test.ts`, `packages/core/tests/reach.test.ts`, `packages/cli/tests/host.test.ts`, `packages/cli/tests/remote-mcp-server.test.ts`, `packages/cli/tests/remote-mcp-offline.test.ts`._
947
+ A carrier is an always-on node that keeps the account's spaces online while
948
+ its devices are off. A host runs carriers for you, for a fee or for free.
949
+ [Spec 06 §4](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)
950
+ and [spec 08](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)
951
+ cover what goes over the wire.
952
+
953
+ ### Carriers
954
+
955
+ `node.carriers.add({ did, name })` needs the account key. It derives the
956
+ carry space, writes the `sys.carrier` record, fills the carry space, and
957
+ returns `{ space, invite }` for the carrier to join with. The name is trimmed
958
+ to 80 characters, `Carrier` by default. Adding a carrier it already has
959
+ returns that one.
960
+
961
+ Carry spaces aren't kept in the node's list. Each is derived again from its
962
+ record. When the node starts, or the registry changes, it refills every carry
963
+ space in the background. That opens every space the account holds, which is
964
+ slow from a data folder, so signing in doesn't wait for it, and nor does
965
+ adding an automation. Adding a carrier writes its passes before it returns.
966
+
967
+ - `carriers.settled(waitMs)` waits for the refill under way, and says whether
968
+ it finished. Use it before a window closes.
969
+ - `carriers.reached(carrySpace, waitMs)` waits until the node is level with
970
+ the carrier in the carry space and the account registry. A node about to
971
+ close waits on it, so what it wrote for the carrier isn't lost.
972
+ - `carriers.remove(carrySpace)` writes `carry:closed` and marks the record
973
+ removed. The carry space stays open until the node closes, so the carrier
974
+ hears it.
975
+
976
+ ### A space made just now
977
+
978
+ A new space lives only on the device that made it until a carrier syncs it.
979
+ An invite handed out before then, with the device closed, can't be used.
980
+
981
+ `node.spaces.carried(spaceId, { waitMs? })` is a short loading step for that.
982
+ If a carrier of the account is connected, it names it a keeper, writes its
983
+ pass, and waits up to `waitMs` (default 3 seconds) for it to be level. It
984
+ says whether it was, and is `false` at once with no carrier connected.
985
+ `contacts.ask` and `inbox.knock` wait on it, and return what it said as
986
+ `carried`, so the app can tell the person.
987
+
988
+ `node.spaces.reached(spaceId, peer, waitMs)` waits the same way for one peer,
989
+ named by its key, such as an app's key. It is `true` once that peer holds
990
+ everything this node does, and `false` when `waitMs` (at most a minute)
991
+ passed first. A connect page uses it to wait for the app to have what it
992
+ wrote.
993
+
994
+ ### The account's own automations
995
+
996
+ `node.automations` needs the account key. It lists, adds, updates (`name`,
997
+ `paused`) and removes the account's own
998
+ [automations](automations.md#the-accounts-own), kept in its registry, and
999
+ copies a wake for each into every carry space. The reference home adds them
1000
+ when a person keeps an app's proposal, and lists them by app to pause or
1001
+ remove ([the account home's side](sign-in.md#the-account-homes-side)).
1002
+
1003
+ ### A carrier's matches
1004
+
1005
+ When a version wakes one of the account's wakes, a `CarrierNode` sends a
1006
+ `wake` event with only the wake, the space, and the record's key, collection
1007
+ and `createdAt`. `wakes()` lists the wakes it holds. The desktop app shows
1008
+ these as notifications. The browser
1009
+ extension doesn't yet.
1010
+
1011
+ ### Hosting
1012
+
1013
+ `node.hosting` pays a host and hands it the account's spaces. Its calls are
1014
+ on [`NodeHosting`](https://minca.dev/api/core/interfaces/NodeHosting/): start and stop using a
1015
+ host, pay into the account's balance or a space's own fund, ask for reminders,
1016
+ see how each host stands, and start a bot.
1017
+
1018
+ A few details:
1019
+
1020
+ - `list()` makes the carrier first if needed, named after the host's address.
1021
+ A second call waits for a handover already in flight. Every device runs it
1022
+ after each [reconcile](#following-the-account).
1023
+ - `pay` and `payForSpace` take `method` `checkout` or `request`, and
1024
+ `monthly` by card, as the host's `HostingView.fund` offers. They answer
1025
+ with `checkout`, a page to open in a new tab with no opener, or `request`,
1026
+ a payment for a wallet that the app shows. Call `list()` until the balance
1027
+ moves.
1028
+ - `remind` mails a link to confirm first.
1029
+ - `stop` sends `DELETE …/carry`, ignoring failure, removes the carrier and
1030
+ deletes the `sys.hosting` record.
1031
+ - `over(id)` returns `{ url, name, over }` with `over.until` and
1032
+ `over.reasons`, read from the receipts in `sys.hosting`. It asks no host.
1033
+ An agent may call it for a space it was given.
1034
+ - `startBot` makes an invite for `role` (by default as `spaces.invite` picks)
1035
+ and hands it over. The host holds the bot's keys, so tell the person first.
1036
+ [Spec 08 §3](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md).
1037
+
1038
+ ### Reaching hosts
1039
+
1040
+ A device reaches a host at the socket its description names (`peer`). Every
1041
+ open space holds a socket to each host in `sys.hosting`, and to each host the
1042
+ space names in `std.host`, and follows as those change. `network.nodes` adds
1043
+ sockets of its own, to every space.
1044
+
1045
+ `network.hosts` names hosts to look for the account registry at, before the
1046
+ account says which it uses. An app with a default host can then restore an
1047
+ account from its recovery code alone.
1048
+
1049
+ `network.reach(address)` decides whether the node may connect to an address
1050
+ it found rather than was given: a host or node a record or invite names, a
1051
+ relay a space or invite names, a short link's place, a host it asks to
1052
+ describe itself. Its own `relays`, `nodes` and `hosts` are always allowed,
1053
+ and without `reach`, so is everything. A refused host isn't asked, so
1054
+ `hosting` calls fail. A refused node or relay isn't dialled. Use it for a node
1055
+ a server runs for someone else, such as the MCP service's: what that node
1056
+ reads isn't the server's to trust, and must not make it connect inside its
1057
+ own network.
1058
+
1059
+ A device waits 15 seconds for a host to answer, and a minute for `startBot`.
1060
+ No answer in time is a `HostError` with status 0, whose message names the
1061
+ address. `describeHost(url, timeoutMs?)` takes another limit. `list()` and
1062
+ `space(id)` don't throw it. They return that host's view with `error` set,
1063
+ so one host that is down doesn't hide the others.
1064
+
1065
+ ### The reference host
1066
+
1067
+ `minca host` makes these choices of its own:
1068
+
1069
+ - A lapsed subscription is kept for `graceDays` (default 30) after
1070
+ `paidUntil`, and swept out hourly (`sweepMs`).
1071
+ - It measures each carried space's folder at most every ten minutes. Each
1072
+ status gives the total as `bytes`, and `quota` from `MINCA_HOST_QUOTA_GB`
1073
+ (none unless set).
1074
+ - At its quota, an account's carry space takes no new space (`full`). What it
1075
+ carries stays and keeps syncing, and a space that waited is taken once
1076
+ there's room.
1077
+
1078
+ With `limits` (`MINCA_HOST_FREE_GB`), a subscription is active with nothing
1079
+ paid, on the `free` plan until it pays, with its quota by plan. A device
1080
+ hands such a host its carry space as it would a free one. A space paid for by
1081
+ its own fund takes none of its members' room. The host counts each space's
1082
+ writers as versions arrive (`onArrived`) and its readers as sockets prove
1083
+ themselves (`onPeer`), and once an hour (`evaluate`) holds each space to the
1084
+ free line. Past a space's `until`, every account's carry space stops carrying
1085
+ it (`skip`), while the space's own subscription still may. Each change is a
1086
+ line in the host's log.
1087
+ [Spec 08 §1.1](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md).
1009
1088
 
1010
1089
  ### A space paying for itself
1011
1090
 
1012
- A space names the hosts it pays in `std.host` records ([standard library](standard-library.md)),
1013
- which only members granted it may write: the `community` template leaves
1014
- `std.host` to admins and moderators (`STAFF_COLLECTIONS`). The host keeps the
1015
- space for the space itself: its own subscription, `space:<id>`, with a fund
1016
- anyone adds to, which pays for keeping it online and for its bots
1017
- ([spec 08 §2](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)).
1018
-
1019
- Every device holding the space's key (not one whose note lacks
1020
- `/account/write`, such as an agent's, nor a carrier) looks at the hosts its space names when it takes a role there and
1021
- on changes after that: at once when the list of hosts changed, else at most
1022
- every ten minutes. For each, it reads the description, refuses a host whose
1023
- key is not the one the record names, asks for the status, and hands over the
1024
- space's pass when the host is paid (or free and not lapsed) and either does
1025
- not carry the space or carries it with an older read key. It looks only where
1026
- the space defines `std.host`, so a space held in part is not made to hold it.
1027
-
1028
- `node.hosting.space(id)` does the same at once and returns each host's view:
1029
- its name, key, status (with the fund's `balance`, its `daily` spend, and
1030
- the `bots` running), whether it is `free`, and `fund`, how money goes in,
1031
- which an app shows anyone who wants to chip in, paying with `payForSpace`.
1032
- A host with neither `free` nor a `fund` takes no communities. A host that
1033
- could not be asked has `error` and no status. An agent may call `space` for
1034
- a space it was given; paying is a person's.
1035
-
1036
- `node.hosting.stopForSpace(id, url)` stops a space using a host it names, with
1037
- what the space can do by itself. It asks the host which bots it runs there,
1038
- then deletes the `std.host` record first, so no device hands the host what
1039
- follows, removes those bots from the space, and gives a private space a new
1040
- key when the host was handed it (or can't be asked). Removing a bot changes
1041
- the key by itself; with none removed, `changeKey` is called. It answers
1042
- `{ bots, newKey }`. A bot is removed only where the account may invoke
1043
- `/member/remove` on it, and the key changed only with `/key/change`: without
1044
- either, only the record goes, and the answer is `{ bots: [], newKey: false }`. A host named and never
1045
- handed the space costs no key change. No call asks the host to drop what it
1046
- has, so it keeps that, unreadable, for as long as the space's subscription is
1047
- paid, and what is in the fund stays there
1091
+ A community can pay for its own hosting. It names its hosts in `std.host`
1092
+ records ([standard library](standard-library.md)), which only members granted
1093
+ it may write. The `community` template leaves `std.host` to admins and
1094
+ moderators (`STAFF_COLLECTIONS`). The host then keeps the space under a
1095
+ subscription of its own, `space:<id>`, with a fund anyone can add to. The
1096
+ fund pays for keeping it online and for its bots.
1097
+
1098
+ Every device holding the space's key looks at the hosts the space names: when
1099
+ it takes a role there, at once when the hosts change, and otherwise at most
1100
+ every ten minutes. Agents and carriers don't. For each host it reads the
1101
+ description, refuses one whose key isn't the one the record names, asks for
1102
+ the status, and hands over the space's pass when the host is paid (or free
1103
+ and not lapsed) and doesn't carry the space yet, or carries it with an older
1104
+ read key. It looks only where the space defines `std.host`, so a space held
1105
+ in part isn't made to hold it.
1106
+
1107
+ `node.hosting.space(id)` does the same at once, and returns each host's view:
1108
+ its name, key, status (the fund's `balance`, its `daily` spend and the `bots`
1109
+ running), whether it is `free`, and `fund`, how money goes in. Show `fund` to
1110
+ anyone who wants to chip in, and pay with `payForSpace`. A host with neither
1111
+ `free` nor `fund` takes no communities. A host that couldn't be asked has
1112
+ `error` and no status. An agent may call `space` for a space it was given,
1113
+ but paying is a person's.
1114
+
1115
+ `node.hosting.stopForSpace(id, url)` stops a space using a host. It asks the
1116
+ host which bots it runs there, deletes the `std.host` record first so no
1117
+ device hands the host anything new, removes those bots, and gives a private
1118
+ space a new key if the host had it, or can't be asked. Removing a bot
1119
+ changes the key by itself. With no bot removed, it calls `changeKey`. It
1120
+ answers `{ bots, newKey }`.
1121
+
1122
+ It removes a bot only where the account may run `/member/remove` on it, and
1123
+ changes the key only with `/key/change`. Without either, only the record
1124
+ goes, and the answer is `{ bots: [], newKey: false }`. A host that was named
1125
+ but never handed the space costs no key change.
1126
+
1127
+ No call asks the host to drop what it has. It keeps the space, unreadable,
1128
+ for as long as the space's subscription is paid, and the fund keeps its money
1048
1129
  ([#220](https://github.com/leifriksheim/minca/issues/220)).
1049
1130
 
1050
- _Source: `packages/core/src/node/node-hosting.ts` (`keepSpaceHosts`, `askSpaceHost`, `hosting.space`), `packages/core/src/session/hosting.ts` (`describeHost`, `HostError`). Tests: `packages/cli/tests/host.test.ts` ("a space paying for itself", "an address that is not a host, or one that is down", "bots a host runs": the two on stopping a space's host)._
1051
-
1052
1131
  ## The inbox
1053
1132
 
1054
- `node.inbox` ([inbox.md](inbox.md), [spec 07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md)):
1055
-
1056
- | Call | Does |
1057
- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1058
- | `get()` | Your inbox, or null until opened: `{ gen, name?, key, sign, places, code, username?, usernameUntil?, updatedAt }`. `code` is signed afresh each time; what it says stays the same |
1059
- | `open({ places?, name? })` | Opens your inbox, or changes where its knocks wait and the name it gives. Places default to the current ones, else this node's relays (up to 3); name to the current one, else the account's |
1060
- | `rotate()` | Clears the inbox and replaces it with `gen + 1`: the old code leads nowhere |
1061
- | `clear()` | Purges every knock waiting, from every mailbox it names |
1062
- | `claim(username)` | Claims a username for your inbox on its domain's name service ([usernames.md](usernames.md)), opening the inbox if need be; one at a time. It follows the inbox: `rotate` and `open` point it at the new code, and `knocks` renews it a month before it lapses |
1063
- | `release()` | Gives the username up: it leads nowhere |
1064
- | `knock(code, { note? })` | by a code, a link or a username: [the exchange](inbox.md#the-exchange), returns `{ space, carried }` |
1065
- | `knocks()` | Fetches the inbox's topic from every mailbox it names, opens and checks ([spec 07 §6](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md); opened results are cached by id), settles sent knocks; returns `{ id, from, name, note?, pairSpace, at }`, newest first |
1066
- | `sent()` | Your knocks nobody has joined yet: `{ space, name, username?, at }` |
1067
- | `accept(id)` | [the exchange](inbox.md#the-exchange), returns the new `ContactView` |
1068
- | `dismiss(id)` | Purges one knock |
1133
+ The inbox is where strangers knock to start a conversation, using a code, a
1134
+ link or a username. `node.inbox` needs the contact key
1135
+ ([inbox](inbox.md), [spec 07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md)).
1136
+
1137
+ Its calls are on [`NodeInbox`](https://minca.dev/api/core/interfaces/NodeInbox/): open,
1138
+ rotate and clear the inbox, claim a username, knock, and list, accept or
1139
+ dismiss the knocks that arrive. `get()` returns an
1140
+ [`InboxView`](https://minca.dev/api/core/interfaces/InboxView/), with the code to hand out.
1141
+
1142
+ A username follows the inbox. `rotate` and `open` point it at the new code,
1143
+ and `knocks` renews it a month before it lapses. You hold one at a time.
1144
+
1145
+ `knocks()` fetches the inbox from every mailbox it names, opens and checks
1146
+ each knock (caching the results by id), and settles knocks you sent. Each is
1147
+ a [`KnockView`](https://minca.dev/api/core/interfaces/KnockView/). Knocking and accepting both follow
1148
+ [the exchange](inbox.md#the-exchange), and need whole-account access.
1149
+ [Spec 07 §6](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md).
1069
1150
 
1070
1151
  ## Client conveniences
1071
1152
 
1072
- These are not protocol; another client may draw sign-in and [calls](../../calls/README.md) however it
1073
- likes.
1074
-
1075
- - **`<minca-auth>`** draws the flow of [sign-in](sign-in.md) into its own light DOM (so password
1076
- managers find its forms). Attributes: `app-name`, `relays` and `nodes`
1077
- (comma-separated). It fires `minca-session` (`detail: { session }`, `null` when
1078
- signed out), bubbling and composed. A page can hand it its own flow with
1079
- `element.auth = createMincaAuth(…)`. It sizes to its container, so it fits a
1080
- page, a modal or a side panel, and draws nothing once someone is in. Colours,
1081
- font and radius are custom properties (`--minca-accent`, `--minca-font`, …).
1082
- - **React** (`@minca/react`): `MincaProvider`, `useMinca`,
1083
- `useAuth`, `useSession`, `useConnection`, `useAccount`, `useNode`,
1084
- `<MincaAuth>`, `useQuery`, `useLive`, `useSpaces`,
1085
- `useHoldSpace` (holds a space while mounted, releasing it a few seconds late),
1086
- `useRecord`, `useLinked`, `useCollections`, `useProfiles`, `useAccess`,
1087
- `useSpaceStatus`, `useCan`. Calls' `CallsProvider` and `useCalls` are in
1088
- `@minca/calls/react`.
1089
-
1090
- _Source: `packages/core/src/elements/minca-auth.ts`, `packages/react/src/`. Tests: none._
1153
+ These aren't protocol. Another client may draw sign-in and
1154
+ [calls](../../calls/README.md) however it likes.
1155
+
1156
+ Sign-in has no drawn screens in the library: a page draws its own on
1157
+ [`createMincaAuth`](sign-in.md), as the account home does.
1158
+
1159
+ ## React
1160
+
1161
+ `@minca/react` follows sign-in or the connection, and keeps what you read
1162
+ live. `MincaProvider` goes at the top, given an `auth` or a `connection`;
1163
+ `useMinca`, `useAuth`, `useSession`, `useConnection` and `useAccount` read
1164
+ it. Below it, hooks such as `useNode`,
1165
+ `useSpaces`, `useQuery`, `useRecord` and `useCan` read and keep current what
1166
+ you show, with `useLive` and `useWatched` for anything else. Each one, and what
1167
+ it gives, is in the [React reference](https://minca.dev/api/react/).
1168
+
1169
+ `result.complete` is false while an app that holds only part of a space is
1170
+ still fetching a collection. Show "Loading…", not "Nothing here".
1171
+
1172
+ An app given the whole account sees every space in it. `useSpaces({ having: [todos] })`
1173
+ lists only the spaces that define those collections.
1174
+
1175
+ Calls have their own, `CallsProvider` and `useCalls`, in `@minca/calls/react`.