From 556cc10f3acd44b82b3b54c3e6e213d72169a0f8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 6 Mar 2026 12:13:18 -0600 Subject: [PATCH] Add nostr_encode and nostr_decode AI tools for NIP-19 bech32 encoding/decoding --- AGENTS.md | 2 + src/components/Shakespeare/ChatPane.tsx | 4 + src/lib/tools/NostrDecodeTool.ts | 52 +++++++++ src/lib/tools/NostrEncodeTool.ts | 146 ++++++++++++++++++++++++ 4 files changed, 204 insertions(+) create mode 100644 src/lib/tools/NostrDecodeTool.ts create mode 100644 src/lib/tools/NostrEncodeTool.ts diff --git a/AGENTS.md b/AGENTS.md index dead4b63..62a8f790 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,8 @@ Shakespeare provides AI agents with specialized tools for project development (n - **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags - **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers - **NostrGenerateKindTool**: Generate unused Nostr event kind numbers +- **NostrEncodeTool**: Encode hex values into NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr) +- **NostrDecodeTool**: Decode NIP-19 bech32 entities into hex and structured data - **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities #### Shell Commands diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 01e3e3b0..09b5abc8 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -35,6 +35,8 @@ import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool'; import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool'; +import { NostrEncodeTool } from '@/lib/tools/NostrEncodeTool'; +import { NostrDecodeTool } from '@/lib/tools/NostrDecodeTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; import { SkillTool } from '@/lib/tools/SkillTool'; @@ -217,6 +219,8 @@ export const ChatPane = forwardRef(({ nostr_read_nips_index: new NostrReadNipsIndexTool(), nostr_generate_kind: new NostrGenerateKindTool(), nostr_publish_events: new NostrPublishEventsTool(), + nostr_encode: new NostrEncodeTool(), + nostr_decode: new NostrDecodeTool(), shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer), read_console_messages: new ReadConsoleMessagesTool(), skill: new SkillTool(fs, availableSkills), diff --git a/src/lib/tools/NostrDecodeTool.ts b/src/lib/tools/NostrDecodeTool.ts new file mode 100644 index 00000000..860cd222 --- /dev/null +++ b/src/lib/tools/NostrDecodeTool.ts @@ -0,0 +1,52 @@ +import { z } from "zod"; +import { nip19 } from 'nostr-tools'; + +import type { Tool, ToolResult } from "./Tool"; + +interface NostrDecodeParams { + value: string; +} + +export class NostrDecodeTool implements Tool { + readonly description = "Decode NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr, nsec) into their hex and structured data representations"; + + readonly inputSchema = z.object({ + value: z.string() + .superRefine((val, ctx) => { + // Strip nostr: URI prefix if present (NIP-21) + const cleaned = val.startsWith('nostr:') ? val.slice(6) : val; + + try { + nip19.decode(cleaned); + } catch { + ctx.addIssue({ + code: 'custom', + message: `Invalid NIP-19 identifier: ${val}. Expected an npub, note, nprofile, nevent, naddr, or nsec string.`, + }); + } + }) + .describe( + 'A NIP-19 bech32-encoded identifier to decode (npub1..., note1..., nprofile1..., nevent1..., naddr1...). Also accepts nostr: URI prefix (NIP-21).', + ), + }); + + async execute(args: NostrDecodeParams): Promise { + const { value } = args; + + // Strip nostr: URI prefix if present (NIP-21) + const cleaned = value.startsWith('nostr:') ? value.slice(6) : value; + + try { + const decoded = nip19.decode(cleaned); + + // Reject nsec for security reasons + if (decoded.type === 'nsec') { + throw new Error('nsec identifiers should not be shared or decoded in this context for security reasons'); + } + + return { content: JSON.stringify(decoded, null, 2) }; + } catch (error) { + throw new Error(`Error decoding NIP-19 value: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} diff --git a/src/lib/tools/NostrEncodeTool.ts b/src/lib/tools/NostrEncodeTool.ts new file mode 100644 index 00000000..4a04cb75 --- /dev/null +++ b/src/lib/tools/NostrEncodeTool.ts @@ -0,0 +1,146 @@ +import { z } from "zod"; +import { nip19 } from 'nostr-tools'; + +import type { Tool, ToolResult } from "./Tool"; + +type NostrEncodeType = 'npub' | 'note' | 'nprofile' | 'nevent' | 'naddr'; + +interface NostrEncodeParams { + type: NostrEncodeType; + hex: string; + relays?: string[]; + author?: string; + kind?: number; + identifier?: string; +} + +const HEX_64_REGEX = /^[0-9a-f]{64}$/; + +export class NostrEncodeTool implements Tool { + readonly description = "Encode hex values into NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr)"; + + readonly inputSchema = z.object({ + type: z.enum(['npub', 'note', 'nprofile', 'nevent', 'naddr']) + .describe( + 'The NIP-19 entity type to encode: npub (public key), note (event id), nprofile (profile with relay hints), nevent (event with relay hints and author), naddr (addressable event coordinate)', + ), + hex: z.string() + .describe( + 'The hex string to encode. For npub/nprofile this is a 64-char hex public key. For note/nevent this is a 64-char hex event id. For naddr this is not used directly (use identifier instead), but should be set to the author pubkey.', + ), + relays: z.array(z.string()) + .optional() + .describe( + 'Optional relay URL hints to attach. Used with nprofile, nevent, and naddr types.', + ), + author: z.string() + .optional() + .describe( + 'Optional author pubkey (64-char hex) to attach as a hint. Used with nevent type.', + ), + kind: z.number() + .optional() + .describe( + 'Event kind number. Required for naddr type.', + ), + identifier: z.string() + .optional() + .describe( + 'The "d" tag identifier for addressable events. Required for naddr type.', + ), + }).superRefine((data, ctx) => { + // Validate hex for types that need it + if (['npub', 'note', 'nprofile', 'nevent'].includes(data.type)) { + if (!HEX_64_REGEX.test(data.hex)) { + ctx.addIssue({ + code: 'custom', + path: ['hex'], + message: 'hex must be a 64-character lowercase hex string', + }); + } + } + + // Validate author hex if provided + if (data.author && !HEX_64_REGEX.test(data.author)) { + ctx.addIssue({ + code: 'custom', + path: ['author'], + message: 'author must be a 64-character lowercase hex public key', + }); + } + + // Validate naddr-specific requirements + if (data.type === 'naddr') { + if (!HEX_64_REGEX.test(data.hex)) { + ctx.addIssue({ + code: 'custom', + path: ['hex'], + message: 'For naddr, hex must be the 64-character lowercase hex author pubkey', + }); + } + if (data.kind === undefined) { + ctx.addIssue({ + code: 'custom', + path: ['kind'], + message: 'kind is required for naddr encoding', + }); + } + if (data.identifier === undefined) { + ctx.addIssue({ + code: 'custom', + path: ['identifier'], + message: 'identifier (d tag) is required for naddr encoding', + }); + } + } + }); + + async execute(args: NostrEncodeParams): Promise { + const { type, hex, relays, author, kind, identifier } = args; + + try { + let encoded: string; + + switch (type) { + case 'npub': { + encoded = nip19.npubEncode(hex); + break; + } + case 'note': { + encoded = nip19.noteEncode(hex); + break; + } + case 'nprofile': { + encoded = nip19.nprofileEncode({ + pubkey: hex, + relays: relays || [], + }); + break; + } + case 'nevent': { + encoded = nip19.neventEncode({ + id: hex, + relays: relays || [], + author: author, + }); + break; + } + case 'naddr': { + encoded = nip19.naddrEncode({ + pubkey: hex, + kind: kind!, + identifier: identifier || '', + relays: relays || [], + }); + break; + } + default: + throw new Error(`Unsupported encode type: ${type}`); + } + + return { content: encoded }; + } catch (error) { + throw new Error(`Error encoding to ${type}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +}