@gakr-gakr/nostr 0.1.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/src/channel.ts ADDED
@@ -0,0 +1,215 @@
1
+ import { describeAccountSnapshot } from "autobot/plugin-sdk/account-helpers";
2
+ import {
3
+ createScopedDmSecurityResolver,
4
+ createTopLevelChannelConfigAdapter,
5
+ } from "autobot/plugin-sdk/channel-config-helpers";
6
+ import { createChatChannelPlugin } from "autobot/plugin-sdk/channel-core";
7
+ import { createChannelMessageAdapterFromOutbound } from "autobot/plugin-sdk/channel-message";
8
+ import {
9
+ buildPassiveChannelStatusSummary,
10
+ buildTrafficStatusSummary,
11
+ } from "autobot/plugin-sdk/extension-shared";
12
+ import { createComputedAccountStatusAdapter } from "autobot/plugin-sdk/status-helpers";
13
+ import {
14
+ buildChannelConfigSchema,
15
+ collectStatusIssuesFromLastError,
16
+ createDefaultChannelRuntimeState,
17
+ DEFAULT_ACCOUNT_ID,
18
+ formatPairingApproveHint,
19
+ type ChannelPlugin,
20
+ } from "./channel-api.js";
21
+ import type { NostrProfile } from "./config-schema.js";
22
+ import { NostrConfigSchema } from "./config-schema.js";
23
+ import {
24
+ getActiveNostrBuses,
25
+ nostrOutboundAdapter,
26
+ nostrPairingTextAdapter,
27
+ startNostrGatewayAccount,
28
+ } from "./gateway.js";
29
+ import { normalizePubkey } from "./nostr-key-utils.js";
30
+ import type { ProfilePublishResult } from "./nostr-profile.js";
31
+ import { resolveNostrOutboundSessionRoute } from "./session-route.js";
32
+ import { nostrSetupAdapter, nostrSetupWizard } from "./setup-surface.js";
33
+ import {
34
+ listNostrAccountIds,
35
+ resolveDefaultNostrAccountId,
36
+ resolveNostrAccount,
37
+ type ResolvedNostrAccount,
38
+ } from "./types.js";
39
+
40
+ const resolveNostrDmPolicy = createScopedDmSecurityResolver<ResolvedNostrAccount>({
41
+ channelKey: "nostr",
42
+ resolvePolicy: (account) => account.config.dmPolicy,
43
+ resolveAllowFrom: (account) => account.config.allowFrom,
44
+ policyPathSuffix: "dmPolicy",
45
+ defaultPolicy: "pairing",
46
+ approveHint: formatPairingApproveHint("nostr"),
47
+ normalizeEntry: (raw) => {
48
+ try {
49
+ return normalizePubkey(raw.trim().replace(/^nostr:/i, ""));
50
+ } catch {
51
+ return raw.trim();
52
+ }
53
+ },
54
+ });
55
+
56
+ const nostrConfigAdapter = createTopLevelChannelConfigAdapter<ResolvedNostrAccount>({
57
+ sectionKey: "nostr",
58
+ resolveAccount: (cfg) => resolveNostrAccount({ cfg }),
59
+ listAccountIds: listNostrAccountIds,
60
+ defaultAccountId: resolveDefaultNostrAccountId,
61
+ deleteMode: "clear-fields",
62
+ clearBaseFields: [
63
+ "name",
64
+ "defaultAccount",
65
+ "privateKey",
66
+ "relays",
67
+ "dmPolicy",
68
+ "allowFrom",
69
+ "profile",
70
+ ],
71
+ resolveAllowFrom: (account) => account.config.allowFrom,
72
+ formatAllowFrom: (allowFrom) =>
73
+ allowFrom
74
+ .map((entry) => String(entry).trim())
75
+ .filter(Boolean)
76
+ .map((entry) => {
77
+ if (entry === "*") {
78
+ return "*";
79
+ }
80
+ try {
81
+ return normalizePubkey(entry);
82
+ } catch {
83
+ return entry;
84
+ }
85
+ })
86
+ .filter(Boolean),
87
+ });
88
+
89
+ const nostrMessageAdapter = createChannelMessageAdapterFromOutbound({
90
+ id: "nostr",
91
+ outbound: nostrOutboundAdapter,
92
+ });
93
+
94
+ export const nostrPlugin: ChannelPlugin<ResolvedNostrAccount> = createChatChannelPlugin({
95
+ base: {
96
+ id: "nostr",
97
+ meta: {
98
+ id: "nostr",
99
+ label: "Nostr",
100
+ selectionLabel: "Nostr",
101
+ docsPath: "/channels/nostr",
102
+ docsLabel: "nostr",
103
+ blurb: "Decentralized DMs via Nostr relays (NIP-04)",
104
+ order: 100,
105
+ },
106
+ capabilities: {
107
+ chatTypes: ["direct"], // DMs only for MVP
108
+ media: false, // No media for MVP
109
+ },
110
+ reload: { configPrefixes: ["channels.nostr"] },
111
+ configSchema: buildChannelConfigSchema(NostrConfigSchema),
112
+ setup: nostrSetupAdapter,
113
+ setupWizard: nostrSetupWizard,
114
+ config: {
115
+ ...nostrConfigAdapter,
116
+ isConfigured: (account) => account.configured,
117
+ describeAccount: (account) =>
118
+ describeAccountSnapshot({
119
+ account,
120
+ configured: account.configured,
121
+ extra: {
122
+ publicKey: account.publicKey,
123
+ },
124
+ }),
125
+ },
126
+ messaging: {
127
+ targetPrefixes: ["nostr"],
128
+ normalizeTarget: (target) => {
129
+ // Strip nostr: prefix if present
130
+ const cleaned = target.trim().replace(/^nostr:/i, "");
131
+ try {
132
+ return normalizePubkey(cleaned);
133
+ } catch {
134
+ return cleaned;
135
+ }
136
+ },
137
+ targetResolver: {
138
+ looksLikeId: (input) => {
139
+ const trimmed = input.trim();
140
+ return trimmed.startsWith("npub1") || /^[0-9a-fA-F]{64}$/.test(trimmed);
141
+ },
142
+ hint: "<npub|hex pubkey|nostr:npub...>",
143
+ },
144
+ resolveOutboundSessionRoute: (params) => resolveNostrOutboundSessionRoute(params),
145
+ },
146
+ message: nostrMessageAdapter,
147
+ status: {
148
+ ...createComputedAccountStatusAdapter<ResolvedNostrAccount>({
149
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
150
+ collectStatusIssues: (accounts) => collectStatusIssuesFromLastError("nostr", accounts),
151
+ buildChannelSummary: ({ snapshot }) =>
152
+ buildPassiveChannelStatusSummary(snapshot, {
153
+ publicKey: snapshot.publicKey ?? null,
154
+ }),
155
+ resolveAccountSnapshot: ({ account, runtime }) => ({
156
+ accountId: account.accountId,
157
+ name: account.name,
158
+ enabled: account.enabled,
159
+ configured: account.configured,
160
+ extra: {
161
+ publicKey: account.publicKey,
162
+ profile: account.profile,
163
+ ...buildTrafficStatusSummary(runtime),
164
+ },
165
+ }),
166
+ }),
167
+ },
168
+ gateway: {
169
+ startAccount: startNostrGatewayAccount,
170
+ },
171
+ },
172
+ pairing: {
173
+ text: nostrPairingTextAdapter,
174
+ },
175
+ security: {
176
+ resolveDmPolicy: resolveNostrDmPolicy,
177
+ },
178
+ outbound: nostrOutboundAdapter,
179
+ });
180
+
181
+ /**
182
+ * Publish a profile (kind:0) for a Nostr account.
183
+ * @param accountId - Account ID (defaults to "default")
184
+ * @param profile - Profile data to publish
185
+ * @returns Publish results with successes and failures
186
+ * @throws Error if account is not running
187
+ */
188
+ export async function publishNostrProfile(
189
+ accountId: string | undefined,
190
+ profile: NostrProfile,
191
+ ): Promise<ProfilePublishResult> {
192
+ const resolvedAccountId = accountId ?? DEFAULT_ACCOUNT_ID;
193
+ const bus = getActiveNostrBuses().get(resolvedAccountId);
194
+ if (!bus) {
195
+ throw new Error(`Nostr bus not running for account ${resolvedAccountId}`);
196
+ }
197
+ return bus.publishProfile(profile);
198
+ }
199
+
200
+ /**
201
+ * Get profile publish state for a Nostr account.
202
+ * @param accountId - Account ID (defaults to "default")
203
+ * @returns Profile publish state or null if account not running
204
+ */
205
+ export async function getNostrProfileState(accountId: string = DEFAULT_ACCOUNT_ID): Promise<{
206
+ lastPublishedAt: number | null;
207
+ lastPublishedEventId: string | null;
208
+ lastPublishResults: Record<string, "ok" | "failed" | "timeout"> | null;
209
+ } | null> {
210
+ const bus = getActiveNostrBuses().get(accountId);
211
+ if (!bus) {
212
+ return null;
213
+ }
214
+ return bus.getProfileState();
215
+ }
@@ -0,0 +1,98 @@
1
+ import {
2
+ AllowFromListSchema,
3
+ DmPolicySchema,
4
+ MarkdownConfigSchema,
5
+ } from "autobot/plugin-sdk/channel-config-primitives";
6
+ import { buildSecretInputSchema } from "autobot/plugin-sdk/secret-input";
7
+ import { z } from "zod";
8
+
9
+ /**
10
+ * Validates https:// URLs only (no javascript:, data:, file:, etc.)
11
+ */
12
+ const safeUrlSchema = z
13
+ .string()
14
+ .url()
15
+ .refine(
16
+ (url) => {
17
+ try {
18
+ const parsed = new URL(url);
19
+ return parsed.protocol === "https:";
20
+ } catch {
21
+ return false;
22
+ }
23
+ },
24
+ { message: "URL must use https:// protocol" },
25
+ );
26
+
27
+ /**
28
+ * NIP-01 profile metadata schema
29
+ * https://github.com/nostr-protocol/nips/blob/master/01.md
30
+ */
31
+ export const NostrProfileSchema = z.object({
32
+ /** Username (NIP-01: name) - max 256 chars */
33
+ name: z.string().max(256).optional(),
34
+
35
+ /** Display name (NIP-01: display_name) - max 256 chars */
36
+ displayName: z.string().max(256).optional(),
37
+
38
+ /** Bio/description (NIP-01: about) - max 2000 chars */
39
+ about: z.string().max(2000).optional(),
40
+
41
+ /** Profile picture URL (must be https) */
42
+ picture: safeUrlSchema.optional(),
43
+
44
+ /** Banner image URL (must be https) */
45
+ banner: safeUrlSchema.optional(),
46
+
47
+ /** Website URL (must be https) */
48
+ website: safeUrlSchema.optional(),
49
+
50
+ /** NIP-05 identifier (e.g., "user@example.com") */
51
+ nip05: z.string().optional(),
52
+
53
+ /** Lightning address (LUD-16) */
54
+ lud16: z.string().optional(),
55
+ });
56
+
57
+ export interface NostrProfile {
58
+ name?: string;
59
+ displayName?: string;
60
+ about?: string;
61
+ picture?: string;
62
+ banner?: string;
63
+ website?: string;
64
+ nip05?: string;
65
+ lud16?: string;
66
+ }
67
+
68
+ /**
69
+ * Zod schema for channels.nostr.* configuration
70
+ */
71
+ export const NostrConfigSchema = z.object({
72
+ /** Account name (optional display name) */
73
+ name: z.string().optional(),
74
+
75
+ /** Optional default account id for routing/account selection. */
76
+ defaultAccount: z.string().optional(),
77
+
78
+ /** Whether this channel is enabled */
79
+ enabled: z.boolean().optional(),
80
+
81
+ /** Markdown formatting overrides (tables). */
82
+ markdown: MarkdownConfigSchema,
83
+
84
+ /** Private key in hex or nsec bech32 format */
85
+ privateKey: buildSecretInputSchema().optional(),
86
+
87
+ /** WebSocket relay URLs to connect to */
88
+ relays: z.array(z.string()).optional(),
89
+
90
+ /** DM access policy: pairing, allowlist, open, or disabled */
91
+ dmPolicy: DmPolicySchema.optional(),
92
+
93
+ /** Allowed sender pubkeys (npub or hex format) */
94
+ allowFrom: AllowFromListSchema,
95
+
96
+ /** Profile metadata (NIP-01 kind:0 content) */
97
+ profile: NostrProfileSchema.optional(),
98
+ });
@@ -0,0 +1 @@
1
+ export const DEFAULT_RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];
package/src/gateway.ts ADDED
@@ -0,0 +1,321 @@
1
+ import {
2
+ resolveStableChannelMessageIngress,
3
+ type StableChannelIngressIdentityParams,
4
+ } from "autobot/plugin-sdk/channel-ingress-runtime";
5
+ import { createChannelPairingController } from "autobot/plugin-sdk/channel-pairing";
6
+ import { attachChannelToResult } from "autobot/plugin-sdk/channel-send-result";
7
+ import type { AutoBotConfig } from "autobot/plugin-sdk/config-contracts";
8
+ import { type ChannelOutboundAdapter, type ChannelPlugin } from "./channel-api.js";
9
+ import type { MetricEvent, MetricsSnapshot } from "./metrics.js";
10
+ import { startNostrBus, type NostrBusHandle } from "./nostr-bus.js";
11
+ import { normalizePubkey } from "./nostr-key-utils.js";
12
+ import { getNostrRuntime } from "./runtime.js";
13
+ import { resolveDefaultNostrAccountId, type ResolvedNostrAccount } from "./types.js";
14
+
15
+ type NostrGatewayStart = NonNullable<
16
+ NonNullable<ChannelPlugin<ResolvedNostrAccount>["gateway"]>["startAccount"]
17
+ >;
18
+ type NostrOutboundAdapter = Pick<
19
+ ChannelOutboundAdapter,
20
+ "deliveryCapabilities" | "deliveryMode" | "textChunkLimit" | "sendText"
21
+ > & {
22
+ sendText: NonNullable<ChannelOutboundAdapter["sendText"]>;
23
+ };
24
+
25
+ const activeBuses = new Map<string, NostrBusHandle>();
26
+ const metricsSnapshots = new Map<string, MetricsSnapshot>();
27
+ const ACCESS_GROUP_PREFIX = "accessGroup:";
28
+
29
+ function parseNostrAccessGroupAllowFromEntry(entry: string): string | null {
30
+ const trimmed = entry.trim();
31
+ if (!trimmed.startsWith(ACCESS_GROUP_PREFIX)) {
32
+ return null;
33
+ }
34
+ const name = trimmed.slice(ACCESS_GROUP_PREFIX.length).trim();
35
+ return name || null;
36
+ }
37
+
38
+ function normalizeNostrAllowEntry(entry: string): string | null {
39
+ const trimmed = entry.trim();
40
+ if (!trimmed) {
41
+ return null;
42
+ }
43
+ if (trimmed === "*") {
44
+ return "*";
45
+ }
46
+ const accessGroup = parseNostrAccessGroupAllowFromEntry(trimmed);
47
+ if (accessGroup) {
48
+ return `accessGroup:${accessGroup}`;
49
+ }
50
+ try {
51
+ return normalizePubkey(trimmed.replace(/^nostr:/i, ""));
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function normalizeNostrSenderPubkey(value: string): string | null {
58
+ try {
59
+ return normalizePubkey(value);
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ const nostrIngressIdentity = {
66
+ key: "nostr-pubkey",
67
+ normalizeEntry: normalizeNostrAllowEntry,
68
+ normalizeSubject: normalizeNostrSenderPubkey,
69
+ sensitivity: "pii",
70
+ entryIdPrefix: "nostr-entry",
71
+ } satisfies StableChannelIngressIdentityParams;
72
+
73
+ export const startNostrGatewayAccount: NostrGatewayStart = async (ctx) => {
74
+ const account = ctx.account;
75
+ ctx.setStatus({
76
+ accountId: account.accountId,
77
+ publicKey: account.publicKey,
78
+ });
79
+ ctx.log?.info?.(`[${account.accountId}] starting Nostr provider (pubkey: ${account.publicKey})`);
80
+
81
+ if (!account.configured) {
82
+ throw new Error("Nostr private key not configured");
83
+ }
84
+
85
+ const runtime = getNostrRuntime();
86
+ const pairing = createChannelPairingController({
87
+ core: runtime,
88
+ channel: "nostr",
89
+ accountId: account.accountId,
90
+ });
91
+ const resolveInboundAccess = async (senderPubkey: string, rawBody: string) =>
92
+ await resolveStableChannelMessageIngress({
93
+ channelId: "nostr",
94
+ accountId: account.accountId,
95
+ identity: nostrIngressIdentity,
96
+ cfg: ctx.cfg,
97
+ useDefaultPairingStore: true,
98
+ subject: { stableId: senderPubkey },
99
+ conversation: {
100
+ kind: "direct",
101
+ id: senderPubkey,
102
+ },
103
+ dmPolicy: account.config.dmPolicy ?? "pairing",
104
+ allowFrom: account.config.allowFrom,
105
+ command: runtime.channel.commands.shouldComputeCommandAuthorized(rawBody, ctx.cfg)
106
+ ? {
107
+ modeWhenAccessGroupsOff: "configured",
108
+ }
109
+ : undefined,
110
+ });
111
+
112
+ let busHandle: NostrBusHandle | null = null;
113
+
114
+ const authorizeSender = async (input: {
115
+ senderId: string;
116
+ reply: (text: string) => Promise<void>;
117
+ }): Promise<"allow" | "block" | "pairing"> => {
118
+ const resolved = await resolveInboundAccess(input.senderId, "");
119
+ if (resolved.senderAccess.decision === "allow") {
120
+ return "allow";
121
+ }
122
+ if (resolved.senderAccess.decision === "pairing") {
123
+ await pairing.issueChallenge({
124
+ senderId: input.senderId,
125
+ senderIdLine: `Your Nostr pubkey: ${input.senderId}`,
126
+ sendPairingReply: input.reply,
127
+ onCreated: () => {
128
+ ctx.log?.debug?.(`[${account.accountId}] nostr pairing request sender=${input.senderId}`);
129
+ },
130
+ onReplyError: (err) => {
131
+ ctx.log?.warn?.(
132
+ `[${account.accountId}] nostr pairing reply failed for ${input.senderId}: ${String(
133
+ err,
134
+ )}`,
135
+ );
136
+ },
137
+ });
138
+ return "pairing";
139
+ }
140
+ ctx.log?.debug?.(
141
+ `[${account.accountId}] blocked Nostr sender ${input.senderId} (${resolved.senderAccess.reasonCode})`,
142
+ );
143
+ return "block";
144
+ };
145
+
146
+ const bus = await startNostrBus({
147
+ accountId: account.accountId,
148
+ privateKey: account.privateKey,
149
+ relays: account.relays,
150
+ authorizeSender: async ({ senderPubkey, reply }) =>
151
+ await authorizeSender({ senderId: senderPubkey, reply }),
152
+ onMessage: async (senderPubkey, text, reply, meta) => {
153
+ const resolvedAccess = await resolveInboundAccess(senderPubkey, text);
154
+ if (resolvedAccess.senderAccess.decision !== "allow") {
155
+ ctx.log?.warn?.(
156
+ `[${account.accountId}] dropping Nostr DM after preflight drift (${senderPubkey}, ${resolvedAccess.senderAccess.reasonCode})`,
157
+ );
158
+ return;
159
+ }
160
+
161
+ const { dispatchInboundDirectDmWithRuntime } = await import("./inbound-direct-dm-runtime.js");
162
+ await dispatchInboundDirectDmWithRuntime({
163
+ cfg: ctx.cfg,
164
+ runtime,
165
+ channel: "nostr",
166
+ channelLabel: "Nostr",
167
+ accountId: account.accountId,
168
+ peer: {
169
+ kind: "direct",
170
+ id: senderPubkey,
171
+ },
172
+ senderId: senderPubkey,
173
+ senderAddress: `nostr:${senderPubkey}`,
174
+ recipientAddress: `nostr:${account.publicKey}`,
175
+ conversationLabel: senderPubkey,
176
+ rawBody: text,
177
+ messageId: meta.eventId,
178
+ timestamp: meta.createdAt * 1000,
179
+ commandAuthorized: resolvedAccess.commandAccess.requested
180
+ ? resolvedAccess.commandAccess.authorized
181
+ : undefined,
182
+ deliver: async (payload) => {
183
+ const outboundText =
184
+ payload && typeof payload === "object" && "text" in payload
185
+ ? ((payload as { text?: string }).text ?? "")
186
+ : "";
187
+ if (!outboundText.trim()) {
188
+ return;
189
+ }
190
+ const tableMode = runtime.channel.text.resolveMarkdownTableMode({
191
+ cfg: ctx.cfg,
192
+ channel: "nostr",
193
+ accountId: account.accountId,
194
+ });
195
+ await reply(runtime.channel.text.convertMarkdownTables(outboundText, tableMode));
196
+ },
197
+ onRecordError: (err) => {
198
+ ctx.log?.error?.(
199
+ `[${account.accountId}] failed recording Nostr inbound session: ${String(err)}`,
200
+ );
201
+ },
202
+ onDispatchError: (err, info) => {
203
+ ctx.log?.error?.(
204
+ `[${account.accountId}] Nostr ${info.kind} reply failed: ${String(err)}`,
205
+ );
206
+ },
207
+ });
208
+ },
209
+ onError: (error, context) => {
210
+ ctx.log?.error?.(`[${account.accountId}] Nostr error (${context}): ${error.message}`);
211
+ },
212
+ onConnect: (relay) => {
213
+ ctx.log?.debug?.(`[${account.accountId}] Connected to relay: ${relay}`);
214
+ },
215
+ onDisconnect: (relay) => {
216
+ ctx.log?.debug?.(`[${account.accountId}] Disconnected from relay: ${relay}`);
217
+ },
218
+ onEose: (relays) => {
219
+ ctx.log?.debug?.(`[${account.accountId}] EOSE received from relays: ${relays}`);
220
+ },
221
+ onMetric: (event: MetricEvent) => {
222
+ if (event.name.startsWith("event.rejected.")) {
223
+ ctx.log?.debug?.(
224
+ `[${account.accountId}] Metric: ${event.name} ${JSON.stringify(event.labels)}`,
225
+ );
226
+ } else if (event.name === "relay.circuit_breaker.open") {
227
+ ctx.log?.warn?.(
228
+ `[${account.accountId}] Circuit breaker opened for relay: ${event.labels?.relay}`,
229
+ );
230
+ } else if (event.name === "relay.circuit_breaker.close") {
231
+ ctx.log?.info?.(
232
+ `[${account.accountId}] Circuit breaker closed for relay: ${event.labels?.relay}`,
233
+ );
234
+ } else if (event.name === "relay.error") {
235
+ ctx.log?.debug?.(`[${account.accountId}] Relay error: ${event.labels?.relay}`);
236
+ }
237
+ if (busHandle) {
238
+ metricsSnapshots.set(account.accountId, busHandle.getMetrics());
239
+ }
240
+ },
241
+ });
242
+
243
+ busHandle = bus;
244
+ activeBuses.set(account.accountId, bus);
245
+
246
+ ctx.log?.info?.(
247
+ `[${account.accountId}] Nostr provider started, connected to ${account.relays.length} relay(s)`,
248
+ );
249
+
250
+ return {
251
+ stop: () => {
252
+ bus.close();
253
+ activeBuses.delete(account.accountId);
254
+ metricsSnapshots.delete(account.accountId);
255
+ ctx.log?.info?.(`[${account.accountId}] Nostr provider stopped`);
256
+ },
257
+ };
258
+ };
259
+
260
+ export const nostrPairingTextAdapter = {
261
+ idLabel: "nostrPubkey",
262
+ message: "Your pairing request has been approved!",
263
+ normalizeAllowEntry: (entry: string) => {
264
+ try {
265
+ return normalizePubkey(entry.trim().replace(/^nostr:/i, ""));
266
+ } catch {
267
+ return entry.trim();
268
+ }
269
+ },
270
+ notify: async ({
271
+ cfg,
272
+ id,
273
+ message,
274
+ accountId,
275
+ }: {
276
+ cfg: AutoBotConfig;
277
+ id: string;
278
+ message: string;
279
+ accountId?: string;
280
+ }) => {
281
+ const bus = activeBuses.get(accountId ?? resolveDefaultNostrAccountId(cfg));
282
+ if (bus) {
283
+ await bus.sendDm(id, message);
284
+ }
285
+ },
286
+ };
287
+
288
+ export const nostrOutboundAdapter: NostrOutboundAdapter = {
289
+ deliveryMode: "direct",
290
+ textChunkLimit: 4000,
291
+ deliveryCapabilities: {
292
+ durableFinal: {
293
+ text: true,
294
+ messageSendingHooks: true,
295
+ },
296
+ },
297
+ sendText: async ({ cfg, to, text, accountId }) => {
298
+ const core = getNostrRuntime();
299
+ const aid = accountId ?? resolveDefaultNostrAccountId(cfg);
300
+ const bus = activeBuses.get(aid);
301
+ if (!bus) {
302
+ throw new Error(`Nostr bus not running for account ${aid}`);
303
+ }
304
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
305
+ cfg,
306
+ channel: "nostr",
307
+ accountId: aid,
308
+ });
309
+ const message = core.channel.text.convertMarkdownTables(text ?? "", tableMode);
310
+ const normalizedTo = normalizePubkey(to);
311
+ await bus.sendDm(normalizedTo, message);
312
+ return attachChannelToResult("nostr", {
313
+ to: normalizedTo,
314
+ messageId: `nostr-${Date.now()}`,
315
+ });
316
+ },
317
+ };
318
+
319
+ export function getActiveNostrBuses(): Map<string, NostrBusHandle> {
320
+ return new Map(activeBuses);
321
+ }
@@ -0,0 +1 @@
1
+ export { dispatchInboundDirectDmWithRuntime } from "autobot/plugin-sdk/direct-dm";