Add nostr_encode and nostr_decode AI tools for NIP-19 bech32 encoding/decoding

This commit is contained in:
Alex Gleason committed 2026-03-06 12:16:56 -06:00
1 parent 7a2873aefb
commit 556cc10f3a
4 files changed
+204

No files matched your search

+2
View File
@@ -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
+4
View File
@@ -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<ChatPaneRef, ChatPaneProps>(({
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),
+52
View File
@@ -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<NostrDecodeParams> {
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<ToolResult> {
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'}`);
}
}
}
+146
View File
@@ -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<NostrEncodeParams> {
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<ToolResult> {
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'}`);
}
}
}