chirli 0.1.0 → 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 (90) hide show
  1. package/ARCHITECTURE.md +18 -20
  2. package/CONTRIBUTING.md +7 -3
  3. package/README.md +63 -55
  4. package/SECURITY.md +11 -11
  5. package/dist/allowlist.d.ts +3 -0
  6. package/dist/allowlist.js +9 -0
  7. package/dist/announcements.d.ts +4 -4
  8. package/dist/announcements.js +66 -34
  9. package/dist/attachments.d.ts +43 -0
  10. package/dist/attachments.js +340 -0
  11. package/dist/blossom.d.ts +2 -2
  12. package/dist/blossom.js +120 -66
  13. package/dist/bot-handlers.d.ts +9 -18
  14. package/dist/bot-handlers.js +125 -66
  15. package/dist/bot.d.ts +17 -20
  16. package/dist/bot.js +150 -55
  17. package/dist/client.d.ts +43 -39
  18. package/dist/client.js +476 -290
  19. package/dist/command-discovery.d.ts +2 -2
  20. package/dist/command-discovery.js +16 -7
  21. package/dist/command-schema.d.ts +2 -2
  22. package/dist/command-schema.js +62 -31
  23. package/dist/commands.d.ts +7 -6
  24. package/dist/commands.js +116 -51
  25. package/dist/defaults.js +13 -6
  26. package/dist/errors.d.ts +12 -12
  27. package/dist/errors.js +55 -18
  28. package/dist/inbox.d.ts +9 -7
  29. package/dist/inbox.js +107 -62
  30. package/dist/index.d.ts +25 -24
  31. package/dist/index.js +11 -11
  32. package/dist/key-sync.d.ts +4 -4
  33. package/dist/key-sync.js +88 -50
  34. package/dist/keys.d.ts +7 -6
  35. package/dist/keys.js +187 -93
  36. package/dist/message-storage-sqlite.d.ts +1 -1
  37. package/dist/message-storage-sqlite.js +32 -27
  38. package/dist/message-storage.d.ts +2 -2
  39. package/dist/messaging-metadata.d.ts +4 -4
  40. package/dist/messaging-metadata.js +73 -46
  41. package/dist/metadata.d.ts +3 -3
  42. package/dist/metadata.js +29 -15
  43. package/dist/modes.d.ts +7 -7
  44. package/dist/modes.js +53 -24
  45. package/dist/nip4e-compat.d.ts +2 -2
  46. package/dist/nip4e-compat.js +2 -2
  47. package/dist/nipcd.d.ts +14 -14
  48. package/dist/nipcd.js +225 -126
  49. package/dist/protocol.d.ts +7 -6
  50. package/dist/protocol.js +101 -54
  51. package/dist/public-inbox.d.ts +17 -15
  52. package/dist/public-inbox.js +129 -138
  53. package/dist/public-thread.d.ts +7 -4
  54. package/dist/public-thread.js +205 -88
  55. package/dist/relay-pool.d.ts +5 -5
  56. package/dist/relay-pool.js +172 -67
  57. package/dist/relay-roles.js +22 -13
  58. package/dist/relay.d.ts +11 -11
  59. package/dist/relay.js +194 -100
  60. package/dist/request-timing.d.ts +2 -2
  61. package/dist/request-timing.js +19 -7
  62. package/dist/session.js +7 -5
  63. package/dist/signer.d.ts +1 -1
  64. package/dist/signers/bunker-relays.d.ts +2 -2
  65. package/dist/signers/bunker-relays.js +16 -13
  66. package/dist/signers/bunker.d.ts +2 -2
  67. package/dist/signers/bunker.js +57 -37
  68. package/dist/signers/nsec.d.ts +2 -2
  69. package/dist/signers/nsec.js +8 -8
  70. package/dist/signers.d.ts +8 -8
  71. package/dist/signers.js +25 -18
  72. package/dist/storage-sqlite.d.ts +3 -1
  73. package/dist/storage-sqlite.js +110 -58
  74. package/dist/storage.d.ts +10 -6
  75. package/dist/store.d.ts +12 -8
  76. package/dist/store.js +156 -78
  77. package/docs/ACCESS.md +14 -25
  78. package/docs/API.md +125 -79
  79. package/docs/KEYS.md +3 -3
  80. package/docs/NIP-CD.md +29 -19
  81. package/docs/PUBLIC.md +33 -23
  82. package/docs/RECOVERY.md +7 -5
  83. package/docs/RELAYS.md +6 -6
  84. package/docs/SESSIONS.md +25 -21
  85. package/docs/SIGNERS.md +5 -3
  86. package/docs/STORAGE.md +15 -15
  87. package/docs/TUTORIAL.md +42 -39
  88. package/package.json +1 -37
  89. package/dist/inbound-policy.d.ts +0 -4
  90. package/dist/inbound-policy.js +0 -9
package/docs/API.md CHANGED
@@ -5,14 +5,16 @@ Chirli is an ESM-only Node.js 24+ package. Import from `chirli`; internal source
5
5
  ## Construction
6
6
 
7
7
  ```ts
8
- import { Bot, nsecSigner } from 'chirli';
8
+ import { Bot, nsecSigner } from "chirli";
9
9
 
10
10
  const signer = nsecSigner(nsecFromYourSecretManager);
11
11
  const bot = new Bot({
12
12
  signer,
13
- database: './chirli.sqlite',
13
+ database: "./chirli.sqlite",
14
+ });
15
+ bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
16
+ await ctx.reply("pong");
14
17
  });
15
- bot.command({ command: 'ping', scopes: ['kind:14'] }, async ctx => { await ctx.reply('pong'); });
16
18
  await bot.start();
17
19
  console.log(bot.pubkey);
18
20
  ```
@@ -25,7 +27,7 @@ Construct the Bot and register handlers before calling `start()`. `start()` reso
25
27
  | --- | --- |
26
28
  | `signer` | Required signing and account-key NIP-44 capabilities; see [signers](SIGNERS.md) |
27
29
  | `database` | SQLite path; default `psstpsst.sqlite`; `:memory:` is ephemeral |
28
- | `messageStorage` | Message records and processing state; defaults to `sqliteMessageStorage` |
30
+ | `messageStorage` | Retained private conversation history and its diagnostic states; defaults to `sqliteMessageStorage` |
29
31
  | `sessionStore` | Optional backend for conversation state. See the [custom store example](SESSIONS.md#use-a-custom-session-store). |
30
32
  | `storageKey` | Optional 32-byte local encryption key; omission selects tagged plaintext |
31
33
  | `transport` | Injected `Transport`; exclusive with `transportOptions` |
@@ -36,8 +38,8 @@ Construct the Bot and register handlers before calling `start()`. `start()` reso
36
38
  | `writeRelays` | Public metadata/command role; nonempty |
37
39
  | `discoveryRelays` | Extra recipients for public account announcements; `[]` disables this extra fan-out |
38
40
  | `blossomServers` | Ordered upload servers; defaults to `https://blossom.jumble.social/`; `[]` disables file uploads |
39
- | `blossomDownloadOrigins` | Optional trusted HTTPS origins for downloads served by a separate CDN |
40
- | `inboundPolicy` | Optional synchronous policy over verified senders, evaluated before persistence |
41
+ | `blossomDownloadOrigins` | Additional trusted HTTPS origins for uploaded blob URLs and incoming attachment downloads |
42
+ | `attachmentDirectory` | Root directory for verified downloads. Defaults to `<database>.attachments`, or `psstpsst.sqlite.attachments` for an in-memory database |
41
43
  | `mode` | `nip17` default, or explicit `nip4e` split messaging keys |
42
44
  | `keyRotation` | Omitted/false, or split-mode rotation settings; see [keys](KEYS.md) |
43
45
  | `nip4eCompatibility` | False suppresses identity-key 10044 publication; dual intake stays enabled |
@@ -47,14 +49,14 @@ Construct the Bot and register handlers before calling `start()`. `start()` reso
47
49
  | `metadataCache` | Peer cache settings or false; see [relays](RELAYS.md) |
48
50
  | `keySync` | Same-identity split-key sync settings or false; see [keys](KEYS.md) |
49
51
 
50
- Omitted relay roles use exported `DEFAULT_DM_RELAYS`, `DEFAULT_READ_RELAYS`, `DEFAULT_WRITE_RELAYS` and `DEFAULT_DISCOVERY_RELAYS` unless overridden by the `relays` shorthand. The account, mode and storage codec are fixed for a Bot's lifetime. Preserve credentials, database and any storage key after restart.
52
+ Omitted relay roles use exported `DEFAULT_DM_RELAYS`, `DEFAULT_READ_RELAYS`, `DEFAULT_WRITE_RELAYS` and `DEFAULT_DISCOVERY_RELAYS` unless overridden by the `relays` shorthand. The account, mode and storage codec are fixed for a Bot's lifetime. Use a fresh database for this storage format; earlier pre-release databases are not migrated. Preserve credentials, this database and any storage key across restarts.
51
53
 
52
54
  ## Lifecycle
53
55
 
54
56
  | Method | Behavior |
55
57
  | --- | --- |
56
58
  | `announce(options?)` | Explicitly publish account key/relay metadata and synchronize registered commands |
57
- | `start()` | Resolve the signer, publish key/relay metadata, synchronize commands, open inbox and retry persisted work |
59
+ | `start()` | Resolve the signer, publish key/relay metadata, synchronize commands, open inbox and retry pending outgoing deliveries |
58
60
  | `idle()` | Drain ordered crypto intake and currently queued handlers |
59
61
  | `requestStop()` | Request shutdown from a handler without awaiting its own drain |
60
62
  | `stop()` | Cancel subscriptions/timers/recovery and drain current work; Bot stays reusable |
@@ -66,7 +68,7 @@ Omitted relay roles use exported `DEFAULT_DM_RELAYS`, `DEFAULT_READ_RELAYS`, `DE
66
68
  `start()` does not render or return the identity. After it completes, `bot.pubkey` is the bot account’s 64-character lowercase hex public key. Applications can display it as text or derive a link or QR payload:
67
69
 
68
70
  ```ts
69
- import { npubEncode } from 'nostr-tools/nip19';
71
+ import { npubEncode } from "nostr-tools/nip19";
70
72
 
71
73
  await bot.start();
72
74
  const uri = `nostr:${npubEncode(bot.pubkey)}`;
@@ -74,30 +76,40 @@ const uri = `nostr:${npubEncode(bot.pubkey)}`;
74
76
 
75
77
  Concurrent start calls share readiness/failure; a start during stop waits for teardown. Startup requires one ready DM replica, while command reconciliation requires every write relay. Other DM replicas can continue recovering. History scans may report incomplete coverage without failing startup. Start does not await every business handler.
76
78
 
77
- `idle()` is not a remote synchronization or delivery barrier. `idle()`, `retryInbox()`, `stop()` and `close()` reject inside message handlers because they would wait on themselves. Use `requestStop()` there, then drain outside the handler.
79
+ `idle()` is not a remote synchronization or delivery barrier. `idle()`, `stop()` and `close()` reject inside message handlers because they would wait on themselves. Use `requestStop()` there, then drain outside the handler. Once stopping begins, new intake is ignored and `bot.receive()` returns `false` without consuming the ID. Work already queued for processing can finish; inputs still being decrypted are not admitted after stop.
78
80
 
79
81
  Await application-owned sends and stop/await application timers before closing Bot. SDK shutdown drains its own work; it cannot cancel arbitrary application effects. One active Bot/process per account database is supported.
80
82
 
83
+ ## Event processing flow
84
+
85
+ 1. **Verify.** For a DM, unwrap the envelope and verify its signatures, canonical rumor ID, sender and recipient, then check its authenticated timestamp against first activation. For a public note or comment, verify the signed event and check its configured source relay, structure, command target and scope. Invalid or ineligible input stops here; it claims nothing and runs no middleware, command or fallback.
86
+ 2. **Claim.** Atomically insert the canonical ID in the account/mode's SQLite store: the inner rumor ID for a DM, or the signed event ID for public input. A duplicate stops before middleware. Eligible public history still stops after claiming its ID; a later live copy does not run. Incoming DM recovery and live delivery use the same admission rule. Eligible outgoing self copies can populate private history without middleware.
87
+ 3. **Run middleware once.** An eligible input enters its conversation or public-root queue. Middleware runs in registration order; put `bot.use(allowlist(pubkeys))` first to restrict everything downstream. Returning without `next()` stops routing. If the chain throws, the error is reported through the applicable error handler. In either case the ID stays claimed; reconnect and restart do not reopen it.
88
+ 4. **Route.** When middleware reaches routing, a DM is saved to private conversation history and can notify receipt observers. Public input has no stored body or conversation history. The SDK invokes the matching scoped command (including argument checks and any command-specific authorization), or the DM fallback if no command matches. The claim is already durable: a crash can leave a callback partially executed or prevent it from running at all.
89
+ 5. **Publish outgoing events separately.** Sends, replies and reactions are stored before publication. Startup, reconnect or `flushOutbox()` can retry that exact signed event, not the incoming callback. Relay acceptance does not confirm delivery or reading.
90
+
81
91
  ## Processing and observations
82
92
 
83
93
  ```ts
84
- const detach = bot.handle(async ctx => {
85
- await ctx.reply('Thanks');
94
+ const detach = bot.handle(async (ctx) => {
95
+ await ctx.reply("Thanks");
86
96
  });
87
97
 
88
- const unobserve = bot.observe(message => {
98
+ const unobserve = bot.observe((message) => {
89
99
  // Receipt observation only; no durable success/failure responsibility.
90
100
  });
91
101
  ```
92
102
 
93
103
  `handle()` registers the handler for messages with no matching command. It receives the same context as command handlers and can be registered before or after commands. Each Bot has one fallback. Call the returned unsubscribe function before registering a replacement.
94
104
 
95
- `observe()` subscribes to new incoming live receipts using detached copies. An observer runs independently of command matching and message completion. Use it for receipt monitoring.
105
+ `observe()` subscribes to newly admitted DMs retained in local conversation history, using detached copies. It runs once routing is reached and does not control command matching or completion.
96
106
 
97
- Commands, middleware and the fallback share durable processing. If any step fails, earlier effects may repeat on retry. Conversation queues are serial, and separate conversations can proceed concurrently. Historical messages and outgoing self copies are stored without dispatch.
107
+ Callbacks are serial within a conversation or public root; different queues can proceed concurrently. See the [event processing flow](#event-processing-flow) for the claim, history and outgoing retry boundaries.
98
108
 
99
109
  `onError(observer)` returns an unsubscribe function. It receives an error and optional verified message context. Observer failures are ignored; there is no SDK default logger.
100
110
 
111
+ For callers injecting protocol events, `await bot.receive(event, source, {relay})` reports intake, not handler success. An eligible new ID returns `true` even if access middleware later stops it; a duplicate or ineligible event returns `false`. Public injection requires a configured source relay. Use `await bot.idle()` to drain queued callbacks, not to force retries.
112
+
101
113
  A `Message` contains rumor `id`, identity `sender`, peer `conversation`, `text`, millisecond `timestamp`, `source`, `direction`, verified `rumor`, optional parent `replyTo`, and optional transport `relay`. Relay provenance is not author-signed. Deduplication uses account/mode + rumor ID, not giftwrap ID.
102
114
 
103
115
  ## Sending and history
@@ -107,7 +119,9 @@ A `Message` contains rumor `id`, identity `sender`, peer `conversation`, `text`,
107
119
  ### Upload file bytes
108
120
 
109
121
  ```ts
110
- const { url, sha256, size, mimeType } = await bot.uploadFile(bytes, { mimeType: 'image/png' });
122
+ const { url, sha256, size, mimeType } = await bot.uploadFile(bytes, {
123
+ mimeType: "image/png",
124
+ });
111
125
  ```
112
126
 
113
127
  `uploadFile(bytes, options?)` uploads the supplied bytes as-is, without encryption, to the first configured Blossom server that accepts them. If the bytes are plaintext, people who can access the blob URL can read them. Callers can encrypt bytes themselves before uploading. Pass `mimeType` for the uploaded bytes, or omit it to use `application/octet-stream`. The result contains the verified URL, SHA-256, byte count and MIME sent in the request. The URL must end in the blob hash, with an optional extension, and use the accepting server’s origin or an explicit `blossomDownloadOrigins` entry. This upload does not send any Nostr message or publish a note; callers can use the result to build a public note with an `imeta` tag.
@@ -117,14 +131,14 @@ const { url, sha256, size, mimeType } = await bot.uploadFile(bytes, { mimeType:
117
131
  Pass the file bytes, not a URL or a path. Configure the servers when constructing the bot:
118
132
 
119
133
  ```ts
120
- import { readFile } from 'node:fs/promises';
121
- import { Bot } from 'chirli';
134
+ import { readFile } from "node:fs/promises";
135
+ import { Bot } from "chirli";
122
136
 
123
- const bot = new Bot({ signer, blossomServers: ['https://files.example.com'] });
137
+ const bot = new Bot({ signer, blossomServers: ["https://files.example.com"] });
124
138
  await bot.start();
125
- const result = await bot.sendFile(peerPubkey, await readFile('report.pdf'), {
126
- name: 'report.pdf',
127
- mimeType: 'application/pdf',
139
+ const result = await bot.sendFile(peerPubkey, await readFile("report.pdf"), {
140
+ name: "report.pdf",
141
+ mimeType: "application/pdf",
128
142
  });
129
143
  ```
130
144
 
@@ -132,47 +146,71 @@ const result = await bot.sendFile(peerPubkey, await readFile('report.pdf'), {
132
146
 
133
147
  By default Chirli uses the exported `DEFAULT_BLOSSOM_SERVERS` list. An explicit list replaces it entirely. `start()` and `announce()` publish the ordered BUD-03 kind 10063 list to `writeRelays` and `discoveryRelays`, not to DM-only relays. With `blossomServers: []`, Chirli publishes no Blossom list and does not clear an existing public list. Use HTTPS URLs with no credentials, query or fragment. Explicit HTTP loopback URLs are allowed for development. Chirli tries only the configured servers, in order. After the first upload succeeds, it tries BUD-04 mirroring concurrently on the remaining configured servers. Mirrors are best-effort: failures do not change the successful upload result. Mirror requests reuse the successful upload authorization and have a 10-second HTTP timeout. The authorization is restricted to configured server hostnames; mirrors never ask the signer to sign again. No unconfigured server is used.
134
148
 
135
- The server receives ciphertext, ciphertext size/hash and a signed upload authorization identifying the bot. The recipient gets the URL and decryption metadata inside a NIP-17 kind-15 gift wrap. Chirli stores outgoing file metadata in local message history like other messages; use `storageKey` (and an appropriate custom store, if configured) to protect it at rest. This API sends private files only. Incoming file handling and downloading are not provided.
149
+ The server receives ciphertext, ciphertext size/hash and a signed upload authorization identifying the bot. The recipient gets the URL and decryption metadata inside a NIP-17 kind-15 gift wrap. Chirli stores outgoing file metadata in local message history like other messages; use `storageKey` (and an appropriate custom store, if configured) to protect it at rest. This API sends private files only.
136
150
 
137
151
  See [NIP-17](https://github.com/nostr-protocol/nips/blob/master/17.md) and [Blossom server lists](https://github.com/hzrd149/blossom/blob/master/buds/03.md).
138
152
 
153
+ ### Receive and download a private file
154
+
155
+ File DMs pass through the same middleware and `handle()` callback as text DMs. A kind-15 input has empty `text` and carries a `file` attachment. It bypasses text command matching. Incoming files use the same replay protection and history admission as other private messages.
156
+
157
+ ```ts
158
+ bot.handle(async (ctx) => {
159
+ const attachment = ctx.input.file;
160
+ if (!attachment) return;
161
+
162
+ const { file, error } = await attachment.download();
163
+ if (error !== null) {
164
+ await ctx.reply(`Unable to read the attachment (${error.code}).`);
165
+ return;
166
+ }
167
+ await ctx.reply(`Received ${file.name} (${file.size} bytes).`);
168
+ });
169
+ ```
170
+
171
+ `FileAttachment` exposes the sender's URL, MIME type, encrypted SHA-256 (`x`), optional plaintext SHA-256 (`ox`), optional encrypted and plaintext byte counts, and an optional filename. These values describe the attachment as sent. Admitted files are also available on `Message.file` in receipt observers and retained history and on `Input.file` in a private thread. Download after the message is admitted, for example in `handle()` or from retained history.
172
+
173
+ `download()` resolves to `{ file, error: null }` or `{ file: null, error }`. The returned standard `File` supports `stream()` and `arrayBuffer()`. Its name defaults to the verified plaintext SHA-256 when the message has no usable filename. Errors have a `code`, a message, and an optional HTTP `status`. Codes cover download failure, integrity checks, decryption, storage and attempts to download outside admitted history.
174
+
175
+ Use `attachment.mimeType` when setting a `Content-Type` header or parsing the file with case-sensitive MIME parameters such as a multipart boundary. The standard `File` constructor lowercases `file.type`, including parameter values. [File API constructor](https://w3c.github.io/FileAPI/#file-constructor)
176
+
177
+ Downloads use the configured Blossom server origins and additional `blossomDownloadOrigins`. Redirects and fallback URLs must follow the same origin rules. If a source times out or returns ciphertext that fails verification, Chirli tries the next fallback URL. The network budget is 60 seconds, with each source receiving a share of the remaining time. The SDK buffers the attachment in memory without a fixed download size limit. Applications decide whether to call `download()`. The optional size fields are sender declarations and are verified after fetching. Chirli checks the encrypted hash, authenticates and decrypts with AES-GCM, then checks the plaintext hash and size when present. Verified plaintext is saved under the account's public key in `attachmentDirectory`, using the computed hash as its filename. A verified cache entry can be reused for the same sender and encryption metadata. Files on disk are plaintext even when `storageKey` protects the message database.
178
+
139
179
  ### Reply with a private or public file
140
180
 
141
181
  ```ts
142
- await ctx.replyFile(bytes, { mimeType: 'image/png', name: 'report.png' });
143
- await bot.replyFile(event, bytes, { mimeType: 'image/png' }); // Outside the handler.
182
+ await ctx.replyFile(bytes, { mimeType: "image/png", name: "report.png" });
183
+ await bot.replyFile(event, bytes, { mimeType: "image/png" }); // Outside the handler.
144
184
  ```
145
185
 
146
186
  `bot.replyFile` takes the same original `ctx.input.event` as `bot.reply`, not an event ID. Both forms return the normal send result. The anchor decides the visibility:
147
187
 
148
- - Authenticated kind-14 DM: encrypt the bytes and send a kind-15 DM with a reference to the triggering rumor. The optional filename is inside the encrypted message.
188
+ - Authenticated kind-14 or kind-15 DM: encrypt the bytes and send a kind-15 DM with a reference to the triggering rumor. The optional filename is inside the encrypted message.
149
189
  - Signed kind 1/1111: **upload the supplied bytes as-is and publicly post the URL**. The reply is kind 1111 with the same root, parent and relay routing as `reply()`, plus an `imeta` tag. The DM filename option is ignored on this path. Only use this form with bytes you intend to publish.
150
190
 
151
191
  For a new top-level public note rather than a reply, `uploadFile()` supplies the blob metadata; Chirli does not create the kind-1 note.
152
192
 
153
193
  ### Replies and references
154
194
 
155
- To reply to a message, pass its ID:
195
+ To reference an earlier DM explicitly, pass its ID:
156
196
 
157
197
  ```ts
158
- await ctx.reply('Got it', { replyTo: ctx.message.id });
159
- await bot.send(peerPubkey, 'Follow-up', { replyTo: earlierMessage.id });
198
+ await ctx.reply("Got it", { replyTo: ctx.input.id }); // Within a DM handler.
199
+ await bot.send(peerPubkey, "Follow-up", { replyTo: earlierMessage.id });
160
200
  ```
161
201
 
162
- `replyTo` is the lowercase hex kind-14 message ID. The SDK writes it as an `e` tag inside the encrypted message. Message objects include the optional parent ID as `message.replyTo` for live messages, history and local lookups. Omit the option for a plain DM.
202
+ `replyTo` is the lowercase hex private message ID. The SDK writes it as an `e` tag inside the encrypted message. Stored private `Message` objects include the optional parent ID as `message.replyTo`. Omit the option for a plain DM. Public replies instead reference the triggering note/comment automatically and do not accept DM options.
163
203
 
164
- ```ts
165
- const parentId = ctx.message.replyTo;
166
- const parent = parentId === undefined ? undefined : ctx.getMessage(parentId);
167
- ```
168
-
169
- `ctx.getMessage(id)` looks in the current conversation. `bot.getMessage(id)` looks across the Bot's local conversations. Both query the configured message store by ID and return `undefined` when the message is missing. Lookup does not fetch from relays.
204
+ `bot.getMessage(id)` looks across the Bot's local private conversations and returns `undefined` if no message is stored. It does not fetch from relays. Use `ctx.thread()` to load context relative to the current input in a shared handler.
170
205
 
171
206
  ### Reactions
172
207
 
173
- Send a private reaction to the current message with `ctx.react('👍')`, or use `bot.react(messageId, '👍')` for a message in local history. Omitting the reaction sends `+` (like). To react to a different message in the handler's conversation, use `ctx.react('👍', messageId)`. The target ID determines the conversation. A missing target rejects.
208
+ Use `ctx.react('👍')` to react to the current input, or pass the original event to `bot.react(event, '👍')`. The Bot method takes an event, not an ID. Omit the reaction string to send `+` (like). Pass a Unicode emoji or other nonblank reaction text; custom image emoji are not supported.
209
+
210
+ - For an authenticated DM, the reaction is a kind-7 rumor inside an encrypted DM envelope and uses the private outbox.
211
+ - For a signed public note or comment, the reaction is a public [NIP-25](https://nips.nostr.com/25) kind-7 event written through the durable public outbox. It tags the target event and author; kind-1111 targets also get a `k` tag.
174
212
 
175
- Reactions use a kind-7 rumor inside the same encrypted DM envelope and durable outbox as text messages. Both reaction methods return `{id, status}` with the same relay acceptance semantics as `send()`. Incoming reactions are ignored, and reactions do not appear in text history or trigger text handlers.
213
+ Both methods return `{id, status}` with the same relay acceptance semantics as `send()`. Incoming reactions are ignored; reactions do not enter private text history or trigger handlers. See [delayed actions](#replies-and-context-after-a-handler) for what the Bot method verifies.
176
214
 
177
215
  ### Delivery and retries
178
216
 
@@ -181,25 +219,25 @@ Discovery, signing and pre-commit persistence errors reject. Once committed, net
181
219
  ### Local history
182
220
 
183
221
  ```ts
184
- const page = bot.history(peerPubkey, { limit: 20 });
222
+ const page = bot.dmHistory(peerPubkey, { limit: 20 });
185
223
  if (page.nextCursor) {
186
- const older = bot.history(peerPubkey, { cursor: page.nextCursor });
224
+ const older = bot.dmHistory(peerPubkey, { cursor: page.nextCursor });
187
225
  }
188
226
  ```
189
227
 
190
228
  History is synchronous local storage access: newest timestamp first, then ascending ID. Default limit is 30, capped at 100. Each page includes `messages`, optional `nextCursor`, `coverage: 'local-only'`, and `complete: false`. The current incoming message and outgoing replies may be present; select context explicitly.
191
229
 
192
- ## Message state and sessions
230
+ ## Private history inspection and sessions
193
231
 
194
232
  | Method | Result |
195
233
  | --- | --- |
196
- | `getMessageState(id)` | `pending`, `processing`, `failed`, `done`, or undefined |
234
+ | `getMessage(id)` | A stored private message, or undefined |
235
+ | `getMessageState(id)` | Diagnostic status of a stored private message, or undefined |
197
236
  | `listMessages({state?,limit?,cursor?})` | `{entries,nextCursor?}`, ordered timestamp/ID ascending |
198
- | `retryInbox({ids?})` | Retry unfinished work; omitted IDs selects all, `[]` selects none |
199
237
  | `await getSession(peer)` | Read the saved session from the configured backend |
200
238
  | `await setSession(peer, value)` | Replace the saved snapshot in the configured backend |
201
239
 
202
- Message list limits are 1..100, default 30. Done/unknown IDs are ignored by retry. Inspection, history, deduplication and retry recovery all use the configured message backend.
240
+ Message list limits are 1..100, default 30. These APIs describe retained private history, not the internal set of claimed IDs. A DM short-circuited by middleware may have a durable ID claim without a history record. Status values never trigger retries.
203
241
 
204
242
  Arbitrary external effects and session saves are not atomic; applications own idempotency.
205
243
 
@@ -210,22 +248,22 @@ Every handler has a conversation-scoped `ctx.session` with `getItem`, `setItem`,
210
248
  | Method | Behavior |
211
249
  | --- | --- |
212
250
  | `use(fn)` | Append middleware before message routing |
213
- | `command(definition, fn, options?)` | Register an explicitly scoped command with an optional typed argument schema |
251
+ | `command(definition, fn, options?)` | Register a command with optional scopes and an optional typed argument schema |
214
252
  | `handle(fn)` | Register the handler for messages with no matching command |
215
253
  | `catch(observer)` | Observe session/middleware failures without consuming them |
216
254
  | `getCommandDefinitions()` | Detached snapshots of this Bot's active definitions |
217
255
 
218
- Use `use()` to register middleware. It runs in registration order and receives `(ctx, next)`. Await `next()` to continue to later middleware and routing. Middleware can return early to stop processing.
256
+ Use `bot.use()` to register Koa-style middleware. Each layer receives the same `ctx` and runs in registration order before routing. Call `next()` at most once; returning without it stops routing.
219
257
 
220
- Routing calls the first matching command with `(ctx, args)`. If none matches, it calls the handler registered with `handle(ctx => …)`. Authorization denial for a matching command ends routing. Context provides `message`, `sender`, `conversation`, `reply`, `react`, `getMessage`, `history`, and `session`.
258
+ Routing calls the first matching command with `(ctx, args)`. If none matches, it calls the handler registered with `handle(ctx => …)`. Authorization denial for a matching command ends routing. Both kinds of handler use the same context: `input`, `sender`, `conversation`, `session`, `reply`, `replyFile`, `react` and `thread`.
221
259
 
222
260
  When args is a Zod 4 object, TypeScript infers its validated output in a separate handler-only ctx.args and the existing second handler parameter. The middleware context is not mutated; its property descriptors, methods and shared session are retained on the handler view. Ordinary middleware/fallback Context has no args. Required values are present, optional values include `undefined`, and enum values use the declared choices. For a definition stored in a separate variable, use `as const satisfies BotCommandDefinition` to preserve its literal types. A dynamic definition exposes unknown argument values until narrowed.
223
261
 
224
- The published `d` equals the command name; custom `id` and the old string shorthand are rejected. Supply `scopes` containing at least one distinct `kind:14`, `kind:1` or `kind:1111`; no kind is inserted implicitly. The same scopes govern publication and authenticated routing. `authorize(ctx, invocation)` controls execution independently of public metadata.
262
+ The published `d` equals the command name; custom `id` and the old string shorthand are rejected. Omit `scopes` to use `["kind:14", "kind:1", "kind:1111"]`. An explicit list replaces the defaults and must contain at least one supported kind. Duplicate kinds are rejected. Public kinds require `publicInbox.relays`. Kind 15 files go through middleware and `handle()` because their content is an attachment URL. `authorize(ctx, invocation)` controls execution independently of public metadata.
225
263
 
226
- `ctx.input` and `await ctx.thread({limit})` work across private and public input. `ctx.reply()` stays encrypted for private input and publishes kind 1111 for public input. `message`, `history`, `react` and `getMessage` are DM-only compatibility methods and throw on public input. Receipt observation and message inspection APIs still describe DMs. See [public inputs and threads](PUBLIC.md) for explicit inbox configuration, target rules and coverage limits.
264
+ `ctx.input` and `await ctx.thread({limit})` work across private and public input. `ctx.reply()` and `ctx.react()` stay encrypted for private input and publish kind 1111 and kind 7, respectively, for public input. Use Bot methods for receipt observation and local private history inspection. See [public inputs and threads](PUBLIC.md) for explicit inbox configuration, target rules and coverage limits.
227
265
 
228
- Session load, middleware, fallback and session save share one error boundary. `catch()` cannot mark failed work successful, and observer failures do not replace the original error. Sessions save only after successful processing.
266
+ Session load, middleware, fallback and session save share one error boundary. `catch()` observes failures without reopening the ID, and observer failures do not replace the original error. Session writes are buffered and commit when middleware returns successfully, even after an intentional short-circuit; an uncaught exception skips the session commit.
229
267
 
230
268
  Omit a command from the next startup registry to withdraw it automatically on restart. Closing the Bot preserves the published catalog until that reconciliation. Runtime additions remain supported; runtime removal is not exposed.
231
269
 
@@ -242,11 +280,11 @@ Command discovery is read-only and returns a bounded relay snapshot with `comple
242
280
 
243
281
  ## Advanced integrations
244
282
 
245
- `await receive(event, 'history' | 'live', {relay}?)` is the verified custom-intake boundary. It returns whether a new supported rumor was stored. Local and remote signers use the same asynchronous path. Classify source truthfully: old history presented as live can execute commands.
283
+ `await receive(event, 'history' | 'live', {relay}?)` is the verified custom-intake boundary. It returns `true` for a newly claimed eligible DM or public input, or a newly stored own DM copy. An ID claim does not imply that a handler ran or that a payload was stored. Local and remote signers use the same asynchronous path. For DMs, the transport source is diagnostic: the authenticated rumor timestamp and first activation determine eligibility. Classify public source truthfully: old public history presented as live can execute commands.
246
284
 
247
285
  Custom `Transport` supplies `query`, `subscribe`, `publish` and `close`. Custom subscription readiness retains its existing contract. Direct built-in Transport subscriptions and bounded queries require actual EOSE; SDK-owned long-lived inboxes alone permit the local read-window fallback described in the relay reference. Physical socket health is independent of either completion signal. The built-in transport uses nostr-tools for pooled physical connections, REQ, EOSE timers, keepalive and ACK tracking, with bounded connect/EOSE/ACK/AUTH operations; `InboxSubscription` owns reconnect and recovery. See [relays](RELAYS.md) and [recovery](RECOVERY.md).
248
286
 
249
- `MessageStorage` implements `insert(account, entry)`, `query(account, options)` and `updateState(account, id, state)`. Entries include encoded payloads and processing state. `sqliteMessageStorage(path)` supplies the default indexed backend. Bot creates and closes its default instance; supplied instances remain application-owned. Internal outbox, keys and metadata always use the `database` path. See [storage](STORAGE.md) for query and failure semantics.
287
+ `MessageStorage` implements `insert(account, entry)`, `query(account, options)` and `updateState(account, id, state)`. Entries include encoded payloads and diagnostic state. `sqliteMessageStorage(path)` supplies the default indexed backend. Bot creates and closes its default instance; supplied instances remain application-owned. Internal outbox, keys and metadata always use the `database` path. See [storage](STORAGE.md) for query and failure semantics.
250
288
 
251
289
  `refreshPeer(pubkey)`, `encryptionKeys()` and `rotateEncryptionKey()` expose peer refresh and public key-custody operations. See [keys](KEYS.md) for retention, own-declaration conflicts and mode changes.
252
290
 
@@ -256,25 +294,28 @@ Command removal is expressed by the next startup registry, not a runtime method.
256
294
 
257
295
  ## Optional official components
258
296
 
259
- `allowlist(pubkeys: readonly string[]): InboundPolicy` snapshots and validates lowercase hex identity keys. Configure `inboundPolicy: allowlist(pubkeys)` in Bot options. `InboundPolicy` is `(authenticatedSender: string) => boolean`, evaluated synchronously after envelope or author verification and before receipt persistence. It runs again before pending work resumes at startup or on retry. Own copies bypass the policy. `allowlist([])` denies all external senders. [Sender authorization](ACCESS.md#official-inbound-policy)
297
+ `allowlist(pubkeys: readonly string[])` returns ordinary middleware. Register `bot.use(allowlist(pubkeys))` before middleware whose effects need protection. It validates and snapshots lowercase hex account keys, checks the verified input author, and calls `next()` only for listed senders. `allowlist([])` blocks every external input from routing. The ID is already claimed; the middleware does not run on public history or outgoing self copies. [Sender authorization](ACCESS.md)
260
298
 
261
- `requestTiming({onTiming})` returns ordinary `bot.use()` middleware. Register it before the processing middleware you want to measure. `RequestTiming` is a frozen object containing only readonly `durationMs:number` (monotonic elapsed milliseconds) and `outcome:'success'|'failure'`. `RequestTimingObserver` may return void or a Promise; synchronous exceptions and rejected observer promises are isolated, and the observer is not awaited. Successful processing stays successful, original handler errors stay the same errors and remain retryable. No context, body, sender, event ID, route inferred from text, credentials or raw error is passed to telemetry. There is no default logger.
299
+ `requestTiming({onTiming})` returns ordinary `bot.use()` middleware. Register it before the processing middleware you want to measure. `RequestTiming` is a frozen object containing only readonly `durationMs:number` (monotonic elapsed milliseconds) and `outcome:'success'|'failure'`. `RequestTimingObserver` may return void or a Promise; synchronous exceptions and rejected observer promises are isolated, and the observer is not awaited. Successful processing stays successful, original handler errors stay the same errors and do not trigger a retry. No context, body, sender, event ID, route inferred from text, credentials or raw error is passed to telemetry. There is no default logger.
262
300
 
263
301
  Timing covers the downstream middleware/command/fallback chain, including reply operations it awaits. It excludes work before this middleware, envelope verification/persistence, queue wait and session persistence after dispatch; a subsequent session-commit error is outside the measured chain outcome. It is neither end-to-end message latency nor a delivery measurement. No route hook or extra framework dependency is introduced.
264
302
 
265
303
  ## Replies and context after a handler
266
304
 
267
- `await bot.reply(event,text,options?)` and `await bot.thread(event,options?)` accept exactly the original `ctx.input.event`: a signed kind 1/1111 Event or an authenticated decrypted kind 14 Rumor. No ID/string, outer gift wrap, context wrapper or token overload is accepted. These methods use the same internal execution as `ctx.reply` and `ctx.thread`; return values, option handling, thread bounds and failures are shared. Private `replyTo` stays optional and is not inserted implicitly. Public replies reject nonempty DM send options.
305
+ `bot.reply(event,text,options?)`, `bot.replyFile(event,bytes,options?)`, `bot.react(event,reaction?)` and `bot.thread(event,options?)` accept the original `ctx.input.event`: a signed kind 1/1111 Event or an authenticated decrypted kind 14 or 15 Rumor. No ID/string, outer gift wrap, context wrapper or token overload is accepted. They use the same routing and visibility as their handler counterparts. Private `replyTo` stays optional and is not inserted implicitly. Public replies reject nonempty DM send options.
268
306
 
269
307
  ```ts
270
308
  // jobs is an application-owned queue; protect plaintext DM events in its storage.
271
- bot.command({command:'work',scopes:['kind:14','kind:1','kind:1111']}, async ctx => {
272
- await jobs.add(structuredClone(ctx.input.event));
273
- });
309
+ bot.command(
310
+ { command: "work", scopes: ["kind:14", "kind:1", "kind:1111"] },
311
+ async (ctx) => {
312
+ await jobs.add(structuredClone(ctx.input.event));
313
+ },
314
+ );
274
315
 
275
316
  // After the handler finishes, with this Bot started and its account store available:
276
317
  async function processJob(event: Event | Rumor) {
277
- const prior = await bot.thread(event, {limit:30});
318
+ const prior = await bot.thread(event, { limit: 30 });
278
319
  const text = await applicationProcessor(prior.entries);
279
320
  return bot.reply(event, text);
280
321
  }
@@ -282,39 +323,44 @@ async function processJob(event: Event | Rumor) {
282
323
 
283
324
  The application supplies `jobs` and `applicationProcessor`; Chirli does not schedule or retain jobs. Import `Rumor` from `chirli` and `Event` from `nostr-tools`. Run `npm run example:async-reply` for a fully offline three-kind example.
284
325
 
285
- Public events are cloned and independently reverified on every call, including IDs, signatures, eligible kind and thread structure. A retained full signed event works after completion/restart even though the public journal removes completed bodies. Known source routing comes only from the SDK's retained local journal, never event tags or a caller-supplied relay. If provenance is unavailable/evicted or that inbox is no longer configured, reply routing uses configured write relays only. Thread queries use the configured public inbox. The public inbox must be configured.
326
+ Public events are cloned and independently reverified on every call, including IDs, signatures, eligible kind and thread structure. A retained full signed event works after completion/restart. The SDK stores no public input body or source relay for delayed calls. Delayed replies and reactions use configured write relays only; immediate handler calls can also use the configured inbox relay that delivered the input. Neither path trusts relay hints from tags. Thread queries use the configured public inbox. The public inbox must be configured.
286
327
 
287
328
  A rumor has no standalone signature. The SDK requires an exact match with the current account/mode's persisted authenticated incoming DM record: hash, canonical fields/tags, sender, recipient, private conversation, text, timestamp and reply reference. Missing records, outgoing self copies, other accounts, changed rumors and outer envelopes are rejected. Reopen with the same signer, database, message backend, mode and any storage key; retaining a rumor alone cannot reconstruct its authentication. DM thread context remains anchored to the saved trigger and excludes later conversation entries.
288
329
 
289
- Calls snapshot the event before asynchronous work, and handler methods retain separate internal snapshots. Mutating a caller object does not retarget an in-flight operation; supplying an already altered object fails verification. Calls require a started/open Bot instance and reject after close. Neither method invokes inbound handlers or provides a queue, token, idempotency key or exactly-once guarantee. Repeating a reply call creates a new logical reply; use application idempotency and `flushOutbox()` for already pending sends. These are explicit application actions, not a second inbound authorization hook; allowlist is not an outbound ACL. Saved DM events contain plaintext and must not be logged or placed in an unprotected job store.
330
+ Calls snapshot the event before asynchronous work, and handler methods retain separate internal snapshots. Mutating a caller object does not retarget an in-flight operation; supplying an already altered object fails verification. Calls require a started/open Bot instance and reject after close. These methods never invoke inbound handlers or provide a queue, token, idempotency key or exactly-once guarantee. Repeating a reply or reaction call creates a new outgoing action; use application idempotency and `flushOutbox()` for already pending sends. These are explicit application actions, not a second inbound authorization hook; allowlist is not an outbound ACL. Saved DM events contain plaintext and must not be logged or placed in an unprotected job store.
290
331
 
291
332
  ## Zod command arguments
292
333
 
293
334
  Declare Zod 4 as an application dependency, import `z` from `zod`, and pass one object directly as `args`. No argument-builder API, second schema or per-command error callback is needed.
294
335
 
295
336
  ```ts
296
- import {z} from 'zod';
297
- import {InvalidArgsError} from 'chirli';
337
+ import { z } from "zod";
338
+ import { InvalidArgsError } from "chirli";
298
339
 
299
340
  bot.use(async (ctx, next) => {
300
- try { await next(); }
301
- catch (error) {
341
+ try {
342
+ await next();
343
+ } catch (error) {
302
344
  if (!(error instanceof InvalidArgsError)) throw error;
303
345
  await ctx.reply(`Usage error for /${error.command}`);
304
346
  }
305
347
  });
306
348
 
307
- bot.command({
308
- command:'pick', scopes:['kind:14','kind:1','kind:1111'],
309
- args:z.object({
310
- user:z.string().meta({label:'User',nipcdType:'pubkey'}),
311
- count:z.bigint().min(1n).max(10n).meta({label:'Count'}),
312
- mode:z.enum(['short','full']).optional().meta({label:'Mode'}),
313
- }),
314
- }, async (ctx, args) => {
315
- // ctx.args and args are the same validated result; count is bigint.
316
- await ctx.reply(`${ctx.args.mode ?? 'short'}: ${args.count}`);
317
- });
349
+ bot.command(
350
+ {
351
+ command: "pick",
352
+ scopes: ["kind:14", "kind:1", "kind:1111"],
353
+ args: z.object({
354
+ user: z.string().meta({ label: "User", nipcdType: "pubkey" }),
355
+ count: z.bigint().min(1n).max(10n).meta({ label: "Count" }),
356
+ mode: z.enum(["short", "full"]).optional().meta({ label: "Mode" }),
357
+ }),
358
+ },
359
+ async (ctx, args) => {
360
+ // ctx.args and args are the same validated result; count is bigint.
361
+ await ctx.reply(`${ctx.args.mode ?? "short"}: ${args.count}`);
362
+ },
363
+ );
318
364
  ```
319
365
 
320
366
  Field names and insertion order generate NIP-CD positional names/order. `optional()` sets required=false. Labels come from field `.meta({label})`, defaulting to the name. String → word, bigint → number, boolean → bool and string enum → enum/choices are inferred. Annotate strings with `nipcdType:'text'|'pubkey'|'event'|'relay'` when needed. For address use `.meta({nipcdType:'address'})` on `z.object({kind:z.number().int(),pubkey:z.string(),identifier:z.string(),relays:z.array(z.string())})`; decoder output matches the existing CommandAddress structure. Constraints/refinements run on decoded values, including asynchronous refinements.
@@ -323,11 +369,11 @@ The supported subset is deliberately bounded: top-level object with no __proto__
323
369
 
324
370
  Registration still automatically publishes the derived CommandArgument[] in the existing kind 31992 format; encode/decode/discovery and protocol CommandDefinition/CommandArgument stay unchanged. `getCommandDefinitions()` returns derived wire definitions, suitable for the pure `parseCommand()` helper. Old Bot args arrays must migrate to z.object; pure protocol helpers continue accepting wire arrays.
325
371
 
326
- After entry policy and middleware, routing first verifies command/target/scopes, then decodes and validates. A matched command's missing/invalid/extra arguments or Zod rejection raises `InvalidArgsError` with command, category (`decode` or `validation`) and bounded safe issues containing only code and registered field path. Submitted values, custom issue messages, raw decoder reasons and arbitrary custom paths are omitted. It never falls through to plain handling. Middleware may catch around await next(); otherwise bot.catch observes it once. With neither handler, it completes silently without an automatic response or retry. An uncaught framework InvalidArgsError skips the session commit; middleware that catches and returns successfully can commit its intentional session writes. Only the exact framework-generated error for that dispatch is terminal; other business/middleware errors (even application-created InvalidArgsError) keep failed/report/retry behavior.
372
+ After middleware, routing first verifies command/target/scopes, then decodes and validates. A matched command's missing/invalid/extra arguments or Zod rejection raises `InvalidArgsError` with command, category (`decode` or `validation`) and bounded safe issues containing only code and registered field path. Submitted values, custom issue messages, raw decoder reasons and arbitrary custom paths are omitted. It never falls through to plain handling. Middleware may catch around await next(); otherwise bot.catch observes it once. With neither handler, it completes silently without an automatic response or retry. An uncaught framework InvalidArgsError skips the session commit; middleware that catches and returns successfully can commit its intentional session writes. The exact framework-generated error is handled separately from application-created errors, which are reported as ordinary failures. Neither path reruns the input.
327
373
 
328
- If a command uses args-dependent `authorize`, malformed input is silently consumed: no validation-error callback is exposed because invalid arguments cannot authorize an error response. Validator exceptions before authorization are retained internally until middleware unwinds, then sent unchanged to the inbox failed/report/retry path. They bypass middleware catch and bot.catch, cannot authorize an error reply, and do not commit sessions. Validators without authorize and other business errors retain existing error-chain semantics. For valid data authorize receives the validated invocation.args before the business handler. No new response-authorization or per-command error callback is introduced. Wrong targets/scopes and entry-policy denials never generate a command-argument error. Public initial admission remains restricted to known, genuinely targeted and scoped invocations; historical/repeated work does not replay error handlers.
374
+ If a command uses args-dependent `authorize`, malformed input is silently consumed: no validation-error callback is exposed because invalid arguments cannot authorize an error response. Validator exceptions before authorization are retained internally until middleware unwinds, then reported unchanged to operational `onError`. They bypass middleware catch and bot.catch, cannot authorize an error reply, and do not commit sessions. Validators without authorize and other business errors retain existing error-chain semantics. For valid data authorize receives the validated invocation.args before the business handler. No new response-authorization or per-command error callback is introduced. Wrong targets/scopes and early middleware stops never generate a command-argument error. Public initial admission remains restricted to known, genuinely targeted and scoped invocations; historical/repeated work does not replay error handlers.
329
375
 
330
- Official requestTiming also reports failure for a validator exception deferred until after middleware because command authorization has not run. Its internal signal contains only failure state, without exposing the original exception or changing next() behavior. Operational onError and inbox retry semantics remain unchanged.
376
+ Official requestTiming also reports failure for a validator exception deferred until after middleware because command authorization has not run. Its internal signal contains only failure state, without exposing the original exception or changing next() behavior. Operational `onError` observes that failure; no callback is retried.
331
377
 
332
378
  ### Command synchronization result across rounds
333
379
 
package/docs/KEYS.md CHANGED
@@ -9,8 +9,8 @@ const day = 24 * 60 * 60 * 1000;
9
9
 
10
10
  const bot = new Bot({
11
11
  signer,
12
- mode: 'nip4e',
13
- database: './chirli.sqlite',
12
+ mode: "nip4e",
13
+ database: "./chirli.sqlite",
14
14
  storageKey,
15
15
  keyRotation: {
16
16
  intervalMs: 30 * day,
@@ -53,7 +53,7 @@ An envelope addressed only to an evicted key can no longer be decrypted. Local t
53
53
  When using a different mode with the same account, close the old Bot and keep its database and storage key. If the account already advertises a different key, acknowledge the exact locally held key in `announce()` before starting.
54
54
 
55
55
  ```ts
56
- const split = new Bot({ mode: 'nip4e', signer, database, storageKey, relays });
56
+ const split = new Bot({ mode: "nip4e", signer, database, storageKey, relays });
57
57
  await split.announce({ replaceEncryptionKey: await signer.getPublicKey() });
58
58
  await split.start();
59
59
  const previousSplitKey = split.encryptionKeys().currentPublicKey;
package/docs/NIP-CD.md CHANGED
@@ -7,21 +7,28 @@ Kind **10992** is a user’s installed-command list. Chirli neither publishes it
7
7
  ## Register the complete set before starting
8
8
 
9
9
  ```ts
10
- import {z} from 'zod';
10
+ import { z } from "zod";
11
11
 
12
12
  const bot = new Bot({ signer });
13
- bot.command({ command: 'ping', scopes: ['kind:14'] }, async ctx => { await ctx.reply('pong'); });
14
- bot.command({
15
- command: 'sum', scopes: ['kind:14'],
16
- title: 'Sum',
17
- description: 'Add two integers.',
18
- args: z.object({
19
- left: z.bigint().meta({label:'Left'}),
20
- right: z.bigint().meta({label:'Right'}),
21
- }),
22
- }, async (ctx, { left, right }) => {
23
- await ctx.reply(String(left + right));
24
- }, { authorize: ctx => allowedSenders.has(ctx.sender) });
13
+ bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
14
+ await ctx.reply("pong");
15
+ });
16
+ bot.command(
17
+ {
18
+ command: "sum",
19
+ scopes: ["kind:14"],
20
+ title: "Sum",
21
+ description: "Add two integers.",
22
+ args: z.object({
23
+ left: z.bigint().meta({ label: "Left" }),
24
+ right: z.bigint().meta({ label: "Right" }),
25
+ }),
26
+ },
27
+ async (ctx, { left, right }) => {
28
+ await ctx.reply(String(left + right));
29
+ },
30
+ { authorize: (ctx) => allowedSenders.has(ctx.sender) },
31
+ );
25
32
  await bot.start();
26
33
  ```
27
34
 
@@ -29,7 +36,7 @@ Command metadata is public and goes to `writeRelays`. The `authorize` callback c
29
36
 
30
37
  ## Automatic startup reconciliation
31
38
 
32
- Before business subscriptions or pending handlers begin, startup:
39
+ Before business subscriptions begin, startup:
33
40
 
34
41
  1. Reads the executor's complete kind 31992 snapshot from every configured write relay, scoped to its identity author. This is one broad logical scan per relay, with bounded paging when necessary, never one query per command. No `#d` filter or kind 5 query is used for startup reconciliation.
35
42
  2. Compares that snapshot with the complete local registry, keeps unchanged definitions and publishes missing/changed definitions.
@@ -44,20 +51,23 @@ Relays commonly remove the targeted definition after accepting kind 5. Reconcili
44
51
  ## Runtime addition and restart reconciliation
45
52
 
46
53
  ```ts
47
- bot.command({ command: 'help', scopes: ['kind:14'] }, async ctx => { await ctx.reply('Available commands…'); });
54
+ bot.command({ command: "help", scopes: ["kind:14"] }, async (ctx) => {
55
+ await ctx.reply("Available commands…");
56
+ });
48
57
  // Optional: await the automatic background synchronization before reading a snapshot.
49
58
  await bot.syncCommands();
50
59
  ```
51
60
 
52
61
  The published `d` is always the command name in `bot.command()`. Custom `id` arguments, even those matching the command name, are rejected. To remove a command, omit it from the next complete startup registry and restart with the same account and relays. A rename is removal of the old command plus registration of a new command at a different coordinate. If publication fails, `flushAnnouncements()` or `syncCommands()` can optionally await/retry the same automatic process.
53
62
 
54
- `syncCommands()` returns added, updated and removed identifiers only; it is an optional wait/retry helper. Closing the Bot preserves public definitions and durable pending work for restart.
63
+ `syncCommands()` returns added, updated and removed identifiers only; it is an optional wait/retry helper. Closing the Bot preserves public definitions and pending publication operations for restart, not pending handler work.
55
64
 
56
65
  ## Discovery
57
66
 
58
67
  ```ts
59
68
  const snapshot = await bot.discoverCommands({
60
- authors: [knownExecutorPubkey], relays: discoveryRelays,
69
+ authors: [knownExecutorPubkey],
70
+ relays: discoveryRelays,
61
71
  });
62
72
  ```
63
73
 
@@ -75,14 +85,14 @@ Invocations begin at content index zero:
75
85
 
76
86
  The qualifier is optional. Both `@npub` and `@nostr:npub` target the executor's identity key.
77
87
 
78
- - Registration uses one object form with explicit scopes. To accept trailing text, declare an optional terminal `text` argument.
88
+ - Registration uses one object form with optional scopes. To accept trailing text, declare an optional terminal `text` argument.
79
89
  - A full definition supports positional `pubkey`, `event`, `address`, `relay`, `number`, `bool`, `enum`, `word` and `text` arguments. Numbers are parsed as `bigint`.
80
90
  - A terminal `text` argument removes one separator and preserves the rest, including leading spaces and newlines.
81
91
  - The first matching command owns the route. An unknown trigger, unselected target or scope mismatch can fall through to the DM `handle()`. Recognized, correctly targeted/scoped commands with invalid arguments never fall through. An authorization denial on the matched command stops routing.
82
92
 
83
93
  ## Scope rules
84
94
 
85
- Bot requires at least one explicitly declared supported kind: `kind:14`, `kind:1` or `kind:1111`. Duplicate kind scopes are rejected. These exact scopes are published and checked against the verified input; no implicit DM fallback is added. Additional scopes narrow that match:
95
+ Bot publishes `kind:14`, `kind:1` and `kind:1111` by default. An explicit `scopes` list replaces the defaults and must include at least one supported kind. Duplicate kind scopes are rejected. Text command routing checks the published scopes against verified input. Kind 15 files go through middleware and `handle()` because their content is an attachment URL. Additional scopes narrow command matching:
86
96
 
87
97
  | Scope | Checks |
88
98
  | --- | --- |