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.
- package/ARCHITECTURE.md +18 -20
- package/CONTRIBUTING.md +7 -3
- package/README.md +63 -55
- package/SECURITY.md +11 -11
- package/dist/allowlist.d.ts +3 -0
- package/dist/allowlist.js +9 -0
- package/dist/announcements.d.ts +4 -4
- package/dist/announcements.js +66 -34
- package/dist/attachments.d.ts +43 -0
- package/dist/attachments.js +340 -0
- package/dist/blossom.d.ts +2 -2
- package/dist/blossom.js +120 -66
- package/dist/bot-handlers.d.ts +9 -18
- package/dist/bot-handlers.js +125 -66
- package/dist/bot.d.ts +17 -20
- package/dist/bot.js +150 -55
- package/dist/client.d.ts +43 -39
- package/dist/client.js +476 -290
- package/dist/command-discovery.d.ts +2 -2
- package/dist/command-discovery.js +16 -7
- package/dist/command-schema.d.ts +2 -2
- package/dist/command-schema.js +62 -31
- package/dist/commands.d.ts +7 -6
- package/dist/commands.js +116 -51
- package/dist/defaults.js +13 -6
- package/dist/errors.d.ts +12 -12
- package/dist/errors.js +55 -18
- package/dist/inbox.d.ts +9 -7
- package/dist/inbox.js +107 -62
- package/dist/index.d.ts +25 -24
- package/dist/index.js +11 -11
- package/dist/key-sync.d.ts +4 -4
- package/dist/key-sync.js +88 -50
- package/dist/keys.d.ts +7 -6
- package/dist/keys.js +187 -93
- package/dist/message-storage-sqlite.d.ts +1 -1
- package/dist/message-storage-sqlite.js +32 -27
- package/dist/message-storage.d.ts +2 -2
- package/dist/messaging-metadata.d.ts +4 -4
- package/dist/messaging-metadata.js +73 -46
- package/dist/metadata.d.ts +3 -3
- package/dist/metadata.js +29 -15
- package/dist/modes.d.ts +7 -7
- package/dist/modes.js +53 -24
- package/dist/nip4e-compat.d.ts +2 -2
- package/dist/nip4e-compat.js +2 -2
- package/dist/nipcd.d.ts +14 -14
- package/dist/nipcd.js +225 -126
- package/dist/protocol.d.ts +7 -6
- package/dist/protocol.js +101 -54
- package/dist/public-inbox.d.ts +17 -15
- package/dist/public-inbox.js +129 -138
- package/dist/public-thread.d.ts +7 -4
- package/dist/public-thread.js +205 -88
- package/dist/relay-pool.d.ts +5 -5
- package/dist/relay-pool.js +172 -67
- package/dist/relay-roles.js +22 -13
- package/dist/relay.d.ts +11 -11
- package/dist/relay.js +194 -100
- package/dist/request-timing.d.ts +2 -2
- package/dist/request-timing.js +19 -7
- package/dist/session.js +7 -5
- package/dist/signer.d.ts +1 -1
- package/dist/signers/bunker-relays.d.ts +2 -2
- package/dist/signers/bunker-relays.js +16 -13
- package/dist/signers/bunker.d.ts +2 -2
- package/dist/signers/bunker.js +57 -37
- package/dist/signers/nsec.d.ts +2 -2
- package/dist/signers/nsec.js +8 -8
- package/dist/signers.d.ts +8 -8
- package/dist/signers.js +25 -18
- package/dist/storage-sqlite.d.ts +3 -1
- package/dist/storage-sqlite.js +110 -58
- package/dist/storage.d.ts +10 -6
- package/dist/store.d.ts +12 -8
- package/dist/store.js +156 -78
- package/docs/ACCESS.md +14 -25
- package/docs/API.md +125 -79
- package/docs/KEYS.md +3 -3
- package/docs/NIP-CD.md +29 -19
- package/docs/PUBLIC.md +33 -23
- package/docs/RECOVERY.md +7 -5
- package/docs/RELAYS.md +6 -6
- package/docs/SESSIONS.md +25 -21
- package/docs/SIGNERS.md +5 -3
- package/docs/STORAGE.md +15 -15
- package/docs/TUTORIAL.md +42 -39
- package/package.json +1 -37
- package/dist/inbound-policy.d.ts +0 -4
- package/dist/inbound-policy.js +0 -9
package/docs/PUBLIC.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Public notes, comments and private input
|
|
2
2
|
|
|
3
|
-
Chirli accepts authenticated kind 14 DMs and verified public kind 1/1111 commands. Applications still own message processing and authorization. There is no general event-adapter framework or AI dependency.
|
|
3
|
+
Chirli accepts authenticated kind 14 and kind 15 DMs and verified public kind 1/1111 commands. Applications still own message processing and authorization. There is no general event-adapter framework or AI dependency.
|
|
4
4
|
|
|
5
5
|
## Explicit registration and inbox
|
|
6
6
|
|
|
@@ -8,47 +8,57 @@ Chirli accepts authenticated kind 14 DMs and verified public kind 1/1111 command
|
|
|
8
8
|
const bot = new Bot({
|
|
9
9
|
signer,
|
|
10
10
|
publicInbox: {
|
|
11
|
-
relays: [
|
|
12
|
-
thread: {timeoutMs:3000,maxEvents:500,maxLookups:16,maxDepth:64},
|
|
11
|
+
relays: ["wss://your-inbox.example", "wss://your-second-inbox.example"],
|
|
12
|
+
thread: { timeoutMs: 3000, maxEvents: 500, maxLookups: 16, maxDepth: 64 },
|
|
13
13
|
},
|
|
14
|
-
writeRelays: [
|
|
15
|
-
});
|
|
16
|
-
bot.command({command:'ping',scopes:['kind:14','kind:1','kind:1111']}, async ctx => {
|
|
17
|
-
await ctx.reply('pong');
|
|
14
|
+
writeRelays: ["wss://your-write.example"],
|
|
18
15
|
});
|
|
16
|
+
bot.command(
|
|
17
|
+
{ command: "ping" },
|
|
18
|
+
async (ctx) => {
|
|
19
|
+
await ctx.reply("pong");
|
|
20
|
+
},
|
|
21
|
+
);
|
|
19
22
|
await bot.start();
|
|
20
23
|
```
|
|
21
24
|
|
|
22
25
|
The example URLs are placeholders. Public inbox URLs must be chosen explicitly by the operator; no default public firehose opens. A public subscription selects only kinds declared by current commands, with a 500-event initial window per relay. Runtime additions update public subscriptions after command catalog synchronization. To remove commands, omit them from the next registry and restart; startup withdraws their definitions. DM subscription, metadata publication and automatic kind 31992 reconciliation retain their existing behavior.
|
|
23
26
|
|
|
24
|
-
`scopes`
|
|
27
|
+
Omitting `scopes` publishes `kind:14`, `kind:1` and `kind:1111`. An explicit list replaces the defaults and must contain at least one supported kind. Kind 15 files go through middleware and `handle()`. Duplicate or unsupported kind scopes are rejected. Same-type scopes are alternatives; different scope types combine. Scope checks use the authenticated rumor/public event and actual source relay, never configured-relay membership as proof of provenance. Registration/publication and routing use the same scopes.
|
|
25
28
|
|
|
26
29
|
Public invocation must start at content index zero. Either `/ping@npub...` or `/ping@nostr:npub...` explicitly selects the bot; no `p` tag is required. An unqualified `/ping` is accepted only when the distinct lowercase `p` targets consist solely of this bot. A conflicting qualifier remains rejected even with the bot's `p` tag. An ordinary structural reply or mention is never an invocation. These stricter public targeting rules are Chirli policy; NIP-CD itself permits multiple executors to match an unqualified invocation. Public `handle()`/middleware runs only for admitted registered invocations, not arbitrary notes. DM fallback behavior is unchanged.
|
|
27
30
|
|
|
28
|
-
Signatures,
|
|
31
|
+
Signatures, kind, structural references, source, invocation and scopes are checked before the SDK atomically claims the signed event ID. Own public events are ignored. Access middleware runs after the claim and receives a detached copy of the verified input. Commands can additionally use `authorize`.
|
|
29
32
|
|
|
30
33
|
## Shared context and privacy
|
|
31
34
|
|
|
32
|
-
`ctx.input` contains `{id,sender,createdAt,text,event}`. `createdAt` is Nostr seconds. `event` is the authenticated decrypted kind 14 rumor for DMs, or the signature-verified raw public event. Anonymous gift-wrap keys are never exposed as the sender.
|
|
35
|
+
`ctx.input` contains `{id,sender,createdAt,kind,text,event}`. `createdAt` is Nostr seconds. `event` is the authenticated decrypted kind 14 or 15 rumor for DMs, or the signature-verified raw public event. A kind-15 input also has `file` and empty `text`. [Receiving private files](API.md#receive-and-download-a-private-file) Anonymous gift-wrap keys are never exposed as the sender.
|
|
33
36
|
|
|
34
37
|
`ctx.reply(text)` encrypts a DM when the input is private. For public inputs it signs kind 1111 with uppercase root scope and lowercase direct parent references, including mixed legacy kind 1/comment ancestry. Only the root author and direct parent author are copied. Missing/malformed legacy roots cause an error instead of a guessed attachment. An explicit modern root is preserved as declared in the signed comment; this does not prove the root's availability or truthfulness. A relay ACK means relay acceptance, never delivery or reading.
|
|
35
38
|
|
|
36
39
|
`ctx.replyFile(bytes, options?)` follows the same kind-1111 threading rules. It publishes the file URL and `imeta`; the bytes are uploaded **without encryption** for public input. The same call on a DM instead uploads ciphertext and replies with a kind-15 DM. Use `bot.replyFile(ctx.input.event, bytes, options?)` for delayed replies.
|
|
37
40
|
|
|
38
|
-
|
|
41
|
+
`ctx.react(reaction?)` signs a public [NIP-25](https://nips.nostr.com/25) kind-7 reaction. It references the target ID with an `e` tag and the target author with a `p` tag; kind-1111 targets also have a `k` tag. Omitting the reaction sends `+` (like). For a private input the same call sends an encrypted kind-7 rumor.
|
|
42
|
+
|
|
43
|
+
Public replies and reactions use configured `writeRelays` plus the configured inbox relay that supplied the input. Untrusted relay hints in tags do not initiate contacts; automatic destination-author relay discovery is not implemented. DM send options are rejected for public replies.
|
|
39
44
|
|
|
40
45
|
`ctx.session` uses separate `public:` thread keys for public input. Default storage namespaces also separate it from private peer sessions. A custom session store receives those prefixed keys and must preserve their separation and account isolation. Legacy unmarked chains may have an intermediate declared root and consequently a different session key until the application chooses a canonical key. Sessions and external side effects are not atomic with business completion.
|
|
41
46
|
|
|
42
|
-
|
|
47
|
+
The handler context has the same fields and methods for both kinds of input. Use `ctx.input` for the current input and `ctx.thread()` for preceding context. `bot.getMessage`, `bot.dmHistory`, `bot.observe`, message listing/state and `bot.send` remain private-message APIs.
|
|
43
48
|
|
|
44
49
|
## Lazy ancestor context
|
|
45
50
|
|
|
46
51
|
```ts
|
|
47
|
-
bot.command(
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
+
bot.command(
|
|
53
|
+
{ command: "summarize", scopes: ["kind:14", "kind:1", "kind:1111"] },
|
|
54
|
+
async (ctx) => {
|
|
55
|
+
const result = await ctx.thread({ limit: 30 });
|
|
56
|
+
const reply = await applicationProcessor(result.entries, {
|
|
57
|
+
complete: result.complete,
|
|
58
|
+
});
|
|
59
|
+
await ctx.reply(reply);
|
|
60
|
+
},
|
|
61
|
+
);
|
|
52
62
|
```
|
|
53
63
|
|
|
54
64
|
No history is sent anywhere automatically. `applicationProcessor` belongs to your application. The offline demo uses a deterministic mock.
|
|
@@ -59,20 +69,20 @@ No history is sent anywhere automatically. `applicationProcessor` belongs to you
|
|
|
59
69
|
- Public input batches its known root: the root event, kind 1 `#e` and kind 1111 `#E`, plus coordinate `#a`/`#A` variants where applicable. Only the current ancestor path is selected, never siblings or descendants. Legacy marked and positional references are supported; marked mentions and embedded NIP-19 quotes are excluded from positional topology. Missing ancestors use bounded targeted lookups. Modern address parents with an exact event ID resolve that version.
|
|
60
70
|
- Missing ancestors, inconsistent roots, timeouts, query windows, cycles and entry/size/depth/lookup bounds produce incomplete results with a reason. Defaults: 3000 ms total, 500 verified events, 16 queries, 64 ancestor steps. The total timer returns without waiting for an unresponsive custom query; the Transport interface cannot abort acquired queries. Built-in transport operations retain their own finite budgets and are closed with owned resources. A complete ancestor chain means those signed references resolved within the window, not complete relay history or global availability.
|
|
61
71
|
|
|
62
|
-
##
|
|
72
|
+
## Claims and outgoing retries
|
|
63
73
|
|
|
64
|
-
|
|
74
|
+
The internal SQLite store claims eligible public IDs before middleware. Public input bodies, relay provenance and pending/failed callback work are not retained; the private `MessageStorage` is not involved. Eligible historical IDs are also claimed without running commands. Offline-gap commands received as history are not executed later as live duplicates.
|
|
65
75
|
|
|
66
|
-
Live
|
|
76
|
+
Live attempts are serial per declared public root, and different roots can proceed concurrently. Returning early, failure or restart does not reopen a claim. A crash can interrupt an attempt or occur before its callback starts. Public replies and reactions use an independent outbox: after signing they are stored before publication, and `flushOutbox()` and reconnect retry the same signed event ID. Applications own any durable business jobs and idempotency.
|
|
67
77
|
|
|
68
|
-
##
|
|
78
|
+
## Command definitions and references
|
|
69
79
|
|
|
70
|
-
|
|
80
|
+
For a private command use `command({command:'ping',scopes:['kind:14']},handler)`. For trailing text declare `args:z.object({text:z.string().optional().meta({label:'Text',nipcdType:'text'})})`. Custom command identifiers are rejected; `d` is the command name. Renames are removal plus addition. Foreign protocol definitions retain their actual `d` values when decoded.
|
|
71
81
|
|
|
72
82
|
References: [NIP-22](https://nips.nostr.com/22), [NIP-CD draft](https://github.com/nostr-protocol/nips/blob/master/CD.md), and read-only review of Jumble's MIT-licensed structural/thread/routing patterns. No running Jumble device or public relay interoperability is covered by local tests.
|
|
73
83
|
|
|
74
84
|
## Application-owned delayed replies
|
|
75
85
|
|
|
76
|
-
|
|
86
|
+
Retain `ctx.input.event` to call `bot.reply(event,text)`, `bot.react(event,reaction?)` or `bot.thread(event,options)` after the handler finishes. Keep the full signed public event, not its ID. The SDK stores no incoming public body. Reverification is mandatory. A delayed reply or reaction uses configured write relays only; an immediate handler action can also use its configured source relay. Relay hints are never inferred from event tags. DM calls require the matching authenticated incoming record in the same account/mode store and protect the retained plaintext event. See [the shared API and offline example](API.md#replies-and-context-after-a-handler).
|
|
77
87
|
|
|
78
88
|
Public admission checks only a registered command head, verified target and scopes before enqueueing. NIP-CD argument decoding and Zod validation happen after middleware. This permits centralized invalid-argument handling without subscribing to arbitrary event handlers. History/replayed IDs still never run validation/error callbacks. An args-dependent authorize callback suppresses malformed-input error callbacks because no valid arguments exist to authorize a response. See [Zod arguments](API.md#zod-command-arguments).
|
package/docs/RECOVERY.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Reconnect and history recovery
|
|
2
2
|
|
|
3
|
-
The Bot manages one inbox subscription per DM relay. Each reconnects independently and can
|
|
3
|
+
The Bot manages one inbox subscription per DM relay. Each reconnects independently and can scan for missed DMs and outgoing self copies. Eligible incoming DMs recovered from a relay use the same middleware and handlers as live delivery, without retrying a previously claimed input.
|
|
4
4
|
|
|
5
5
|
## Defaults and configuration
|
|
6
6
|
|
|
@@ -25,13 +25,15 @@ Set `reconnect: false` to disable automatic reconnect. Set `recovery: false` to
|
|
|
25
25
|
|
|
26
26
|
## What a recovery pass does
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
When a relay has no checkpoint, its next scan starts at the Bot’s persisted first activation minus the configured overlap. Later passes start at that relay’s saved checkpoint minus the overlap. Scan bounds filter the outer giftwrap’s timestamp, not the inner DM timestamp. Each pass fixes its upper bound before querying; only a complete pass advances the checkpoint. Checkpoints are scoped to the account, mode and relay.
|
|
29
29
|
|
|
30
30
|
Pagination includes the oldest returned second in the next request. If a full page cannot move past that boundary, the pass reports `boundary-overflow`. Query failures, page limits and boundary overflow leave the checkpoint unchanged. A retry can read earlier pages again. Deduplication uses the decrypted message ID.
|
|
31
31
|
|
|
32
32
|
### Live messages and recovered history
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
The SDK saves the first DM activation time per bot public key and database before opening its DM inbox. It is reused on subsequent starts. After verification, the SDK discards both incoming DMs and outgoing self copies whose inner rumor timestamp is older than that time. A valid `ms` tag gives millisecond precision; when absent or unusable, a rumor in the same whole second as activation is eligible. Sender clocks can differ.
|
|
35
|
+
|
|
36
|
+
Once eligible, an incoming DM goes through the same ID claim, middleware and routing whether it arrived live, before EOSE, or in a catch-up query. Failed or denied inputs stay claimed. A later duplicate never reruns the handler. Eligible outgoing self copies can populate local history without middleware. Public command subscriptions keep their separate live/history rules.
|
|
35
37
|
|
|
36
38
|
## Trigger and inspect recovery
|
|
37
39
|
|
|
@@ -48,10 +50,10 @@ Call `syncHistory()` on a running Bot. It returns one result per DM relay with i
|
|
|
48
50
|
| `aborted` | The pass was interrupted or its replica was unavailable |
|
|
49
51
|
| `disabled` | Additional recovery paging is disabled |
|
|
50
52
|
|
|
51
|
-
Concurrent calls share a relay's active pass. Local `
|
|
53
|
+
Concurrent calls share a relay's active pass. Local `bot.dmHistory()` always reports `coverage: 'local-only'` and `complete: false`. Recovery is bounded and requires the keys needed to decrypt each message. See [key retention](KEYS.md#legacy-count-and-expiration).
|
|
52
54
|
|
|
53
55
|
## Startup and retries
|
|
54
56
|
|
|
55
|
-
Startup waits for at least one inbox replica to finish its initial read window (real EOSE or the long-lived inbox fallback) and finish its initial recovery attempt. This initialization gate is separate from physical WebSocket connection health. An incomplete recovery can still leave the Bot ready. Reconnected subscriptions retry pending outbox envelopes with their original ciphertext, IDs and targets. The SDK retries on startup and reconnect, and the live runner also has a periodic [retry timer](https://github.com/CodyTseng/chirli/blob/main/examples/live/README.md).
|
|
57
|
+
Startup waits for at least one inbox replica to finish its initial read window (real EOSE or the long-lived inbox fallback) and finish its initial recovery attempt. This initialization gate is separate from physical WebSocket connection health. An incomplete recovery can still leave the Bot ready. Reconnected subscriptions retry pending outbox envelopes with their original ciphertext, IDs and targets. The SDK retries that outgoing work on startup and reconnect, and the live runner also has a periodic [retry timer](https://github.com/CodyTseng/chirli/blob/main/examples/live/README.md).
|
|
56
58
|
|
|
57
59
|
An established replica's transient network failures get a 30-second recovery window before `onError()` reports one warning for the outage. Initial failures, explicit protocol rejections and history errors are reported immediately. `stop()` and `close()` cancel reconnect demand, delayed warnings and in-progress recovery. See [relays](RELAYS.md) for timeouts and diagnostics.
|
package/docs/RELAYS.md
CHANGED
|
@@ -5,9 +5,9 @@ Set each relay role independently. The common `relays` option supplies any role
|
|
|
5
5
|
```ts
|
|
6
6
|
const bot = new Bot({
|
|
7
7
|
signer,
|
|
8
|
-
dmRelays: [
|
|
9
|
-
readRelays: [
|
|
10
|
-
writeRelays: [
|
|
8
|
+
dmRelays: ["wss://inbox.example"],
|
|
9
|
+
readRelays: ["wss://read.example"],
|
|
10
|
+
writeRelays: ["wss://write.example"],
|
|
11
11
|
});
|
|
12
12
|
await bot.start();
|
|
13
13
|
```
|
|
@@ -89,13 +89,13 @@ Physical connection health, subscription usability and initial read completion a
|
|
|
89
89
|
|
|
90
90
|
Failed subscription attempts are removed immediately and late callbacks are fenced. With `reconnect:false`, no background retry is scheduled. If all public replicas later become unavailable, explicit `syncCommands()` starts a fresh same-kind attempt. Another usable replica is preserved, even if it is still awaiting its initial read completion. Automatic reconnect remains the default and repairs replica demand independently with the existing backoff.
|
|
91
91
|
|
|
92
|
-
Initial
|
|
92
|
+
Initial reads and reconnect scans can deliver DMs at or after first activation through the same middleware and router as live DMs. They can also restore eligible outgoing self copies and retry pending outgoing publications. They never rerun a previously claimed business input. Stop fences delayed recovery and cancels reconnect demand.
|
|
93
93
|
|
|
94
94
|
### Relays that omit EOSE
|
|
95
95
|
|
|
96
96
|
Only long-lived DM and public inbox subscriptions in the built-in transport use a local read-window fallback. After the socket opens and REQ is sent, `eoseTimeoutMs` without EOSE completes that subscription's initial window locally. It neither sends an EOSE frame nor claims the relay sent one. Pending AUTH, CLOSED and disconnect still fail through their normal paths. Real EOSE and local completion settle initialization at most once; real EOSE can still arrive later and restore normal live classification.
|
|
97
97
|
|
|
98
|
-
Before real EOSE, frames remain transport history and carry an internal local boundary. The verified public-input layer allows execution only when the signed event's `created_at` is strictly later than that boundary.
|
|
98
|
+
Before real EOSE, frames remain transport history and carry an internal local boundary. The verified public-input layer allows execution only when the signed event's `created_at` is strictly later than that boundary. DM business admission is independent of EOSE and uses the verified inner rumor timestamp relative to persisted first activation. The backdated giftwrap timestamp only selects relay query windows. Signature, authenticated identity, scope and deduplication still apply.
|
|
99
99
|
|
|
100
100
|
This is degraded compatibility, not proof of message ordering: signed timestamps are sender-controlled, clocks can differ, future-dated old messages may pass, and new messages from a slow clock may remain history. Real EOSE behavior is unchanged. Applications requiring a reliable history/live boundary should choose relays that provide EOSE.
|
|
101
101
|
|
|
@@ -112,7 +112,7 @@ Read-only source review informed these changes; application state/UI code was no
|
|
|
112
112
|
| Jumble `src/lib/relay-pool-lifecycle.ts` | Browser online/resume hints trigger health checks | DOM/UI hooks are not copied into the headless SDK; applications own process lifecycle |
|
|
113
113
|
| PsstPsst `src/services/relay/managed-relay-pool.ts` | Per-relay physical generations, demand-driven retry with jitter, replay, idle release and current subscription status | Existing pooled transport, AUTH replay, per-replica retry, quiet transient diagnostics and stop cancellation remain |
|
|
114
114
|
| PsstPsst `src/services/relay/lifecycle-relay.ts` | Failed REQ/AUTH writes retire an unusable socket rather than leave orphan demand | Chirli's existing socket-failure path and transport leases remain responsible for write/disconnect signaling |
|
|
115
|
-
| PsstPsst `src/services/dm/gift-wrap-pager.ts`, `src/services/dm/dm.service.ts` | Distinguish first readiness from reconnect; bounded, epoch-fenced history recovery |
|
|
115
|
+
| PsstPsst `src/services/dm/gift-wrap-pager.ts`, `src/services/dm/dm.service.ts` | Distinguish first readiness from reconnect; bounded, epoch-fenced history recovery | Recovered DMs since first activation can dispatch once; public subscription readiness and outgoing retries are separate |
|
|
116
116
|
|
|
117
117
|
Chirli already has independent connect/EOSE/ACK/AUTH deadlines, ping/pong half-open detection, pooled connections, stable-period backoff reset and bounded per-relay DM recovery. This change does not add a second connection manager or mobile foreground/background pause policy. Inbox initialization requires a completed initial window and a settled bounded recovery attempt; neither implies a complete relay archive or confirmed recipient delivery. Long-running production outages, OS sleep/network changes, proxies and real external relays still require deployment validation; local tests use disposable identities and memory/loopback relays only.
|
|
118
118
|
|
package/docs/SESSIONS.md
CHANGED
|
@@ -5,22 +5,22 @@ Use `ctx.session` to keep business state between messages in the same DM convers
|
|
|
5
5
|
## Use the default SQLite storage
|
|
6
6
|
|
|
7
7
|
```ts
|
|
8
|
-
import { Bot } from
|
|
8
|
+
import { Bot } from "chirli";
|
|
9
9
|
|
|
10
10
|
const bot = new Bot<{ visits: number }>({
|
|
11
11
|
signer,
|
|
12
|
-
database:
|
|
12
|
+
database: "./bot.sqlite",
|
|
13
13
|
});
|
|
14
14
|
|
|
15
|
-
bot.command({ command:
|
|
16
|
-
const visits = (await ctx.session.getItem(
|
|
17
|
-
ctx.session.setItem(
|
|
15
|
+
bot.command({ command: "visit", scopes: ["kind:14"] }, async (ctx) => {
|
|
16
|
+
const visits = ((await ctx.session.getItem("visits")) ?? 0) + 1;
|
|
17
|
+
ctx.session.setItem("visits", visits);
|
|
18
18
|
await ctx.reply(`Visit ${visits}`);
|
|
19
19
|
});
|
|
20
20
|
|
|
21
|
-
bot.command({ command:
|
|
21
|
+
bot.command({ command: "reset", scopes: ["kind:14"] }, async (ctx) => {
|
|
22
22
|
ctx.session.clear();
|
|
23
|
-
await ctx.reply(
|
|
23
|
+
await ctx.reply("Session reset.");
|
|
24
24
|
});
|
|
25
25
|
|
|
26
26
|
await bot.start();
|
|
@@ -35,7 +35,7 @@ The type argument checks keys and value types. Supply a default where you read a
|
|
|
35
35
|
| `ctx.session.removeItem(key)` | Stage deletion of one key. |
|
|
36
36
|
| `ctx.session.clear()` | Reset the current conversation. Later writes in the same message become the new snapshot. |
|
|
37
37
|
|
|
38
|
-
Middleware and the chosen command or text handler share the same session for the current message. Successful processing commits changes once. If processing throws before the commit, the staged changes are discarded. If a custom store fails during
|
|
38
|
+
Middleware and the chosen command or text handler share the same session for the current message. Successful processing commits changes once. If processing throws before the commit, the staged changes are discarded. If a custom store fails during commit, the error is reported and the SDK does not rerun the callback. A reply or other effect that already succeeded is not rolled back.
|
|
39
39
|
|
|
40
40
|
## Use a custom session store
|
|
41
41
|
|
|
@@ -44,12 +44,12 @@ Pass `sessionStore` to `new Bot()` to choose where business sessions are saved.
|
|
|
44
44
|
The following example uses an application-owned SQLite file for a Bot whose session stores a visit count. The `signer` is the one configured for your Bot.
|
|
45
45
|
|
|
46
46
|
```ts
|
|
47
|
-
import { DatabaseSync } from
|
|
48
|
-
import { Bot, type SessionStore } from
|
|
47
|
+
import { DatabaseSync } from "node:sqlite";
|
|
48
|
+
import { Bot, type SessionStore } from "chirli";
|
|
49
49
|
|
|
50
50
|
type State = { visits: number };
|
|
51
51
|
|
|
52
|
-
const db = new DatabaseSync(
|
|
52
|
+
const db = new DatabaseSync("./my-sessions.sqlite");
|
|
53
53
|
db.exec(`
|
|
54
54
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
55
55
|
conversation TEXT PRIMARY KEY,
|
|
@@ -57,7 +57,7 @@ db.exec(`
|
|
|
57
57
|
) STRICT
|
|
58
58
|
`);
|
|
59
59
|
|
|
60
|
-
const read = db.prepare(
|
|
60
|
+
const read = db.prepare("SELECT snapshot FROM sessions WHERE conversation = ?");
|
|
61
61
|
const write = db.prepare(`
|
|
62
62
|
INSERT INTO sessions (conversation, snapshot) VALUES (?, ?)
|
|
63
63
|
ON CONFLICT(conversation) DO UPDATE SET snapshot = excluded.snapshot
|
|
@@ -67,15 +67,19 @@ const sessionStore: SessionStore<State> = {
|
|
|
67
67
|
get(conversation) {
|
|
68
68
|
const row = read.get(conversation);
|
|
69
69
|
if (row === undefined) return undefined;
|
|
70
|
-
if (typeof row.snapshot !==
|
|
70
|
+
if (typeof row.snapshot !== "string")
|
|
71
|
+
throw new Error("Invalid session snapshot");
|
|
71
72
|
|
|
72
73
|
const value: unknown = JSON.parse(row.snapshot);
|
|
73
|
-
if (!value || typeof value !==
|
|
74
|
-
throw new Error(
|
|
74
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
75
|
+
throw new Error("Invalid session snapshot");
|
|
75
76
|
}
|
|
76
|
-
if (!(
|
|
77
|
-
if (
|
|
78
|
-
|
|
77
|
+
if (!("visits" in value)) return {};
|
|
78
|
+
if (
|
|
79
|
+
typeof value.visits !== "number" ||
|
|
80
|
+
!Number.isSafeInteger(value.visits)
|
|
81
|
+
) {
|
|
82
|
+
throw new Error("Invalid session count");
|
|
79
83
|
}
|
|
80
84
|
return { visits: value.visits };
|
|
81
85
|
},
|
|
@@ -85,9 +89,9 @@ const sessionStore: SessionStore<State> = {
|
|
|
85
89
|
};
|
|
86
90
|
|
|
87
91
|
const bot = new Bot({ signer, sessionStore });
|
|
88
|
-
bot.command({ command:
|
|
89
|
-
const visits = (await ctx.session.getItem(
|
|
90
|
-
ctx.session.setItem(
|
|
92
|
+
bot.command({ command: "visit", scopes: ["kind:14"] }, async (ctx) => {
|
|
93
|
+
const visits = ((await ctx.session.getItem("visits")) ?? 0) + 1;
|
|
94
|
+
ctx.session.setItem("visits", visits);
|
|
91
95
|
await ctx.reply(`Visit ${visits}`);
|
|
92
96
|
});
|
|
93
97
|
await bot.start();
|
package/docs/SIGNERS.md
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
Create a Bot with a signer. Local nsec and remote bunker credentials use the same API; application handlers never inspect the signing backend.
|
|
4
4
|
|
|
5
5
|
```ts
|
|
6
|
-
import { Bot, nsecSigner, bunkerSigner } from
|
|
6
|
+
import { Bot, nsecSigner, bunkerSigner } from "chirli";
|
|
7
7
|
|
|
8
8
|
const signer = nsecSigner(nsecFromYourSecretManager);
|
|
9
9
|
// Alternatively: const signer = bunkerSigner(bunkerUri, { clientSecret: bunkerClientKeyFromYourSecretManager });
|
|
10
10
|
const bot = new Bot({
|
|
11
11
|
signer,
|
|
12
|
-
database:
|
|
12
|
+
database: "./inbox.sqlite",
|
|
13
13
|
});
|
|
14
14
|
await bot.start();
|
|
15
15
|
console.log(bot.pubkey);
|
|
@@ -37,7 +37,9 @@ The application always owns the signer. Bot never calls its optional `close()`,
|
|
|
37
37
|
## Remote bunker
|
|
38
38
|
|
|
39
39
|
```ts
|
|
40
|
-
const signer = bunkerSigner(bunkerUri, {
|
|
40
|
+
const signer = bunkerSigner(bunkerUri, {
|
|
41
|
+
clientSecret: bunkerClientKeyFromYourSecretManager,
|
|
42
|
+
});
|
|
41
43
|
```
|
|
42
44
|
|
|
43
45
|
A bunker URI identifies the service key. Chirli resolves the account key through NIP-46 and checks it on reconnect. A timed-out operation discards the connection. Later requests can reconnect using the same client key.
|
package/docs/STORAGE.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Message storage
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Retained private messages and their diagnostic states belong to `MessageStorage`. The first DM activation timestamp, atomic inbound ID claims, outbox, keys, peer evidence, declarations, sessions and relay checkpoints stay in internal SQLite. Internal persistence accepts only a `database` path; its backend cannot be replaced.
|
|
4
4
|
|
|
5
5
|
Business conversation state uses `ctx.session`. A Bot can supply a `sessionStore` for that state. Internal sessions used by the framework stay in SQLite. See the [session guide and custom store example](SESSIONS.md#use-a-custom-session-store).
|
|
6
6
|
|
|
@@ -9,12 +9,12 @@ Business conversation state uses `ctx.session`. A Bot can supply a `sessionStore
|
|
|
9
9
|
Bot uses `sqliteMessageStorage` by default, with message records in the same database file as the internal tables. `:memory:` keeps both stores in memory. To choose a separate message database:
|
|
10
10
|
|
|
11
11
|
```ts
|
|
12
|
-
import { Bot, sqliteMessageStorage } from
|
|
12
|
+
import { Bot, sqliteMessageStorage } from "chirli";
|
|
13
13
|
|
|
14
|
-
const messages = sqliteMessageStorage(
|
|
14
|
+
const messages = sqliteMessageStorage("./messages.sqlite");
|
|
15
15
|
const bot = new Bot({
|
|
16
16
|
signer,
|
|
17
|
-
database:
|
|
17
|
+
database: "./internal.sqlite",
|
|
18
18
|
storageKey,
|
|
19
19
|
messageStorage: messages,
|
|
20
20
|
});
|
|
@@ -27,7 +27,7 @@ try {
|
|
|
27
27
|
}
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
-
Bot closes its default message backend. Close an injected backend after closing the Bot. Preserve
|
|
30
|
+
Bot closes its default message backend. Close an injected backend after closing the Bot. Use fresh database paths for this pre-release storage format, including for any separate history database. Earlier files are unsupported; no migration is provided. Leave them in place if you want to keep them. Preserve the new databases and any storage key across restarts.
|
|
31
31
|
|
|
32
32
|
## Three-method interface
|
|
33
33
|
|
|
@@ -39,24 +39,24 @@ interface MessageStorage {
|
|
|
39
39
|
}
|
|
40
40
|
```
|
|
41
41
|
|
|
42
|
-
Each entry contains `id`, `conversation`, millisecond `timestamp`, opaque `payload`, and `state`. The SDK handles payload encryption and decoding.
|
|
42
|
+
Each entry contains `id`, `conversation`, millisecond `timestamp`, opaque `payload`, and `state`. The SDK handles payload encryption and decoding. These are diagnostic fields on conversation records, not a work queue. An admitted live message can be `processing`, `failed` or `done`. Outgoing and self-copy messages need no incoming handler.
|
|
43
43
|
|
|
44
|
-
- `insert` must atomically insert once by account + ID. Return false on duplicates, preserving the existing payload and state. This
|
|
44
|
+
- `insert` must atomically insert once by account + ID. Return false on duplicates, preserving the existing payload and state. This deduplicates storage writes; the prior ID claim in internal SQLite separately controls callback eligibility.
|
|
45
45
|
- `updateState` durably changes only an existing record's state, scoped by account + ID. It must not create a missing message.
|
|
46
|
-
- `query` returns detached records. Optional filters are exact `id`, exact `conversation`, and any of `states`; an empty state array matches nothing. `limit` bounds the result, including zero
|
|
46
|
+
- `query` returns detached records. Optional filters are exact `id`, exact `conversation`, and any of `states`; an empty state array matches nothing. `limit` bounds the result, including zero.
|
|
47
47
|
- `order` defaults to `oldest` (timestamp ASC, ID ASC). `newest` uses timestamp DESC, ID ASC; `recovery` uses timestamp ASC, ID DESC. The optional `{timestamp, id}` cursor is exclusive in that order.
|
|
48
|
-
- Implement filtering, ordering, cursors and limits in the database. Queries
|
|
48
|
+
- Implement filtering, ordering, cursors and limits in the database. Queries by exact ID, conversation or diagnostic state should use indexes.
|
|
49
49
|
- All methods are synchronous and durable on return. Promise-returning methods are unsupported.
|
|
50
50
|
|
|
51
|
-
History, `getMessage`, `listMessages
|
|
51
|
+
History, `getMessage`, `listMessages` and `getMessageState` use this backend. A claimed ID need not have a history entry. An eligible incoming DM, including one recovered from a relay, is saved only when middleware reaches routing. Pre-activation DMs are ignored and short-circuited DMs retain only their ID claim. No inbound claim, outbox, keyring or metadata interface is required from custom implementations.
|
|
52
52
|
|
|
53
53
|
## Failures and restart
|
|
54
54
|
|
|
55
|
-
For cross-store writes, internal SQLite first commits a temporary message handoff with the corresponding peer metadata or exact outgoing outbox bundle. Only then does the SDK insert the message into `MessageStorage`. Successful insertion removes the temporary record. A crash or uncertain insert can repeat insertion, so duplicates must never reset an existing
|
|
55
|
+
For cross-store writes, internal SQLite first commits a temporary message handoff with the corresponding peer metadata or exact outgoing outbox bundle. Only then does the SDK insert the message into `MessageStorage`. Successful insertion removes the temporary record. A crash or uncertain insert can repeat insertion, so duplicates must never reset an existing diagnostic state. This repairs storage only, not a handler attempt.
|
|
56
56
|
|
|
57
|
-
A failed insert
|
|
57
|
+
A failed insert can leave a durable handoff for storage recovery. Recovering that record later does not call middleware or handlers. A send may fail after committing its exact outbox bundle. Use `flushOutbox()` to retry that bundle. A new `send()` creates a new message.
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
An error in a handler or state write does not reopen the ID claim. Keep the internal database as well as any injected history backend across restarts. To retry business effects, persist and operate your own jobs. One active Bot/process per account database is supported.
|
|
60
60
|
|
|
61
61
|
## SQLite and encryption
|
|
62
62
|
|
|
@@ -64,8 +64,8 @@ Successful handling writes done to the message backend. A state-write failure le
|
|
|
64
64
|
|
|
65
65
|
`storageKey` encrypts payloads with AES-GCM before storage. Without it, payloads use tagged plaintext. Routing metadata and states remain visible. Preserve the original key; missing/wrong keys fail rather than resetting data.
|
|
66
66
|
|
|
67
|
-
The `JsonMessageStorage` demo shows
|
|
67
|
+
The `JsonMessageStorage` demo shows these operations for small files using an in-memory scan. Run `npm run example:storage` from the GitHub checkout to verify custom message history and internal session recovery after restart. [JsonMessageStorage example](https://github.com/CodyTseng/chirli/blob/main/examples/_json-storage.ts)
|
|
68
68
|
|
|
69
69
|
## Public command journal
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
Public inputs retain canonical ID claims, not a history, incoming body or queued callback payload. Signed outgoing public replies and reactions share a durable public outbox with exact-ID retries. Neither uses the replaceable DM MessageStorage. Default public sessions use a separate namespace. Custom SessionStore implementations must preserve public/private and account key separation. The selected storage codec applies to public outbox and session values. See [public claims and outgoing retries](PUBLIC.md#claims-and-outgoing-retries).
|
package/docs/TUTORIAL.md
CHANGED
|
@@ -21,13 +21,13 @@ On first launch the runner creates credentials beside `.chirli/bot.sqlite`. Late
|
|
|
21
21
|
Add this import at the top of `examples/live/commands.ts`:
|
|
22
22
|
|
|
23
23
|
```ts
|
|
24
|
-
import { npubEncode } from
|
|
24
|
+
import { npubEncode } from "nostr-tools/nip19";
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
Register the command inside the existing `runLive` callback:
|
|
28
28
|
|
|
29
29
|
```ts
|
|
30
|
-
bot.command({ command:
|
|
30
|
+
bot.command({ command: "hello", scopes: ["kind:14"] }, async (ctx) => {
|
|
31
31
|
await ctx.reply(`Hello, nostr:${npubEncode(ctx.sender)}!`);
|
|
32
32
|
});
|
|
33
33
|
```
|
|
@@ -48,47 +48,57 @@ The `runLive` helper selects a signer, constructs and starts a Bot, prints readi
|
|
|
48
48
|
The existing live commands example already imports z from zod; keep that import once. Add only these imports:
|
|
49
49
|
|
|
50
50
|
```ts
|
|
51
|
-
import {InvalidArgsError} from
|
|
52
|
-
import {randomInt} from
|
|
51
|
+
import { InvalidArgsError } from "chirli";
|
|
52
|
+
import { randomInt } from "node:crypto";
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
Inside the existing runLive callback, register shared error handling before the command:
|
|
56
56
|
|
|
57
57
|
```ts
|
|
58
58
|
bot.use(async (ctx, next) => {
|
|
59
|
-
try {
|
|
60
|
-
|
|
59
|
+
try {
|
|
60
|
+
await next();
|
|
61
|
+
} catch (error) {
|
|
61
62
|
if (!(error instanceof InvalidArgsError)) throw error;
|
|
62
|
-
await ctx.reply(
|
|
63
|
+
await ctx.reply("Usage: /roll <1..20>");
|
|
63
64
|
}
|
|
64
65
|
});
|
|
65
66
|
|
|
66
|
-
bot.command(
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
67
|
+
bot.command(
|
|
68
|
+
{
|
|
69
|
+
command: "roll",
|
|
70
|
+
scopes: ["kind:14"],
|
|
71
|
+
args: z.object({
|
|
72
|
+
sides: z.bigint().min(1n).max(20n).meta({ label: "Sides" }),
|
|
73
|
+
}),
|
|
74
|
+
},
|
|
75
|
+
async (ctx, args) => {
|
|
76
|
+
// Both entry points contain the same validated output.
|
|
77
|
+
const rolled = randomInt(1, Number(ctx.args.sides) + 1);
|
|
78
|
+
await ctx.reply(`Rolled ${rolled} on a ${args.sides}-sided die.`);
|
|
79
|
+
},
|
|
80
|
+
);
|
|
74
81
|
```
|
|
75
82
|
|
|
76
83
|
Rebuild and restart, then send `/roll 6`: the reply is `Rolled N on a 6-sided die.`, with N in 1..6. `/roll`, `/roll invalid` and `/roll 21` each produce `Usage: /roll <1..20>` from the shared middleware, never the command handler. Arguments are decoded by NIP-CD before Zod runs; number tokens produce bigint. No response or retry is added when no error handler is configured. Plain fallback does not receive invalid arguments for a recognized, correctly targeted/scoped command.
|
|
77
84
|
|
|
78
85
|
Only command handlers have typed ctx.args; middleware uses the ordinary context before validation and sees no args after next returns. Use `.meta({nipcdType:'text'})` for a final free-text string; plain strings are words. See [schema support](API.md#zod-command-arguments) for optional/address fields and unsupported transforms. To run these valid/invalid examples without any external connection, build and run `npm run example:commands`; its /roll handler uses the same schema and middleware.
|
|
79
86
|
|
|
80
|
-
For commands with args-dependent authorize, invalid input is silently terminated: an invalid request cannot authorize a usage reply. A validator exception before authorization bypasses reply-capable middleware/catch observers and reaches operational onError
|
|
87
|
+
For commands with args-dependent authorize, invalid input is silently terminated: an invalid request cannot authorize a usage reply. A validator exception before authorization bypasses reply-capable middleware/catch observers and reaches operational `onError` without a second processing attempt.
|
|
81
88
|
|
|
82
89
|
## 3. Persist conversation state
|
|
83
90
|
|
|
84
91
|
Use the conversation’s key-value storage through `ctx.session`. The handler supplies the default when a key is missing.
|
|
85
92
|
|
|
86
93
|
```ts
|
|
87
|
-
const bot = new Bot<{ visits: number }>({
|
|
94
|
+
const bot = new Bot<{ visits: number }>({
|
|
95
|
+
signer,
|
|
96
|
+
database: "./chirli.sqlite",
|
|
97
|
+
});
|
|
88
98
|
|
|
89
|
-
bot.command({ command:
|
|
90
|
-
const visits = (await ctx.session.getItem(
|
|
91
|
-
ctx.session.setItem(
|
|
99
|
+
bot.command({ command: "visit", scopes: ["kind:14"] }, async (ctx) => {
|
|
100
|
+
const visits = ((await ctx.session.getItem("visits")) ?? 0) + 1;
|
|
101
|
+
ctx.session.setItem("visits", visits);
|
|
92
102
|
await ctx.reply(`Visit ${visits}`);
|
|
93
103
|
});
|
|
94
104
|
|
|
@@ -104,12 +114,12 @@ Call `ctx.session.removeItem(key)` to delete one value or `ctx.session.clear()`
|
|
|
104
114
|
Register a handler for messages with no matching command:
|
|
105
115
|
|
|
106
116
|
```ts
|
|
107
|
-
bot.handle(async ctx => {
|
|
108
|
-
await ctx.reply(
|
|
117
|
+
bot.handle(async (ctx) => {
|
|
118
|
+
await ctx.reply("Message received");
|
|
109
119
|
});
|
|
110
120
|
```
|
|
111
121
|
|
|
112
|
-
Use `bot.use()` for shared middleware before routing.
|
|
122
|
+
Use `bot.use()` for shared middleware before routing. Use `observe()` for independent receipt monitoring. Observers do not determine processing success.
|
|
113
123
|
|
|
114
124
|
```ts
|
|
115
125
|
bot.catch((error, ctx) => {
|
|
@@ -117,15 +127,9 @@ bot.catch((error, ctx) => {
|
|
|
117
127
|
});
|
|
118
128
|
```
|
|
119
129
|
|
|
120
|
-
`Bot.catch()` observes session, middleware and business errors.
|
|
121
|
-
|
|
122
|
-
Inspect `bot.getMessageState(id)` or `bot.listMessages({ state: 'failed' })`. Retry from application management code, outside message handlers:
|
|
130
|
+
`Bot.catch()` observes session, middleware and business errors. No callback is retried by the SDK; the input ID stays claimed. Framework `InvalidArgsError` never reaches the business handler or plain fallback and is silent unless middleware or `bot.catch` handles it. For business work that must be retried, persist your own job using the input ID. For an already queued outgoing message, use `bot.flushOutbox()` to retry delivery of the same signed event.
|
|
123
131
|
|
|
124
|
-
|
|
125
|
-
await bot.retryInbox({ ids: [failedMessageId] });
|
|
126
|
-
```
|
|
127
|
-
|
|
128
|
-
Handlers are serial per conversation. Calling `idle()`, `retryInbox()`, `stop()` or `close()` from a handler would wait on itself and is rejected. Use `requestStop()` to request shutdown and drain from outside the handler.
|
|
132
|
+
See the [event processing flow](API.md#event-processing-flow) for what stops before routing and what can be retried. Handlers are serial per conversation. Calling `idle()`, `stop()` or `close()` from a handler would wait on itself and is rejected. Use `requestStop()` to request shutdown and drain from outside the handler.
|
|
129
133
|
|
|
130
134
|
## 5. Understand public command synchronization
|
|
131
135
|
|
|
@@ -133,18 +137,17 @@ All commands are public on configured write relays. Their definitions are synchr
|
|
|
133
137
|
|
|
134
138
|
- To remove a command, omit it from the complete registry and restart with the same account/relays; startup publishes the withdrawal. Runtime additions remain supported.
|
|
135
139
|
- Declare a typed argument schema in `command()` for typed arguments. Registration accepts an `authorize` callback.
|
|
136
|
-
-
|
|
140
|
+
- Register `bot.use(allowlist(pubkeys))` first to authorize live senders before later middleware and handlers.
|
|
137
141
|
- Use `discoverCommands()` to inspect metadata; discovery never installs handlers.
|
|
138
142
|
|
|
139
143
|
Commands are declared automatically as kind `31992`, with `d` derived from the command name. Withdrawals use kind `5`; user-installed kind `10992` lists are untouched. See [commands](NIP-CD.md) for the complete contract.
|
|
140
144
|
|
|
141
145
|
## 6. Move into your own application
|
|
142
146
|
|
|
143
|
-
|
|
147
|
+
Create a verified release tarball from this checkout.
|
|
144
148
|
|
|
145
149
|
```sh
|
|
146
|
-
npm run
|
|
147
|
-
npm pack --ignore-scripts
|
|
150
|
+
npm run pack:release
|
|
148
151
|
```
|
|
149
152
|
|
|
150
153
|
Install the resulting tarball in your ESM application, for example `npm install /absolute/path/to/chirli/chirli-0.1.0.tgz`. Import from `chirli`, without internal source paths.
|
|
@@ -152,16 +155,16 @@ Install the resulting tarball in your ESM application, for example `npm install
|
|
|
152
155
|
Construct the Bot, register handlers and await startup:
|
|
153
156
|
|
|
154
157
|
```ts
|
|
155
|
-
import { Bot, nsecSigner } from
|
|
158
|
+
import { Bot, nsecSigner } from "chirli";
|
|
156
159
|
|
|
157
160
|
const signer = nsecSigner(nsecFromYourSecretManager);
|
|
158
161
|
const bot = new Bot({
|
|
159
162
|
signer,
|
|
160
|
-
database:
|
|
163
|
+
database: "./chirli.sqlite",
|
|
161
164
|
});
|
|
162
165
|
|
|
163
|
-
bot.command({ command:
|
|
164
|
-
await ctx.reply(
|
|
166
|
+
bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
|
|
167
|
+
await ctx.reply("pong", { replyTo: ctx.input.id });
|
|
165
168
|
});
|
|
166
169
|
|
|
167
170
|
await bot.start();
|