mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Add Nostr AI tools
This commit is contained in:
19 files changed
+1671
No files matched your search
@@ -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<NostrFetchEventParams> {
|
||||
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<string> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NostrGenerateKindParams> {
|
||||
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<KindRange>,
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.nipsClient = new NIPsClient({
|
||||
urlTemplate: 'https://raw.githubusercontent.com/nostr-protocol/nips/refs/heads/master/{nip}.md',
|
||||
});
|
||||
}
|
||||
|
||||
async execute(args: NostrGenerateKindParams): Promise<string> {
|
||||
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'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NostrReadKindParams> {
|
||||
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<string> {
|
||||
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'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NostrReadNipParams> {
|
||||
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<string> {
|
||||
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'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import { NIPsClient } from "../NIPsClient";
|
||||
|
||||
export class NostrReadNipsIndexTool implements Tool<object> {
|
||||
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<string> {
|
||||
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'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NostrReadProtocolParams> {
|
||||
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<string> {
|
||||
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'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NostrReadTagParams> {
|
||||
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<string> {
|
||||
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'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user