From 9d700060d1e0a4dea4515faafc1d9aedc2c90f0a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 28 Aug 2025 13:57:50 -0500 Subject: [PATCH] Add Nostr AI tools --- src/components/Shakespeare/ChatPane.tsx | 14 + src/lib/HTTPError.test.ts | 17 + src/lib/HTTPError.ts | 14 + src/lib/KindGenerator.test.ts | 371 ++++++++++++++++++++++ src/lib/KindGenerator.ts | 178 +++++++++++ src/lib/NIPsClient.test.ts | 47 +++ src/lib/NIPsClient.ts | 52 +++ src/lib/NostrbookClient.test.ts | 46 +++ src/lib/NostrbookClient.ts | 53 ++++ src/lib/fixtures/NIPs.md | 402 ++++++++++++++++++++++++ src/lib/llmstxt.test.ts | 35 +++ src/lib/llmstxt.ts | 19 ++ src/lib/tools/NostrFetchEventTool.ts | 184 +++++++++++ src/lib/tools/NostrGenerateKindTool.ts | 47 +++ src/lib/tools/NostrReadKindTool.ts | 41 +++ src/lib/tools/NostrReadNipTool.ts | 48 +++ src/lib/tools/NostrReadNipsIndexTool.ts | 27 ++ src/lib/tools/NostrReadProtocolTool.ts | 35 +++ src/lib/tools/NostrReadTagTool.ts | 41 +++ 19 files changed, 1671 insertions(+) create mode 100644 src/lib/HTTPError.test.ts create mode 100644 src/lib/HTTPError.ts create mode 100644 src/lib/KindGenerator.test.ts create mode 100644 src/lib/KindGenerator.ts create mode 100644 src/lib/NIPsClient.test.ts create mode 100644 src/lib/NIPsClient.ts create mode 100644 src/lib/NostrbookClient.test.ts create mode 100644 src/lib/NostrbookClient.ts create mode 100644 src/lib/fixtures/NIPs.md create mode 100644 src/lib/llmstxt.test.ts create mode 100644 src/lib/llmstxt.ts create mode 100644 src/lib/tools/NostrFetchEventTool.ts create mode 100644 src/lib/tools/NostrGenerateKindTool.ts create mode 100644 src/lib/tools/NostrReadKindTool.ts create mode 100644 src/lib/tools/NostrReadNipTool.ts create mode 100644 src/lib/tools/NostrReadNipsIndexTool.ts create mode 100644 src/lib/tools/NostrReadProtocolTool.ts create mode 100644 src/lib/tools/NostrReadTagTool.ts diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index a53a279d..0a798aa4 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -21,6 +21,13 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool'; import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool'; import { GitCommitTool } from '@/lib/tools/GitCommitTool'; import { BuildProjectTool } from '@/lib/tools/BuildProjectTool'; +import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool'; +import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool'; +import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool'; +import { NostrReadTagTool } from '@/lib/tools/NostrReadTagTool'; +import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool'; +import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; +import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; @@ -82,6 +89,13 @@ export const ChatPane = forwardRef(({ npm_add_package: new NpmAddPackageTool(browserFS, cwd), npm_remove_package: new NpmRemovePackageTool(browserFS, cwd), build_project: new BuildProjectTool(browserFS, cwd), + nostr_read_nip: new NostrReadNipTool(), + nostr_fetch_event: new NostrFetchEventTool(), + nostr_read_kind: new NostrReadKindTool(), + nostr_read_tag: new NostrReadTagTool(), + nostr_read_protocol: new NostrReadProtocolTool(), + nostr_read_nips_index: new NostrReadNipsIndexTool(), + nostr_generate_kind: new NostrGenerateKindTool(), }), [browserFS, cwd]); // Convert tools to OpenAI format diff --git a/src/lib/HTTPError.test.ts b/src/lib/HTTPError.test.ts new file mode 100644 index 00000000..a691c7f2 --- /dev/null +++ b/src/lib/HTTPError.test.ts @@ -0,0 +1,17 @@ +import { describe, it, expect } from 'vitest'; + +import { HTTPError } from './HTTPError.ts'; + +describe('HTTPError', () => { + it('should create HTTPError with correct properties', () => { + const request = new Request('https://example.com/api'); + const response = new Response('Not Found', { status: 404 }); + + const error = new HTTPError(response, request); + + expect(error.name).toBe('HTTPError'); + expect(error.message).toBe('HTTP Error: 404 GET https://example.com/api'); + expect(error.response).toBe(response); + expect(error.request).toBe(request); + }); +}); diff --git a/src/lib/HTTPError.ts b/src/lib/HTTPError.ts new file mode 100644 index 00000000..110e8caf --- /dev/null +++ b/src/lib/HTTPError.ts @@ -0,0 +1,14 @@ +/** Error class for HTTP request failures */ +export class HTTPError extends Error { + /** The response object from the failed HTTP request */ + readonly response: Response; + /** The original request object */ + readonly request: Request; + + constructor(response: Response, request: Request) { + super(`HTTP Error: ${response.status} ${request.method} ${request.url}`); + this.name = 'HTTPError'; + this.response = response; + this.request = request; + } +} \ No newline at end of file diff --git a/src/lib/KindGenerator.test.ts b/src/lib/KindGenerator.test.ts new file mode 100644 index 00000000..ea76b8d5 --- /dev/null +++ b/src/lib/KindGenerator.test.ts @@ -0,0 +1,371 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { KindGenerator } from './KindGenerator.ts'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +describe('KindGenerator', () => { + it('should extract used kinds from real NIPs fixture', () => { + const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8'); + const usedKinds = KindGenerator.extractUsedKinds(nipsIndex); + + // Check that some expected kinds are extracted from the real NIPs index + const expectedKinds = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 20, + 21, + 22, + 30, + 31, + 32, + 33, + 40, + 41, + 42, + 43, + 44, + 62, + 64, + 818, + 1018, + 1021, + 1022, + 1040, + 1059, + 1063, + 1068, + 1111, + 1311, + 1337, + 1617, + 1621, + 1622, + 1971, + 1984, + 1985, + 1986, + 1987, + 2003, + 2004, + 2022, + 4550, + 7000, + 7374, + 7375, + 7376, + 9041, + 9321, + 9467, + 9734, + 9735, + 9802, + 10000, + 10001, + 10002, + 10003, + 10004, + 10005, + 10006, + 10007, + 10009, + 10012, + 10013, + 10015, + 10019, + 10020, + 10030, + 10050, + 10063, + 10096, + 10166, + 13194, + 17375, + 21000, + 22242, + 23194, + 23195, + 24133, + 24242, + 27235, + 30000, + 30001, + 30002, + 30003, + 30004, + 30005, + 30007, + 30008, + 30009, + 30015, + 30017, + 30018, + 30019, + 30020, + 30023, + 30024, + 30030, + 30040, + 30041, + 30063, + 30078, + 30166, + 30267, + 30311, + 30315, + 30388, + 30402, + 30403, + 30617, + 30618, + 30818, + 30819, + 31234, + 31388, + 31890, + 31922, + 31923, + 31924, + 31925, + 31989, + 31990, + 32267, + 34550, + 38383, + 39089, + 39092, + 39701, + ]; + + for (const kind of expectedKinds) { + expect(usedKinds.has(kind)).toBe(true); + } + + // Check that ranges are properly extracted + // `5000`-`5999` should add all numbers from 5000 to 5999 + for (let i = 5000; i <= 5999; i++) { + expect(usedKinds.has(i)).toBe(true); + } + + // `6000`-`6999` should add all numbers from 6000 to 6999 + for (let i = 6000; i <= 6999; i++) { + expect(usedKinds.has(i)).toBe(true); + } + + // `9000`-`9030` should add all numbers from 9000 to 9030 + for (let i = 9000; i <= 9030; i++) { + expect(usedKinds.has(i)).toBe(true); + } + + // `39000-9` should add all numbers from 39000 to 39009 + for (let i = 39000; i <= 39009; i++) { + expect(usedKinds.has(i)).toBe(true); + } + + // `1630`-`1633` should add all numbers from 1630 to 1633 + for (let i = 1630; i <= 1633; i++) { + expect(usedKinds.has(i)).toBe(true); + } + }); + + it('should extract used kinds from mock data', () => { + const mockNipsIndex = ` +## Event Kinds + +| kind | description | NIP | +| ------------- | ------------------------------- | -------------------------------------- | +| \`0\` | User Metadata | [01](01.md) | +| \`1\` | Short Text Note | [10](10.md) | +| \`3\` | Follows | [02](02.md) | +| \`1000\`-\`1999\` | Custom Range | [test](test.md) | +| \`30000\` | Addressable Event | [51](51.md) | +`; + + const usedKinds = KindGenerator.extractUsedKinds(mockNipsIndex); + + // Check individual kinds + expect(usedKinds.has(0)).toBe(true); + expect(usedKinds.has(1)).toBe(true); + expect(usedKinds.has(3)).toBe(true); + expect(usedKinds.has(30000)).toBe(true); + + // Check range + for (let i = 1000; i <= 1999; i++) { + expect(usedKinds.has(i)).toBe(true); + } + }); + + it('should get kind range info correctly', () => { + const regularRange = KindGenerator.getKindRangeInfo('regular'); + expect(regularRange.min).toBe(1000); + expect(regularRange.max).toBe(9999); + expect(regularRange.name).toBe('Regular Events'); + + const replaceableRange = KindGenerator.getKindRangeInfo('replaceable'); + expect(replaceableRange.min).toBe(10000); + expect(replaceableRange.max).toBe(19999); + + const ephemeralRange = KindGenerator.getKindRangeInfo('ephemeral'); + expect(ephemeralRange.min).toBe(20000); + expect(ephemeralRange.max).toBe(29999); + + const addressableRange = KindGenerator.getKindRangeInfo('addressable'); + expect(addressableRange.min).toBe(30000); + expect(addressableRange.max).toBe(39999); + }); + + it('should generate available kinds in correct ranges', () => { + const usedKinds = new Set([1000, 1001, 1002, 10000, 10001, 30000, 30001]); + + // Test regular range + const regularKind = KindGenerator.generateAvailableKind( + 'regular', + usedKinds, + ); + expect(regularKind >= 1000 && regularKind <= 9999).toBe(true); + expect(usedKinds.has(regularKind)).toBe(false); + // Check new constraints + expect(regularKind % 2 !== 0).toBe(true); + expect(regularKind % 5 !== 0).toBe(true); + // Check buffer constraint - should not be within 2 of any used kind + for (const usedKind of usedKinds) { + const distance = Math.abs(regularKind - usedKind); + expect(distance > 2).toBe(true); + } + + // Test replaceable range + const replaceableKind = KindGenerator.generateAvailableKind( + 'replaceable', + usedKinds, + ); + expect(replaceableKind >= 10000 && replaceableKind <= 19999).toBe(true); + expect(usedKinds.has(replaceableKind)).toBe(false); + expect(replaceableKind % 2 !== 0).toBe(true); + expect(replaceableKind % 5 !== 0).toBe(true); + + // Test ephemeral range + const ephemeralKind = KindGenerator.generateAvailableKind( + 'ephemeral', + usedKinds, + ); + expect(ephemeralKind >= 20000 && ephemeralKind <= 29999).toBe(true); + expect(usedKinds.has(ephemeralKind)).toBe(false); + expect(ephemeralKind % 2 !== 0).toBe(true); + expect(ephemeralKind % 5 !== 0).toBe(true); + + // Test addressable range + const addressableKind = KindGenerator.generateAvailableKind( + 'addressable', + usedKinds, + ); + expect(addressableKind >= 30000 && addressableKind <= 39999).toBe(true); + expect(usedKinds.has(addressableKind)).toBe(false); + expect(addressableKind % 2 !== 0).toBe(true); + expect(addressableKind % 5 !== 0).toBe(true); + }); + + it('should respect buffer constraints when generating kinds', () => { + // Test buffer constraint specifically + const usedKinds = new Set([1007, 1013, 1019]); // Use odd numbers that aren't multiples of 5 + + const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds); + + // Should be in range + expect(regularKind >= 1000 && regularKind <= 9999).toBe(true); + + // Should be odd + expect(regularKind % 2 !== 0).toBe(true); + + // Should not be multiple of 5 + expect(regularKind % 5 !== 0).toBe(true); + + // Should not be within buffer of used kinds + const forbiddenNumbers = new Set([ + 1005, 1006, 1007, 1008, 1009, // around 1007 + 1011, 1012, 1013, 1014, 1015, // around 1013 + 1017, 1018, 1019, 1020, 1021, // around 1019 + ]); + + expect(forbiddenNumbers.has(regularKind)).toBe(false); + }); + + it('should handle edge cases with many used kinds', () => { + // Test with many used kinds to ensure we still find valid ones + const usedKinds = new Set(); + + // Fill most even numbers and multiples of 5 in a small range + for (let i = 1000; i <= 1100; i++) { + if (i % 2 === 0 || i % 5 === 0) { + usedKinds.add(i); + } + } + + const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds); + + // Should still find a valid kind + expect(regularKind >= 1000 && regularKind <= 9999).toBe(true); + expect(regularKind % 2 !== 0).toBe(true); + expect(regularKind % 5 !== 0).toBe(true); + expect(usedKinds.has(regularKind)).toBe(false); + }); + + it('should generate random kinds with good distribution', () => { + const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8'); + const usedKinds = KindGenerator.extractUsedKinds(nipsIndex); + + // Generate many kinds and check distribution + const results = new Map(); + const iterations = 100; + + for (let i = 0; i < iterations; i++) { + const kind = KindGenerator.generateAvailableKind('regular', usedKinds); + results.set(kind, (results.get(kind) || 0) + 1); + + // Verify constraints on each generated kind + expect(kind % 2 !== 0).toBe(true); + expect(kind % 5 !== 0).toBe(true); + expect(usedKinds.has(kind)).toBe(false); + } + + // Check that we get good variety (at least 10 unique kinds in 100 iterations) + // Reduced expectations due to fewer iterations + expect(results.size).toBeGreaterThanOrEqual(10); + + // Check that no single kind dominates (no kind should appear more than 30% of the time) + // Increased threshold due to fewer iterations + const maxFrequency = Math.max(...results.values()); + const maxFrequencyPercent = (maxFrequency / iterations) * 100; + expect(maxFrequencyPercent).toBeLessThanOrEqual(30); + + // Check that all generated kinds follow our constraints + for (const [kind] of results) { + expect(kind % 2 !== 0).toBe(true); + expect(kind % 5 !== 0).toBe(true); + + // Check buffer constraint + for (const usedKind of usedKinds) { + const distance = Math.abs(kind - usedKind); + expect(distance > 2).toBe(true); + } + } + }); +}); diff --git a/src/lib/KindGenerator.ts b/src/lib/KindGenerator.ts new file mode 100644 index 00000000..282c8328 --- /dev/null +++ b/src/lib/KindGenerator.ts @@ -0,0 +1,178 @@ +/** + * Utilities for generating unused Nostr event kind numbers + */ + +export interface KindRangeInfo { + name: string; + min: number; + max: number; + description: string; +} + +export type KindRange = 'regular' | 'replaceable' | 'ephemeral' | 'addressable'; + +/** + * Generator for unused Nostr event kind numbers + */ +export class KindGenerator { + /** + * Extract used kind numbers from the NIPs index + */ + static extractUsedKinds(nipsIndex: string): Set { + const usedKinds = new Set(); + + // Look for kind numbers in the Event Kinds table + // Format: | `1234` | description | NIP | + // Also handle ranges like `5000`-`5999` + + const kindPatterns = [ + // Single kind in backticks: `1234` + /\|\s*`(\d+)`\s*\|/g, + // Range in backticks: `5000`-`5999` + /\|\s*`(\d+)`-`(\d+)`\s*\|/g, + // Range in backticks with single digit end: `39000-9` + /\|\s*`(\d+)-(\d+)`\s*\|/g, + ]; + + for (const pattern of kindPatterns) { + let match; + while ((match = pattern.exec(nipsIndex)) !== null) { + if (match[2] !== undefined && match[1] !== undefined) { + // Handle range format like `5000`-`5999` or `39000-9` + const start = parseInt(match[1], 10); + let end = parseInt(match[2], 10); + + // Handle special case like `39000-9` which means 39000-39009 + if (end < start && end < 10) { + const startStr = match[1]; + const endStr = match[2]; + if (startStr && endStr) { + // Replace the last digit(s) of start with end + const prefix = startStr.slice(0, -endStr.length); + end = parseInt(prefix + endStr, 10); + } + } + + if ( + !isNaN(start) && !isNaN(end) && start >= 0 && end >= 0 && + start <= 65535 && end <= 65535 && start <= end + ) { + // Add all numbers in the range + for (let i = start; i <= end; i++) { + usedKinds.add(i); + } + } + } else if (match[1] !== undefined) { + // Handle single kind format like `1234` + const num = parseInt(match[1], 10); + if (!isNaN(num) && num >= 0 && num <= 65535) { + usedKinds.add(num); + } + } + } + } + + return usedKinds; + } + + /** + * Generate an available kind number in the specified range + */ + static generateAvailableKind( + range: KindRange, + usedKinds: Set, + ): number { + const rangeInfo = this.getKindRangeInfo(range); + + // Create a set of all numbers to avoid (used kinds + buffer) + const kindsToAvoid = new Set(); + + // Add used kinds and their buffer zones + for (const usedKind of usedKinds) { + kindsToAvoid.add(usedKind); + // Add buffer of 2 kinds on each side + kindsToAvoid.add(usedKind - 2); + kindsToAvoid.add(usedKind - 1); + kindsToAvoid.add(usedKind + 1); + kindsToAvoid.add(usedKind + 2); + } + + // Collect all available numbers in the range + const availableKinds: number[] = []; + for (let i = rangeInfo.min; i <= rangeInfo.max; i++) { + // Skip if in range to avoid + if (kindsToAvoid.has(i)) { + continue; + } + + // Skip even numbers + if (i % 2 === 0) { + continue; + } + + // Skip multiples of 5 + if (i % 5 === 0) { + continue; + } + + availableKinds.push(i); + } + + // If no available numbers, fall back to first valid number in range + if (availableKinds.length === 0) { + for (let i = rangeInfo.min; i <= rangeInfo.max; i++) { + // Find first odd number that's not a multiple of 5 + if (i % 2 !== 0 && i % 5 !== 0) { + return i; + } + } + // Ultimate fallback + return rangeInfo.min; + } + + // Return a random available number + const randomIndex = Math.floor(Math.random() * availableKinds.length); + return availableKinds[randomIndex]!; + } + + /** + * Get information about a kind range + */ + static getKindRangeInfo(range: KindRange): KindRangeInfo { + switch (range) { + case 'regular': + return { + name: 'Regular Events', + min: 1000, + max: 9999, + description: + 'Regular events for application-specific use cases. These events are stored permanently.', + }; + case 'replaceable': + return { + name: 'Replaceable Events', + min: 10000, + max: 19999, + description: + 'Events that can be replaced by newer versions from the same author.', + }; + case 'ephemeral': + return { + name: 'Ephemeral Events', + min: 20000, + max: 29999, + description: 'Events that are not stored permanently by relays.', + }; + case 'addressable': + return { + name: 'Addressable Events', + min: 30000, + max: 39999, + description: + 'Events that can be addressed and replaced using the "d" tag identifier.', + }; + default: + throw new Error(`Unknown range: ${range}`); + } + } +} \ No newline at end of file diff --git a/src/lib/NIPsClient.test.ts b/src/lib/NIPsClient.test.ts new file mode 100644 index 00000000..b77c48ff --- /dev/null +++ b/src/lib/NIPsClient.test.ts @@ -0,0 +1,47 @@ +import { describe, it, expect } from 'vitest'; + +import { NIPsClient } from './NIPsClient.ts'; + +describe('NIPsClient', () => { + const mockFetch: typeof fetch = async (input, init) => { + const { url } = new Request(input, init); + switch (url) { + case 'https://git.test/nostr-protocol/nips/refs/heads/master/01.md': + return new Response('NIP-01'); + case 'https://git.test/nostr-protocol/nips/refs/heads/master/README.md': + return new Response('NIPs'); + case 'https://git.test/nostr-protocol/nips/refs/heads/master/BREAKING.md': + return new Response('Breaking Changes'); + default: + return new Response('Not Found', { status: 404 }); + } + }; + + const client = new NIPsClient({ + urlTemplate: + 'https://git.test/nostr-protocol/nips/refs/heads/master/{nip}.md', + fetch: mockFetch, + }); + + it('should read NIP document', async () => { + const doc = await client.readNip('01'); + expect(doc).toBe('NIP-01'); + }); + + it('should read index document', async () => { + const doc = await client.readIndex(); + expect(doc).toBe('NIPs'); + }); + + it('should read breaking changes document', async () => { + const doc = await client.readBreaking(); + expect(doc).toBe('Breaking Changes'); + }); + + it('should throw HTTPError for 404 responses', async () => { + await expect(client.readNip('abc')).rejects.toMatchObject({ + name: 'HTTPError', + message: 'HTTP Error: 404 GET https://git.test/nostr-protocol/nips/refs/heads/master/abc.md', + }); + }); +}); diff --git a/src/lib/NIPsClient.ts b/src/lib/NIPsClient.ts new file mode 100644 index 00000000..b5c0dbea --- /dev/null +++ b/src/lib/NIPsClient.ts @@ -0,0 +1,52 @@ +import { HTTPError } from './HTTPError'; + +/** Options for configuring the NIPsClient */ +export interface NIPsClientOpts { + /** Template URL with {nip} placeholder that will be replaced with the NIP number */ + urlTemplate: string; + /** Optional fetch function override */ + fetch?: typeof fetch; +} + +/** Client for fetching NIPs (Nostr Implementation Possibilities) documentation */ +export class NIPsClient { + /** Template URL with {nip} placeholder */ + readonly urlTemplate: string; + + /** The fetch implementation to use for requests */ + private fetch: typeof fetch; + + constructor(opts: NIPsClientOpts) { + this.urlTemplate = opts.urlTemplate; + this.fetch = opts.fetch ?? globalThis.fetch.bind(globalThis); + } + + /** Reads a documentation file by its slug */ + async readDoc(slug: string): Promise { + const url = this.urlTemplate.replace('{nip}', slug); + + const request = new Request(url); + const response = await this.fetch(request); + + if (!response.ok) { + throw new HTTPError(response, request); + } + + return response.text(); + } + + /** Reads a specific NIP document by its identifier */ + readNip(nip: string): Promise { + return this.readDoc(nip); + } + + /** Reads the main index (README) document */ + readIndex(): Promise { + return this.readDoc('README'); + } + + /** Reads the breaking changes document */ + readBreaking(): Promise { + return this.readDoc('BREAKING'); + } +} \ No newline at end of file diff --git a/src/lib/NostrbookClient.test.ts b/src/lib/NostrbookClient.test.ts new file mode 100644 index 00000000..8a9aa442 --- /dev/null +++ b/src/lib/NostrbookClient.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect } from 'vitest'; + +import { NostrbookClient } from './NostrbookClient.ts'; + +describe('NostrbookClient', () => { + const mockFetch: typeof fetch = async (input, init) => { + const { url } = new Request(input, init); + switch (url) { + case 'https://nostrbook.test/kinds/1.md': + return new Response('Kind: 1'); + case 'https://nostrbook.test/tags/p.md': + return new Response('Tag: p'); + case 'https://nostrbook.test/protocol/relay.md': + return new Response('Protocol: relay'); + default: + return new Response('Not Found', { status: 404 }); + } + }; + + const client = new NostrbookClient({ + baseUrl: 'https://nostrbook.test', + fetch: mockFetch, + }); + + it('should read kind document', async () => { + const doc = await client.readKind(1); + expect(doc).toBe('Kind: 1'); + }); + + it('should read tag document', async () => { + const doc = await client.readTag('p'); + expect(doc).toBe('Tag: p'); + }); + + it('should read protocol document', async () => { + const doc = await client.readProtocol('relay'); + expect(doc).toBe('Protocol: relay'); + }); + + it('should throw HTTPError for 404 responses', async () => { + await expect(client.readKind(999)).rejects.toMatchObject({ + name: 'HTTPError', + message: 'HTTP Error: 404 GET https://nostrbook.test/kinds/999.md', + }); + }); +}); diff --git a/src/lib/NostrbookClient.ts b/src/lib/NostrbookClient.ts new file mode 100644 index 00000000..baa6895e --- /dev/null +++ b/src/lib/NostrbookClient.ts @@ -0,0 +1,53 @@ +import { HTTPError } from './HTTPError'; +import { llmstxtUrl } from './llmstxt'; + +/** Options for configuring the NostrbookClient */ +export interface NostrbookClientOpts { + /** Base URL of the Nostrbook service */ + baseUrl: URL | string; + /** Optional fetch function override */ + fetch?: typeof fetch; +} + +/** Client for interacting with Nostrbook documentation */ +export class NostrbookClient { + /** Base URL of the Nostrbook service */ + readonly baseUrl: URL; + + /** The fetch implementation to use for requests */ + private fetch: typeof fetch; + + constructor(opts: NostrbookClientOpts) { + this.baseUrl = new URL(opts.baseUrl); + this.fetch = opts.fetch ?? globalThis.fetch.bind(globalThis); + } + + /** Fetches content from a specific path on the Nostrbook service */ + async get(path: string): Promise { + const url = llmstxtUrl(new URL(path, this.baseUrl)); + + const request = new Request(url); + const response = await this.fetch(request); + + if (!response.ok) { + throw new HTTPError(response, request); + } + + return response.text(); + } + + /** Reads documentation for a specific Nostr event kind */ + readKind(kind: number): Promise { + return this.get(`/kinds/${kind}`); + } + + /** Reads documentation for a specific Nostr tag */ + readTag(tag: string): Promise { + return this.get(`/tags/${tag}`); + } + + /** Reads documentation for a specific Nostr protocol document */ + readProtocol(doc: string): Promise { + return this.get(`/protocol/${doc}`); + } +} \ No newline at end of file diff --git a/src/lib/fixtures/NIPs.md b/src/lib/fixtures/NIPs.md new file mode 100644 index 00000000..397eceb5 --- /dev/null +++ b/src/lib/fixtures/NIPs.md @@ -0,0 +1,402 @@ +# NIPs + +NIPs stand for **Nostr Implementation Possibilities**. + +They exist to document what may be implemented by [Nostr](https://github.com/nostr-protocol/nostr)-compatible _relay_ and _client_ software. + +--- + +- [List](#list) +- [Event Kinds](#event-kinds) +- [Message Types](#message-types) + - [Client to Relay](#client-to-relay) + - [Relay to Client](#relay-to-client) +- [Standardized Tags](#standardized-tags) +- [Criteria for acceptance of NIPs](#criteria-for-acceptance-of-nips) +- [Is this repository a centralizing factor?](#is-this-repository-a-centralizing-factor) +- [How this repository works](#how-this-repository-works) +- [Breaking Changes](#breaking-changes) +- [License](#license) + +--- + +## List + +- [NIP-01: Basic protocol flow description](01.md) +- [NIP-02: Follow List](02.md) +- [NIP-03: OpenTimestamps Attestations for Events](03.md) +- [NIP-04: Encrypted Direct Message](04.md) --- **unrecommended**: deprecated in favor of [NIP-17](17.md) +- [NIP-05: Mapping Nostr keys to DNS-based internet identifiers](05.md) +- [NIP-06: Basic key derivation from mnemonic seed phrase](06.md) +- [NIP-07: `window.nostr` capability for web browsers](07.md) +- [NIP-08: Handling Mentions](08.md) --- **unrecommended**: deprecated in favor of [NIP-27](27.md) +- [NIP-09: Event Deletion Request](09.md) +- [NIP-10: Text Notes and Threads](10.md) +- [NIP-11: Relay Information Document](11.md) +- [NIP-13: Proof of Work](13.md) +- [NIP-14: Subject tag in text events](14.md) +- [NIP-15: Nostr Marketplace (for resilient marketplaces)](15.md) +- [NIP-17: Private Direct Messages](17.md) +- [NIP-18: Reposts](18.md) +- [NIP-19: bech32-encoded entities](19.md) +- [NIP-21: `nostr:` URI scheme](21.md) +- [NIP-22: Comment](22.md) +- [NIP-23: Long-form Content](23.md) +- [NIP-24: Extra metadata fields and tags](24.md) +- [NIP-25: Reactions](25.md) +- [NIP-26: Delegated Event Signing](26.md) --- **unrecommended**: adds unecessary burden for little gain +- [NIP-27: Text Note References](27.md) +- [NIP-28: Public Chat](28.md) +- [NIP-29: Relay-based Groups](29.md) +- [NIP-30: Custom Emoji](30.md) +- [NIP-31: Dealing with Unknown Events](31.md) +- [NIP-32: Labeling](32.md) +- [NIP-34: `git` stuff](34.md) +- [NIP-35: Torrents](35.md) +- [NIP-36: Sensitive Content](36.md) +- [NIP-37: Draft Events](37.md) +- [NIP-38: User Statuses](38.md) +- [NIP-39: External Identities in Profiles](39.md) +- [NIP-40: Expiration Timestamp](40.md) +- [NIP-42: Authentication of clients to relays](42.md) +- [NIP-44: Encrypted Payloads (Versioned)](44.md) +- [NIP-45: Counting results](45.md) +- [NIP-46: Nostr Remote Signing](46.md) +- [NIP-47: Nostr Wallet Connect](47.md) +- [NIP-48: Proxy Tags](48.md) +- [NIP-49: Private Key Encryption](49.md) +- [NIP-50: Search Capability](50.md) +- [NIP-51: Lists](51.md) +- [NIP-52: Calendar Events](52.md) +- [NIP-53: Live Activities](53.md) +- [NIP-54: Wiki](54.md) +- [NIP-55: Android Signer Application](55.md) +- [NIP-56: Reporting](56.md) +- [NIP-57: Lightning Zaps](57.md) +- [NIP-58: Badges](58.md) +- [NIP-59: Gift Wrap](59.md) +- [NIP-60: Cashu Wallet](60.md) +- [NIP-61: Nutzaps](61.md) +- [NIP-62: Request to Vanish](62.md) +- [NIP-64: Chess (PGN)](64.md) +- [NIP-65: Relay List Metadata](65.md) +- [NIP-66: Relay Discovery and Liveness Monitoring](66.md) +- [NIP-68: Picture-first feeds](68.md) +- [NIP-69: Peer-to-peer Order events](69.md) +- [NIP-70: Protected Events](70.md) +- [NIP-71: Video Events](71.md) +- [NIP-72: Moderated Communities](72.md) +- [NIP-73: External Content IDs](73.md) +- [NIP-75: Zap Goals](75.md) +- [NIP-77: Negentropy Syncing](77.md) +- [NIP-78: Application-specific data](78.md) +- [NIP-7D: Threads](7D.md) +- [NIP-84: Highlights](84.md) +- [NIP-86: Relay Management API](86.md) +- [NIP-88: Polls](88.md) +- [NIP-89: Recommended Application Handlers](89.md) +- [NIP-90: Data Vending Machines](90.md) +- [NIP-92: Media Attachments](92.md) +- [NIP-94: File Metadata](94.md) +- [NIP-96: HTTP File Storage Integration](96.md) +- [NIP-98: HTTP Auth](98.md) +- [NIP-99: Classified Listings](99.md) +- [NIP-B0: Web Bookmarks](B0.md) +- [NIP-B7: Blossom](B7.md) +- [NIP-C0: Code Snippets](C0.md) +- [NIP-C7: Chats](C7.md) + +## Event Kinds + +| kind | description | NIP | +| ------------- | ------------------------------- | -------------------------------------- | +| `0` | User Metadata | [01](01.md) | +| `1` | Short Text Note | [10](10.md) | +| `2` | Recommend Relay | 01 (deprecated) | +| `3` | Follows | [02](02.md) | +| `4` | Encrypted Direct Messages | [04](04.md) | +| `5` | Event Deletion Request | [09](09.md) | +| `6` | Repost | [18](18.md) | +| `7` | Reaction | [25](25.md) | +| `8` | Badge Award | [58](58.md) | +| `9` | Chat Message | [C7](C7.md) | +| `10` | Group Chat Threaded Reply | 29 (deprecated) | +| `11` | Thread | [7D](7D.md) | +| `12` | Group Thread Reply | 29 (deprecated) | +| `13` | Seal | [59](59.md) | +| `14` | Direct Message | [17](17.md) | +| `15` | File Message | [17](17.md) | +| `16` | Generic Repost | [18](18.md) | +| `17` | Reaction to a website | [25](25.md) | +| `20` | Picture | [68](68.md) | +| `21` | Video Event | [71](71.md) | +| `22` | Short-form Portrait Video Event | [71](71.md) | +| `30` | internal reference | [NKBIP-03] | +| `31` | external web reference | [NKBIP-03] | +| `32` | hardcopy reference | [NKBIP-03] | +| `33` | prompt reference | [NKBIP-03] | +| `40` | Channel Creation | [28](28.md) | +| `41` | Channel Metadata | [28](28.md) | +| `42` | Channel Message | [28](28.md) | +| `43` | Channel Hide Message | [28](28.md) | +| `44` | Channel Mute User | [28](28.md) | +| `62` | Request to Vanish | [62](62.md) | +| `64` | Chess (PGN) | [64](64.md) | +| `818` | Merge Requests | [54](54.md) | +| `1018` | Poll Response | [88](88.md) | +| `1021` | Bid | [15](15.md) | +| `1022` | Bid confirmation | [15](15.md) | +| `1040` | OpenTimestamps | [03](03.md) | +| `1059` | Gift Wrap | [59](59.md) | +| `1063` | File Metadata | [94](94.md) | +| `1068` | Poll | [88](88.md) | +| `1111` | Comment | [22](22.md) | +| `1311` | Live Chat Message | [53](53.md) | +| `1337` | Code Snippet | [C0](C0.md) | +| `1617` | Patches | [34](34.md) | +| `1621` | Issues | [34](34.md) | +| `1622` | Git Replies (deprecated) | [34](34.md) | +| `1630`-`1633` | Status | [34](34.md) | +| `1971` | Problem Tracker | [nostrocket][nostrocket] | +| `1984` | Reporting | [56](56.md) | +| `1985` | Label | [32](32.md) | +| `1986` | Relay reviews | | +| `1987` | AI Embeddings / Vector lists | [NKBIP-02] | +| `2003` | Torrent | [35](35.md) | +| `2004` | Torrent Comment | [35](35.md) | +| `2022` | Coinjoin Pool | [joinstr][joinstr] | +| `4550` | Community Post Approval | [72](72.md) | +| `5000`-`5999` | Job Request | [90](90.md) | +| `6000`-`6999` | Job Result | [90](90.md) | +| `7000` | Job Feedback | [90](90.md) | +| `7374` | Reserved Cashu Wallet Tokens | [60](60.md) | +| `7375` | Cashu Wallet Tokens | [60](60.md) | +| `7376` | Cashu Wallet History | [60](60.md) | +| `9000`-`9030` | Group Control Events | [29](29.md) | +| `9041` | Zap Goal | [75](75.md) | +| `9321` | Nutzap | [61](61.md) | +| `9467` | Tidal login | [Tidal-nostr] | +| `9734` | Zap Request | [57](57.md) | +| `9735` | Zap | [57](57.md) | +| `9802` | Highlights | [84](84.md) | +| `10000` | Mute list | [51](51.md) | +| `10001` | Pin list | [51](51.md) | +| `10002` | Relay List Metadata | [65](65.md), [51](51.md) | +| `10003` | Bookmark list | [51](51.md) | +| `10004` | Communities list | [51](51.md) | +| `10005` | Public chats list | [51](51.md) | +| `10006` | Blocked relays list | [51](51.md) | +| `10007` | Search relays list | [51](51.md) | +| `10009` | User groups | [51](51.md), [29](29.md) | +| `10012` | Favorite relays list | [51](51.md) | +| `10013` | Private event relay list | [37](37.md) | +| `10015` | Interests list | [51](51.md) | +| `10019` | Nutzap Mint Recommendation | [61](61.md) | +| `10020` | Media follows | [51](51.md) | +| `10030` | User emoji list | [51](51.md) | +| `10050` | Relay list to receive DMs | [51](51.md), [17](17.md) | +| `10063` | User server list | [Blossom][blossom] | +| `10096` | File storage server list | [96](96.md) | +| `10166` | Relay Monitor Announcement | [66](66.md) | +| `13194` | Wallet Info | [47](47.md) | +| `17375` | Cashu Wallet Event | [60](60.md) | +| `21000` | Lightning Pub RPC | [Lightning.Pub][lnpub] | +| `22242` | Client Authentication | [42](42.md) | +| `23194` | Wallet Request | [47](47.md) | +| `23195` | Wallet Response | [47](47.md) | +| `24133` | Nostr Connect | [46](46.md) | +| `24242` | Blobs stored on mediaservers | [Blossom][blossom] | +| `27235` | HTTP Auth | [98](98.md) | +| `30000` | Follow sets | [51](51.md) | +| `30001` | Generic lists | 51 (deprecated) | +| `30002` | Relay sets | [51](51.md) | +| `30003` | Bookmark sets | [51](51.md) | +| `30004` | Curation sets | [51](51.md) | +| `30005` | Video sets | [51](51.md) | +| `30007` | Kind mute sets | [51](51.md) | +| `30008` | Profile Badges | [58](58.md) | +| `30009` | Badge Definition | [58](58.md) | +| `30015` | Interest sets | [51](51.md) | +| `30017` | Create or update a stall | [15](15.md) | +| `30018` | Create or update a product | [15](15.md) | +| `30019` | Marketplace UI/UX | [15](15.md) | +| `30020` | Product sold as an auction | [15](15.md) | +| `30023` | Long-form Content | [23](23.md) | +| `30024` | Draft Long-form Content | [23](23.md) | +| `30030` | Emoji sets | [51](51.md) | +| `30040` | Curated Publication Index | [NKBIP-01] | +| `30041` | Curated Publication Content | [NKBIP-01] | +| `30063` | Release artifact sets | [51](51.md) | +| `30078` | Application-specific Data | [78](78.md) | +| `30166` | Relay Discovery | [66](66.md) | +| `30267` | App curation sets | [51](51.md) | +| `30311` | Live Event | [53](53.md) | +| `30315` | User Statuses | [38](38.md) | +| `30388` | Slide Set | [Corny Chat][cornychat-slideset] | +| `30402` | Classified Listing | [99](99.md) | +| `30403` | Draft Classified Listing | [99](99.md) | +| `30617` | Repository announcements | [34](34.md) | +| `30618` | Repository state announcements | [34](34.md) | +| `30818` | Wiki article | [54](54.md) | +| `30819` | Redirects | [54](54.md) | +| `31234` | Draft Event | [37](37.md) | +| `31388` | Link Set | [Corny Chat][cornychat-linkset] | +| `31890` | Feed | [NUD: Custom Feeds][NUD: Custom Feeds] | +| `31922` | Date-Based Calendar Event | [52](52.md) | +| `31923` | Time-Based Calendar Event | [52](52.md) | +| `31924` | Calendar | [52](52.md) | +| `31925` | Calendar Event RSVP | [52](52.md) | +| `31989` | Handler recommendation | [89](89.md) | +| `31990` | Handler information | [89](89.md) | | +| `32267` | Software Application | | | +| `34550` | Community Definition | [72](72.md) | +| `38383` | Peer-to-peer Order events | [69](69.md) | +| `39000-9` | Group metadata events | [29](29.md) | +| `39089` | Starter packs | [51](51.md) | +| `39092` | Media starter packs | [51](51.md) | +| `39701` | Web bookmarks | [B0](B0.md) | + +[NUD: Custom Feeds]: https://wikifreedia.xyz/cip-01/ +[nostrocket]: https://github.com/nostrocket/NIPS/blob/main/Problems.md +[lnpub]: https://github.com/shocknet/Lightning.Pub/blob/master/proto/autogenerated/client.md +[cornychat-slideset]: https://cornychat.com/datatypes#kind30388slideset +[cornychat-linkset]: https://cornychat.com/datatypes#kind31388linkset +[joinstr]: https://gitlab.com/1440000bytes/joinstr/-/blob/main/NIP.md +[NKBIP-01]: https://wikistr.com/nkbip-01*fd208ee8c8f283780a9552896e4823cc9dc6bfd442063889577106940fd927c1 +[NKBIP-02]: https://wikistr.com/nkbip-02*fd208ee8c8f283780a9552896e4823cc9dc6bfd442063889577106940fd927c1 +[NKBIP-03]: https://wikistr.com/nkbip-03*fd208ee8c8f283780a9552896e4823cc9dc6bfd442063889577106940fd927c1 +[blossom]: https://github.com/hzrd149/blossom +[Tidal-nostr]: https://wikistr.com/tidal-nostr + +## Message types + +### Client to Relay + +| type | description | NIP | +| ------- | --------------------------------------------------- | ----------- | +| `EVENT` | used to publish events | [01](01.md) | +| `REQ` | used to request events and subscribe to new updates | [01](01.md) | +| `CLOSE` | used to stop previous subscriptions | [01](01.md) | +| `AUTH` | used to send authentication events | [42](42.md) | +| `COUNT` | used to request event counts | [45](45.md) | + +### Relay to Client + +| type | description | NIP | +| -------- | ------------------------------------------------------- | ----------- | +| `EOSE` | used to notify clients all stored events have been sent | [01](01.md) | +| `EVENT` | used to send events requested to clients | [01](01.md) | +| `NOTICE` | used to send human-readable messages to clients | [01](01.md) | +| `OK` | used to notify clients if an EVENT was successful | [01](01.md) | +| `CLOSED` | used to notify clients that a REQ was ended and why | [01](01.md) | +| `AUTH` | used to send authentication challenges | [42](42.md) | +| `COUNT` | used to send requested event counts to clients | [45](45.md) | + +## Standardized Tags + +| name | value | other parameters | NIP | +| ----------------- | ------------------------------------ | ------------------------------- | -------------------------------------------------- | +| `a` | coordinates to an event | relay URL | [01](01.md) | +| `A` | root address | relay URL | [22](22.md) | +| `d` | identifier | -- | [01](01.md) | +| `e` | event id (hex) | relay URL, marker, pubkey (hex) | [01](01.md), [10](10.md) | +| `E` | root event id | relay URL | [22](22.md) | +| `f` | currency code | -- | [69](69.md) | +| `g` | geohash | -- | [52](52.md) | +| `h` | group id | -- | [29](29.md) | +| `i` | external identity | proof, url hint | [35](35.md), [39](39.md), [73](73.md) | +| `I` | root external identity | -- | [22](22.md) | +| `k` | kind | -- | [18](18.md), [25](25.md), [72](72.md), [73](73.md) | +| `K` | root scope | -- | [22](22.md) | +| `l` | label, label namespace, language name| -- | [32](32.md), [C0](C0.md) | +| `L` | label namespace | -- | [32](32.md) | +| `m` | MIME type | -- | [94](94.md) | +| `p` | pubkey (hex) | relay URL, petname | [01](01.md), [02](02.md), [22](22.md) | +| `P` | pubkey (hex) | -- | [22](22.md), [57](57.md) | +| `q` | event id (hex) | relay URL, pubkey (hex) | [18](18.md) | +| `r` | a reference (URL, etc) | -- | [24](24.md), [25](25.md) | +| `r` | relay url | marker | [65](65.md) | +| `s` | status | -- | [69](69.md) | +| `t` | hashtag | -- | [24](24.md), [34](34.md), [35](35.md) | +| `u` | url | -- | [61](61.md), [98](98.md) | +| `x` | hash | -- | [35](35.md), [56](56.md) | +| `y` | platform | -- | [69](69.md) | +| `z` | order number | -- | [69](69.md) | +| `-` | -- | -- | [70](70.md) | +| `alt` | summary | -- | [31](31.md) | +| `amount` | millisatoshis, stringified | -- | [57](57.md) | +| `bolt11` | `bolt11` invoice | -- | [57](57.md) | +| `challenge` | challenge string | -- | [42](42.md) | +| `client` | name, address | relay URL | [89](89.md) | +| `clone` | git clone URL | -- | [34](34.md) | +| `content-warning` | reason | -- | [36](36.md) | +| `delegation` | pubkey, conditions, delegation token | -- | [26](26.md) | +| `dep` | Required dependency | -- | [C0](C0.md) | +| `description` | description | -- | [34](34.md), [57](57.md), [58](58.md), [C0](C0.md) | +| `emoji` | shortcode, image URL | -- | [30](30.md) | +| `encrypted` | -- | -- | [90](90.md) | +| `extension` | File extension | -- | [C0](C0.md) | +| `expiration` | unix timestamp (string) | -- | [40](40.md) | +| `file` | full path (string) | -- | [35](35.md) | +| `goal` | event id (hex) | relay URL | [75](75.md) | +| `image` | image URL | dimensions in pixels | [23](23.md), [52](52.md), [58](58.md) | +| `imeta` | inline metadata | -- | [92](92.md) | +| `license` | License of the shared content | -- | [C0](C0.md) | +| `lnurl` | `bech32` encoded `lnurl` | -- | [57](57.md) | +| `location` | location string | -- | [52](52.md), [99](99.md) | +| `name` | name | -- | [34](34.md), [58](58.md), [72](72.md), [C0](C0.md) | +| `nonce` | random | difficulty | [13](13.md) | +| `preimage` | hash of `bolt11` invoice | -- | [57](57.md) | +| `price` | price | currency, frequency | [99](99.md) | +| `proxy` | external ID | protocol | [48](48.md) | +| `published_at` | unix timestamp (string) | -- | [23](23.md), [B0](B0.md) | +| `relay` | relay url | -- | [42](42.md), [17](17.md) | +| `relays` | relay list | -- | [57](57.md) | +| `repo` | Reference to the origin repository | -- | [C0](C0.md) | +| `runtime` | Runtime or environment specification | -- | [C0](C0.md) | +| `server` | file storage server url | -- | [96](96.md) | +| `subject` | subject | -- | [14](14.md), [17](17.md), [34](34.md) | +| `summary` | summary | -- | [23](23.md), [52](52.md) | +| `thumb` | badge thumbnail | dimensions in pixels | [58](58.md) | +| `title` | title | -- | [23](23.md), [B0](B0.md) | +| `tracker` | torrent tracker URL | -- | [35](35.md) | +| `web` | webpage URL | -- | [34](34.md) | +| `zap` | pubkey (hex), relay URL | weight | [57](57.md) | + +Please update these lists when proposing new NIPs. + +## Criteria for acceptance of NIPs + +1. They should be fully implemented in at least two clients and one relay -- when applicable. +2. They should make sense. +3. They should be optional and backwards-compatible: care must be taken such that clients and relays that choose to not implement them do not stop working when interacting with the ones that choose to. +4. There should be no more than one way of doing the same thing. +5. Other rules will be made up when necessary. + +## Is this repository a centralizing factor? + +To promote interoperability, we need standards that everybody can follow, and we need them to define a **single way of doing each thing** without ever hurting **backwards-compatibility**, and for that purpose there is no way around getting everybody to agree on the same thing and keep a centralized index of these standards. However the fact that such an index exists doesn't hurt the decentralization of Nostr. _At any point the central index can be challenged if it is failing to fulfill the needs of the protocol_ and it can migrate to other places and be maintained by other people. + +It can even fork into multiple versions, and then some clients would go one way, others would go another way, and some clients would adhere to both competing standards. This would hurt the simplicity, openness and interoperability of Nostr a little, but everything would still work in the short term. + +There is a list of notable Nostr software developers who have commit access to this repository, but that exists mostly for practical reasons, as by the nature of the thing we're dealing with the repository owner can revoke membership and rewrite history as they want -- and if these actions are unjustified or perceived as bad or evil the community must react. + +## How this repository works + +Standards may emerge in two ways: the first way is that someone starts doing something, then others copy it; the second way is that someone has an idea of a new standard that could benefit multiple clients and the protocol in general without breaking **backwards-compatibility** and the principle of having **a single way of doing things**, then they write that idea and submit it to this repository, other interested parties read it and give their feedback, then once most people reasonably agree we codify that in a NIP which client and relay developers that are interested in the feature can proceed to implement. + +These two ways of standardizing things are supported by this repository. Although the second is preferred, an effort will be made to codify standards emerged outside this repository into NIPs that can be later referenced and easily understood and implemented by others -- but obviously as in any human system discretion may be applied when standards are considered harmful. + +## Breaking Changes + +[Breaking Changes](BREAKING.md) + +## License + +All NIPs are public domain. + +## Contributors + + + + diff --git a/src/lib/llmstxt.test.ts b/src/lib/llmstxt.test.ts new file mode 100644 index 00000000..64a0f561 --- /dev/null +++ b/src/lib/llmstxt.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect } from 'vitest'; + +import { llmstxtUrl } from './llmstxt.ts'; + +describe('llmstxtUrl', () => { + it('should convert URLs to llmstxt format correctly', () => { + const testCases = [ + { + input: 'https://example.com', + expected: 'https://example.com/index.md', + }, + { + input: 'https://example.com/', + expected: 'https://example.com/index.md', + }, + { + input: 'https://example.com/test', + expected: 'https://example.com/test.md', + }, + { + input: 'https://example.com/test/', + expected: 'https://example.com/test/index.md', + }, + { + input: 'https://example.com/test.md', + expected: 'https://example.com/test.md', + }, + ]; + + for (const { input, expected } of testCases) { + const result = llmstxtUrl(input); + expect(result.toString()).toBe(expected); + } + }); +}); diff --git a/src/lib/llmstxt.ts b/src/lib/llmstxt.ts new file mode 100644 index 00000000..e9e015d0 --- /dev/null +++ b/src/lib/llmstxt.ts @@ -0,0 +1,19 @@ +/** + * Adds a markdown extension to the URL according to the + * [llms.txt](https://llmstxt.org/) specification. + */ +export function llmstxtUrl(url: URL | string): URL { + url = new URL(url); + + if (url.pathname.endsWith('.md')) { + return url; + } + + if (url.pathname.endsWith('/')) { + url.pathname += 'index.md'; + } else { + url.pathname += '.md'; + } + + return url; +} \ No newline at end of file diff --git a/src/lib/tools/NostrFetchEventTool.ts b/src/lib/tools/NostrFetchEventTool.ts new file mode 100644 index 00000000..a571123c --- /dev/null +++ b/src/lib/tools/NostrFetchEventTool.ts @@ -0,0 +1,184 @@ +import { z } from "zod"; +import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify'; +import { nip19 } from 'nostr-tools'; + +import type { Tool } from "./Tool"; + +interface NostrFetchEventParams { + identifier: string; +} + +export class NostrFetchEventTool implements Tool { + readonly description = "Fetch a Nostr event using a nip19 identifier"; + + readonly inputSchema = z.object({ + identifier: z + .string() + .superRefine((val, ctx) => { + let decoded: nip19.DecodedResult; + try { + decoded = nip19.decode(val); + } catch { + ctx.addIssue({ + code: 'custom', + message: + `Failed to decode identifier. Invalid NIP-19 identifier: ${val}`, + }); + return; + } + + // Reject nsec for security reasons + if (decoded.type === 'nsec') { + ctx.addIssue({ + code: 'custom', + message: + 'nsec identifiers are not supported for security reasons', + }); + return; + } + + // Accept npub, nprofile, naddr, note, nevent + if (!['npub', 'nprofile', 'naddr', 'note', 'nevent'].includes(decoded.type)) { + ctx.addIssue({ + code: 'custom', + message: + `Unsupported identifier type: ${decoded.type}. Supported types: npub, nprofile, naddr, note, nevent`, + }); + return; + } + }) + .describe( + 'NIP-19 identifier (npub, nprofile, naddr, note, or nevent), e.g. npub1... or naddr1...', + ), + }); + + async execute(args: NostrFetchEventParams): Promise { + const { identifier } = args; + + const decoded = nip19.decode(identifier); + + const defaultRelays = [ + 'wss://ditto.pub/relay', + 'wss://relay.nostr.band', + 'wss://relay.primal.net', + ]; + + const pool = new NPool({ + open(url) { + return new NRelay1(url); + }, + eventRouter() { + return [...defaultRelays]; + }, + reqRouter(filters) { + return new Map( + [...defaultRelays].map((url) => [url, filters]), + ); + }, + }); + + try { + let event: NostrEvent | undefined; + + switch (decoded.type) { + case 'npub': { + // For npub, fetch the user's kind 0 (profile) event + [event] = await pool.query( + [{ + kinds: [0], + authors: [decoded.data], + limit: 1, + }], + { signal: AbortSignal.timeout(8_000) }, + ); + break; + } + + case 'nprofile': { + // For nprofile, fetch the user's kind 0 (profile) event + let { relays } = decoded.data; + + if (!relays || !relays.length) { + relays = defaultRelays; + } + + [event] = await pool.group(relays).query( + [{ + kinds: [0], + authors: [decoded.data.pubkey], + limit: 1, + }], + { signal: AbortSignal.timeout(8_000) }, + ); + break; + } + + case 'note': { + // For note, fetch the specific event by ID + [event] = await pool.query( + [{ ids: [decoded.data] }], + { signal: AbortSignal.timeout(8_000) }, + ); + break; + } + + case 'nevent': { + // For nevent, fetch the specific event by ID + let { relays } = decoded.data; + + if (!relays || !relays.length) { + relays = defaultRelays; + } + + [event] = await pool.group(relays).query( + [{ + ids: [decoded.data.id], + }], + { signal: AbortSignal.timeout(8_000) }, + ); + break; + } + + case 'naddr': { + // For naddr, fetch by kind, pubkey, and d tag + let { relays } = decoded.data; + + if (!relays || !relays.length) { + relays = defaultRelays; + } + + [event] = await pool.group(relays).query( + [{ + kinds: [decoded.data.kind], + authors: [decoded.data.pubkey], + '#d': [decoded.data.identifier], + }], + { signal: AbortSignal.timeout(8_000) }, + ); + break; + } + + default: + throw new Error(`Unsupported identifier type: ${decoded.type}`); + } + + if (!event) { + throw new Error('No event found for the provided identifier. Make sure it exists and is accessible.'); + } + + // Special handling for specific kinds + if (event.kind === 30817) { + // Kind 30817 is a NIP document, return just the content + return event.content; + } + + // For other kinds, return the full event JSON + return JSON.stringify(event, null, 2); + + } catch (error) { + throw new Error(`Error fetching event: ${error instanceof Error ? error.message : 'Unknown error'}`); + } finally { + await pool.close(); + } + } +} \ No newline at end of file diff --git a/src/lib/tools/NostrGenerateKindTool.ts b/src/lib/tools/NostrGenerateKindTool.ts new file mode 100644 index 00000000..37e3918e --- /dev/null +++ b/src/lib/tools/NostrGenerateKindTool.ts @@ -0,0 +1,47 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import { KindGenerator, type KindRange } from "../KindGenerator"; +import { NIPsClient } from "../NIPsClient"; + +interface NostrGenerateKindParams { + range: KindRange; +} + +export class NostrGenerateKindTool implements Tool { + private nipsClient: NIPsClient; + + readonly description = "Generate an unused Nostr event kind number in the specified range"; + + readonly inputSchema = z.object({ + range: z.enum(['regular', 'replaceable', 'ephemeral', 'addressable']) + .describe( + 'Kind range: regular (1000-9999), replaceable (10000-19999), ephemeral (20000-29999), addressable (30000-39999)', + ) as z.ZodType, + }); + + constructor() { + this.nipsClient = new NIPsClient({ + urlTemplate: 'https://raw.githubusercontent.com/nostr-protocol/nips/refs/heads/master/{nip}.md', + }); + } + + async execute(args: NostrGenerateKindParams): Promise { + const { range } = args; + + try { + const nipsIndex = await this.nipsClient.readIndex(); + const usedKinds = KindGenerator.extractUsedKinds(nipsIndex); + const availableKind = KindGenerator.generateAvailableKind( + range, + usedKinds, + ); + + const rangeInfo = KindGenerator.getKindRangeInfo(range); + + return `Generated unused kind: ${availableKind}\n\nRange: ${rangeInfo.name} (${rangeInfo.min}-${rangeInfo.max})\nDescription: ${rangeInfo.description}\n\nThis kind number is currently not used by any official NIP.`; + } catch (error) { + throw new Error(`Error generating kind: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/tools/NostrReadKindTool.ts b/src/lib/tools/NostrReadKindTool.ts new file mode 100644 index 00000000..597f5de4 --- /dev/null +++ b/src/lib/tools/NostrReadKindTool.ts @@ -0,0 +1,41 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import { NostrbookClient } from "../NostrbookClient"; +import { HTTPError } from "../HTTPError"; + +interface NostrReadKindParams { + kind: number; +} + +export class NostrReadKindTool implements Tool { + private nostrbookClient: NostrbookClient; + + readonly description = "Read Nostr documentation about a specific event kind"; + + readonly inputSchema = z.object({ + kind: z.number().describe('Kind number to retrieve, e.g. `1` or `42`'), + }); + + constructor() { + this.nostrbookClient = new NostrbookClient({ + baseUrl: 'https://nostrbook.dev', + }); + } + + async execute(args: NostrReadKindParams): Promise { + const { kind } = args; + + try { + const text = await this.nostrbookClient.readKind(kind); + return text; + } catch (error) { + if (error instanceof HTTPError && error.response.status === 404) { + throw new Error( + `No documentation found for kind ${kind}. Try using the \`nostr_read_nips_index\` tool to see if it's specified by a NIP.` + ); + } + throw new Error(`Error reading kind ${kind}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/tools/NostrReadNipTool.ts b/src/lib/tools/NostrReadNipTool.ts new file mode 100644 index 00000000..71f0be32 --- /dev/null +++ b/src/lib/tools/NostrReadNipTool.ts @@ -0,0 +1,48 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import { NIPsClient } from "../NIPsClient"; +import { HTTPError } from "../HTTPError"; + +interface NostrReadNipParams { + nip: string; +} + +export class NostrReadNipTool implements Tool { + private nipsClient: NIPsClient; + + readonly description = "Read a Nostr NIP document"; + + readonly inputSchema = z.object({ + nip: z + .string() + .length(2) + .regex( + /^[0-9A-F]{2}$/, + 'NIP must be a 2-digit uppercase hex string, e.g. `01` or `C7`', + ) + .describe('NIP to retrieve, e.g. `01` or `C7`'), + }); + + constructor() { + this.nipsClient = new NIPsClient({ + urlTemplate: 'https://raw.githubusercontent.com/nostr-protocol/nips/refs/heads/master/{nip}.md', + }); + } + + async execute(args: NostrReadNipParams): Promise { + const { nip } = args; + + try { + const text = await this.nipsClient.readNip(nip); + return text; + } catch (error) { + if (error instanceof HTTPError && error.response.status === 404) { + throw new Error( + `NIP-${nip} does not exist in the official NIPs repository. Try using the \`nostr_read_nips_index\` tool to retrieve the full list of NIPs.` + ); + } + throw new Error(`Error reading NIP-${nip}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/tools/NostrReadNipsIndexTool.ts b/src/lib/tools/NostrReadNipsIndexTool.ts new file mode 100644 index 00000000..f5727534 --- /dev/null +++ b/src/lib/tools/NostrReadNipsIndexTool.ts @@ -0,0 +1,27 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import { NIPsClient } from "../NIPsClient"; + +export class NostrReadNipsIndexTool implements Tool { + private nipsClient: NIPsClient; + + readonly description = "Read the full list of NIPs, kinds, and tags"; + + readonly inputSchema = z.object({}); + + constructor() { + this.nipsClient = new NIPsClient({ + urlTemplate: 'https://raw.githubusercontent.com/nostr-protocol/nips/refs/heads/master/{nip}.md', + }); + } + + async execute(_args: object): Promise { + try { + const text = await this.nipsClient.readIndex(); + return text; + } catch (error) { + throw new Error(`Error reading NIPs index: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/tools/NostrReadProtocolTool.ts b/src/lib/tools/NostrReadProtocolTool.ts new file mode 100644 index 00000000..74cb8725 --- /dev/null +++ b/src/lib/tools/NostrReadProtocolTool.ts @@ -0,0 +1,35 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import { NostrbookClient } from "../NostrbookClient"; + +interface NostrReadProtocolParams { + doc: 'index' | 'event' | 'filter' | 'client' | 'relay'; +} + +export class NostrReadProtocolTool implements Tool { + private nostrbookClient: NostrbookClient; + + readonly description = "Read Nostr protocol basics"; + + readonly inputSchema = z.object({ + doc: z.enum(['index', 'event', 'filter', 'client', 'relay']), + }); + + constructor() { + this.nostrbookClient = new NostrbookClient({ + baseUrl: 'https://nostrbook.dev', + }); + } + + async execute(args: NostrReadProtocolParams): Promise { + const { doc } = args; + + try { + const text = await this.nostrbookClient.readProtocol(doc); + return text; + } catch (error) { + throw new Error(`Error reading protocol doc "${doc}": ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/tools/NostrReadTagTool.ts b/src/lib/tools/NostrReadTagTool.ts new file mode 100644 index 00000000..b7ba59e2 --- /dev/null +++ b/src/lib/tools/NostrReadTagTool.ts @@ -0,0 +1,41 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import { NostrbookClient } from "../NostrbookClient"; +import { HTTPError } from "../HTTPError"; + +interface NostrReadTagParams { + tag: string; +} + +export class NostrReadTagTool implements Tool { + private nostrbookClient: NostrbookClient; + + readonly description = "Read Nostr documentation about a specific tag"; + + readonly inputSchema = z.object({ + tag: z.string().describe('Tag name to retrieve, e.g. `p` or `e`'), + }); + + constructor() { + this.nostrbookClient = new NostrbookClient({ + baseUrl: 'https://nostrbook.dev', + }); + } + + async execute(args: NostrReadTagParams): Promise { + const { tag } = args; + + try { + const text = await this.nostrbookClient.readTag(tag); + return text; + } catch (error) { + if (error instanceof HTTPError && error.response.status === 404) { + throw new Error( + `No documentation found for the "${tag}" tag. Try using the \`nostr_read_nips_index\` tool to see if it's specified by a NIP.` + ); + } + throw new Error(`Error reading tag "${tag}": ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file