From e1d85e66be6762840d500568eac04578f4949558 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 3 Nov 2025 22:59:29 -0600 Subject: [PATCH] Add nostr_publish_events tool --- src/components/AIMessageItem.tsx | 9 +- src/components/Shakespeare/ChatPane.tsx | 2 + src/lib/tools/NostrPublishEventsTool.test.ts | 180 +++++++++++++++++++ src/lib/tools/NostrPublishEventsTool.ts | 124 +++++++++++++ 4 files changed, 314 insertions(+), 1 deletion(-) create mode 100644 src/lib/tools/NostrPublishEventsTool.test.ts create mode 100644 src/lib/tools/NostrPublishEventsTool.ts diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index 60f81b80..0923f1f1 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -1,6 +1,6 @@ import { memo, useState } from 'react'; import { Streamdown } from 'streamdown'; -import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react'; +import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs, Send } from 'lucide-react'; import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import { UserMessage } from '@/components/UserMessage'; @@ -141,6 +141,13 @@ export const AIMessageItem = memo(({ icon: Plus, title: args.range ? `Generated ${args.range} kind` : 'Generated Kind' }; + case 'nostr_publish_events': { + const eventCount = args.events?.length || 0; + return { + icon: Send, + title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event' + }; + } case 'deploy_project': return { icon: Globe, diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index b98939af..ecd1a5d4 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -29,6 +29,7 @@ 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 { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; @@ -154,6 +155,7 @@ export const ChatPane = forwardRef(({ nostr_read_protocol: new NostrReadProtocolTool(), nostr_read_nips_index: new NostrReadNipsIndexTool(), nostr_generate_kind: new NostrGenerateKindTool(), + nostr_publish_events: new NostrPublishEventsTool(), shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer), read_console_messages: new ReadConsoleMessagesTool(), }; diff --git a/src/lib/tools/NostrPublishEventsTool.test.ts b/src/lib/tools/NostrPublishEventsTool.test.ts new file mode 100644 index 00000000..09db4ef0 --- /dev/null +++ b/src/lib/tools/NostrPublishEventsTool.test.ts @@ -0,0 +1,180 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { NostrPublishEventsTool } from './NostrPublishEventsTool'; + +// Mock nostr-tools to avoid crypto issues in test environment +vi.mock('nostr-tools', () => ({ + generateSecretKey: vi.fn(() => new Uint8Array(32).fill(1)), + getPublicKey: vi.fn(() => 'test-pubkey-1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'), + finalizeEvent: vi.fn((template, _secretKey) => ({ + ...template, + pubkey: 'test-pubkey-1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', + id: 'test-event-id-1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', + sig: 'test-signature-1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', + })), +})); + +// Mock NPool to avoid actual network calls +vi.mock('@nostrify/nostrify', () => ({ + NPool: vi.fn().mockImplementation(() => ({ + event: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + })), + NRelay1: vi.fn(), +})); + +describe('NostrPublishEventsTool', () => { + let tool: NostrPublishEventsTool; + + beforeEach(() => { + tool = new NostrPublishEventsTool(); + }); + + it('should have correct description', () => { + expect(tool.description).toContain('Publish Nostr events'); + expect(tool.description).toContain('ephemeral keypair'); + }); + + it('should validate input schema', () => { + // Valid input + expect(() => + tool.inputSchema.parse({ + events: [{ kind: 1, content: 'hello world' }], + }) + ).not.toThrow(); + + // Valid with relays + expect(() => + tool.inputSchema.parse({ + events: [{ kind: 1, content: 'hello' }], + relays: ['wss://relay.example.com'], + }) + ).not.toThrow(); + + // Invalid: empty events array + expect(() => + tool.inputSchema.parse({ + events: [], + }) + ).toThrow(); + + // Invalid: invalid kind + expect(() => + tool.inputSchema.parse({ + events: [{ kind: -1 }], + }) + ).toThrow(); + + // Invalid: invalid relay URL + expect(() => + tool.inputSchema.parse({ + events: [{ kind: 1 }], + relays: ['not-a-url'], + }) + ).toThrow(); + }); + + it('should publish events with default values', async () => { + const result = await tool.execute({ + events: [{}], + }); + + const parsed = JSON.parse(result); + expect(parsed.success).toBe(true); + expect(parsed.pubkey).toBeDefined(); + expect(parsed.events_published).toBe(2); // kind 0 + 1 user event + expect(parsed.events).toHaveLength(2); + expect(parsed.events[0].kind).toBe(0); // Profile event + expect(parsed.events[1].kind).toBe(1); // Default kind + }); + + it('should publish multiple events with custom values', async () => { + const result = await tool.execute({ + events: [ + { kind: 1, content: 'hello world', tags: [['t', 'test']] }, + { kind: 30023, content: '# Article', tags: [['d', 'my-article']] }, + ], + }); + + const parsed = JSON.parse(result); + expect(parsed.success).toBe(true); + expect(parsed.events_published).toBe(3); // kind 0 + 2 user events + expect(parsed.events[1].kind).toBe(1); + expect(parsed.events[1].content).toBe('hello world'); + expect(parsed.events[2].kind).toBe(30023); + }); + + it('should use custom relays when provided', async () => { + const customRelays = ['wss://relay.custom1.com', 'wss://relay.custom2.com']; + const result = await tool.execute({ + events: [{ kind: 1, content: 'test' }], + relays: customRelays, + }); + + const parsed = JSON.parse(result); + expect(parsed.relays).toEqual(customRelays); + }); + + it('should truncate long content in response', async () => { + const longContent = 'a'.repeat(150); + const result = await tool.execute({ + events: [{ kind: 1, content: longContent }], + }); + + const parsed = JSON.parse(result); + expect(parsed.events[1].content).toHaveLength(103); // 100 chars + '...' + expect(parsed.events[1].content).toMatch(/^a+\.\.\.$/); + }); + + it('should set created_at to current time by default', async () => { + const beforeTime = Math.floor(Date.now() / 1000); + await tool.execute({ + events: [{ kind: 1, content: 'test' }], + }); + const afterTime = Math.floor(Date.now() / 1000); + + // We can't directly check the created_at in the mocked version, + // but we can verify the tool doesn't throw and executes successfully + expect(beforeTime).toBeLessThanOrEqual(afterTime); + }); + + it('should use custom created_at when provided', async () => { + const customTime = 1234567890; + const result = await tool.execute({ + events: [{ kind: 1, content: 'test', created_at: customTime }], + }); + + const parsed = JSON.parse(result); + expect(parsed.success).toBe(true); + }); + + it('should not create fallback kind 0 when user provides one', async () => { + const result = await tool.execute({ + events: [ + { kind: 0, content: JSON.stringify({ name: 'Custom Name', about: 'Custom bio' }) }, + { kind: 1, content: 'hello world' }, + ], + }); + + const parsed = JSON.parse(result); + expect(parsed.success).toBe(true); + expect(parsed.events_published).toBe(2); // Only the 2 user events, no fallback + expect(parsed.events[0].kind).toBe(0); // User's kind 0 + expect(parsed.events[1].kind).toBe(1); + }); + + it('should create fallback kind 0 when user does not provide one', async () => { + const result = await tool.execute({ + events: [ + { kind: 1, content: 'hello world' }, + { kind: 30023, content: '# Article' }, + ], + }); + + const parsed = JSON.parse(result); + expect(parsed.success).toBe(true); + expect(parsed.events_published).toBe(3); // Fallback kind 0 + 2 user events + expect(parsed.events[0].kind).toBe(0); // Fallback profile event + expect(parsed.events[1].kind).toBe(1); + expect(parsed.events[2].kind).toBe(30023); + }); +}); diff --git a/src/lib/tools/NostrPublishEventsTool.ts b/src/lib/tools/NostrPublishEventsTool.ts new file mode 100644 index 00000000..e7e491e6 --- /dev/null +++ b/src/lib/tools/NostrPublishEventsTool.ts @@ -0,0 +1,124 @@ +import { z } from "zod"; +import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify'; +import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools'; + +import type { Tool } from "./Tool"; + +interface NostrPublishEventsParams { + events: Array<{ + kind?: number; + content?: string; + tags?: string[][]; + created_at?: number; + }>; + relays?: string[]; +} + +export class NostrPublishEventsTool implements Tool { + readonly description = "Publish Nostr events using an ephemeral keypair. All events in a single call are signed by the same ephemeral pubkey. You should include a kind 0 (profile metadata) event in the events array to give the publisher an identity. If no kind 0 is provided, a generic one will be created automatically as a fallback."; + + readonly inputSchema = z.object({ + events: z.array( + z.object({ + kind: z.number().int().min(0).max(65535).optional().describe('Event kind number (default: 1)'), + content: z.string().optional().describe('Event content (default: empty string)'), + tags: z.array(z.array(z.string())).optional().describe('Event tags (default: empty array)'), + created_at: z.number().int().positive().optional().describe('Unix timestamp in seconds (default: current time)'), + }) + ).min(1).describe('Array of partial Nostr events to publish. Include a kind 0 event to set profile metadata.'), + relays: z.array(z.string().url()).optional().describe('Optional array of relay URLs to publish to (default: hardcoded relay list)'), + }); + + async execute(args: NostrPublishEventsParams): Promise { + const { events: partialEvents, relays } = args; + + // Default relays if none provided + const defaultRelays = [ + 'wss://relay.ditto.pub', + 'wss://relay.nostr.band', + 'wss://relay.primal.net', + ]; + + const targetRelays = relays && relays.length > 0 ? relays : defaultRelays; + + // Generate ephemeral keypair + const secretKey = generateSecretKey(); + const pubkey = getPublicKey(secretKey); + + // Check if user provided a kind 0 event + const hasKind0 = partialEvents.some((e) => e.kind === 0); + + // Finalize all user-provided events + const currentTimestamp = Math.floor(Date.now() / 1000); + const finalizedEvents: NostrEvent[] = partialEvents.map((partial) => { + return finalizeEvent({ + kind: partial.kind ?? 1, + content: partial.content ?? '', + tags: partial.tags ?? [], + created_at: partial.created_at ?? currentTimestamp, + }, secretKey); + }); + + // If no kind 0 was provided, create a generic profile event as fallback + const allEvents: NostrEvent[] = []; + if (!hasKind0) { + const profileEvent = finalizeEvent({ + kind: 0, + content: JSON.stringify({ + name: 'Ephemeral Publisher', + about: 'Temporary identity for publishing events', + }), + tags: [], + created_at: currentTimestamp, + }, secretKey); + allEvents.push(profileEvent); + } + allEvents.push(...finalizedEvents); + + // Create pool for publishing + const pool = new NPool({ + open(url) { + return new NRelay1(url); + }, + eventRouter() { + return [...targetRelays]; + }, + reqRouter(filters) { + return new Map( + [...targetRelays].map((url) => [url, filters]), + ); + }, + }); + + try { + // Publish all events + const publishPromises = allEvents.map((event) => + pool.event(event, { + signal: AbortSignal.timeout(10_000), + relays: targetRelays, + }) + ); + + await Promise.all(publishPromises); + + // Format successful response + const summary = { + success: true, + pubkey, + events_published: allEvents.length, + relays: targetRelays, + events: allEvents.map((e) => ({ + id: e.id, + kind: e.kind, + content: e.content.length > 100 ? `${e.content.slice(0, 100)}...` : e.content, + })), + }; + + return JSON.stringify(summary, null, 2); + } catch (error) { + throw new Error(`Error publishing events: ${error instanceof Error ? error.message : 'Unknown error'}`); + } finally { + await pool.close(); + } + } +}