mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add NIP-89 kind 31990 app management for projects
- AppDialog with app preview card, Blossom icon upload, and collapsible advanced section - AppTool for AI to view/update app with view-before-update guard - Shared buildAppEvent utility for DRY event construction - Auto-fill website from deployment URL, default name from project ID - Add repo 'a' tag when origin is a nostr:// URI owned by the user - Custom tool call rendering with AppWindow icon - System prompt guidance for app publishing workflow and prerequisites - Store app coordinate in .git/shakespeare/app.json via DotAI
This commit is contained in:
10 files changed
+1152
-2
No files matched your search
@@ -393,4 +393,47 @@ export class DotAI {
|
||||
console.warn(`Failed to write .git/ai/FINISH_REASON file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read app config from .git/shakespeare/app.json file.
|
||||
* Stores the Nostr "a" coordinate for the project's kind 31990 app event.
|
||||
* @returns App config object or null if not found or invalid
|
||||
*/
|
||||
async readAppConfig(): Promise<AppConfig | null> {
|
||||
try {
|
||||
const appPath = join(this.workingDir, ".git", "shakespeare", "app.json");
|
||||
const content = await this.fs.readFile(appPath, "utf8");
|
||||
const data = JSON.parse(content);
|
||||
|
||||
if (data && typeof data.a === 'string' && data.a.length > 0) {
|
||||
return { a: data.a };
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write app config to .git/shakespeare/app.json file.
|
||||
* @param config App config with the Nostr "a" coordinate (e.g. "31990:<pubkey>:<d-tag>")
|
||||
*/
|
||||
async writeAppConfig(config: AppConfig): Promise<void> {
|
||||
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
|
||||
const appPath = join(shakespeareDir, "app.json");
|
||||
|
||||
try {
|
||||
await this.fs.mkdir(shakespeareDir, { recursive: true });
|
||||
await this.fs.writeFile(appPath, JSON.stringify(config, null, 2) + "\n");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .git/shakespeare/app.json file: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** App config stored in .git/shakespeare/app.json */
|
||||
export interface AppConfig {
|
||||
/** Nostr "a" coordinate for the kind 31990 event (e.g. "31990:<pubkey>:<d-tag>") */
|
||||
a: string;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import git from 'isomorphic-git';
|
||||
import { NostrURI } from './NostrURI';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
|
||||
/** Input for building a kind 31990 app event. */
|
||||
export interface AppEventInput {
|
||||
name: string;
|
||||
about?: string;
|
||||
picture?: string;
|
||||
website?: string;
|
||||
dTag: string;
|
||||
supportedKinds?: string[];
|
||||
webHandlers?: Array<{ url: string; type?: string }>;
|
||||
}
|
||||
|
||||
/** The content and tags for a kind 31990 event, ready to be signed/published. */
|
||||
export interface AppEventData {
|
||||
content: string;
|
||||
tags: string[][];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the content JSON and tags array for a kind 31990 app event.
|
||||
*
|
||||
* Optionally inspects the project's git origin remote. If it's a `nostr://`
|
||||
* URI owned by the given pubkey, an `a` tag referencing the kind 30617 repo
|
||||
* event is included.
|
||||
*/
|
||||
export async function buildAppEvent(
|
||||
input: AppEventInput,
|
||||
opts?: {
|
||||
fs?: JSRuntimeFS;
|
||||
cwd?: string;
|
||||
pubkey?: string;
|
||||
},
|
||||
): Promise<AppEventData> {
|
||||
// Build content (kind-0-style metadata JSON)
|
||||
const content: Record<string, string> = {};
|
||||
if (input.name.trim()) content.name = input.name.trim();
|
||||
if (input.about?.trim()) content.about = input.about.trim();
|
||||
if (input.picture?.trim()) content.picture = input.picture.trim();
|
||||
if (input.website?.trim()) content.website = input.website.trim();
|
||||
|
||||
// Build tags
|
||||
const tags: string[][] = [
|
||||
['d', input.dTag.trim()],
|
||||
];
|
||||
|
||||
// Add k tags for supported kinds
|
||||
if (input.supportedKinds) {
|
||||
for (const kind of input.supportedKinds) {
|
||||
tags.push(['k', kind]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add web handler tags
|
||||
if (input.webHandlers) {
|
||||
for (const handler of input.webHandlers) {
|
||||
if (handler.url) {
|
||||
const webTag = ['web', handler.url];
|
||||
if (handler.type) {
|
||||
webTag.push(handler.type);
|
||||
}
|
||||
tags.push(webTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If origin remote is a nostr:// URI owned by the given pubkey, add an "a" tag for the repo
|
||||
if (opts?.fs && opts.cwd && opts.pubkey) {
|
||||
try {
|
||||
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
|
||||
const originUrl = remotes.find(r => r.remote === 'origin')?.url;
|
||||
if (originUrl?.startsWith('nostr://')) {
|
||||
const nostrURI = await NostrURI.parse(originUrl);
|
||||
if (nostrURI.pubkey === opts.pubkey) {
|
||||
tags.push(['a', `30617:${nostrURI.pubkey}:${nostrURI.identifier}`]);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// No remote or parse error, skip
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
content: JSON.stringify(content),
|
||||
tags,
|
||||
};
|
||||
}
|
||||
+23
-1
@@ -275,7 +275,29 @@ This project has a repository URL configured, so you can create an "Edit with Sh
|
||||
|
||||
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
|
||||
|
||||
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if README %}
|
||||
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}
|
||||
|
||||
## Publishing an App
|
||||
|
||||
Users can publish their project as a Nostr app (NIP-89 kind 31990) using the \`app\` tool. This creates a discoverable app listing on Nostr with metadata like name, description, icon, and website.
|
||||
|
||||
### Before Publishing
|
||||
|
||||
When a user asks to publish an app, follow this process:
|
||||
|
||||
1. **Check app state first**: Always call the \`app\` tool with \`view_app\` before doing anything else to see if an app has already been published.
|
||||
2. **Require deployment**: The project should be deployed to a public URL before publishing an app. If it hasn't been deployed yet, strongly encourage the user to deploy first — an app listing without a working URL is not useful.
|
||||
3. **Ensure the site is polished**: Push back if the site is incomplete. Before publishing, the project should have:
|
||||
- A **custom favicon** (not the default Vite/React favicon)
|
||||
- **Open Graph meta tags** (\`og:title\`, \`og:description\`, \`og:image\`, \`og:url\`)
|
||||
- A proper **og:image** that will display well when shared on social media
|
||||
- The site should generally look finished and presentable
|
||||
4. **Find a suitable app icon**: Check the project files for existing icons or images suitable for the app icon (e.g., a logo, favicon SVG, or brand image). If a suitable image exists and the project is deployed, use the deployed site's public URL to that image (e.g., \`https://deployed-url.com/logo.png\`). If no suitable icon exists, stop and let the user know — offer to generate one, let the user upload one, or suggest they use the "App" dialog in the project menu directly.
|
||||
5. **Update the app**: Once all prerequisites are met, call the \`app\` tool with \`update_app\` to publish or update the app listing. Set the \`website\` field to the deployed URL.
|
||||
|
||||
### The App Dialog
|
||||
|
||||
Users can also manage their app listing manually through the **App** option in the project dropdown menu. If the user prefers a visual form over the chat-based approach, point them to this dialog.{% if README %}
|
||||
|
||||
{{ README }}{% endif %}{% if AGENTS %}
|
||||
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
import { z } from 'zod';
|
||||
import { NPool, NRelay1 } from '@nostrify/nostrify';
|
||||
import type { NostrEvent, NostrSigner } from '@nostrify/nostrify';
|
||||
|
||||
import { DotAI } from '../DotAI';
|
||||
import { buildAppEvent } from '../appEvent';
|
||||
import type { Tool, ToolResult } from './Tool';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
interface AppToolParams {
|
||||
action: 'view_app' | 'update_app';
|
||||
name?: string;
|
||||
about?: string;
|
||||
picture?: string;
|
||||
website?: string;
|
||||
d?: string;
|
||||
supported_kinds?: string[];
|
||||
web_handlers?: Array<{ url: string; type?: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* AI tool for viewing and updating the project's NIP-89 kind 31990 app event.
|
||||
*
|
||||
* The agent must call `view_app` at least once in a session before calling `update_app`.
|
||||
* This ensures the agent is aware of the current state before making changes.
|
||||
*/
|
||||
export class AppTool implements Tool<AppToolParams> {
|
||||
private hasViewed = false;
|
||||
|
||||
readonly description =
|
||||
'View or update the project\'s Nostr app (NIP-89 kind 31990). ' +
|
||||
'Use "view_app" to see the current app event. ' +
|
||||
'Use "update_app" to create or update the app event (you MUST call view_app first in this session before updating). ' +
|
||||
'This publishes the event using the user\'s own Nostr signer.';
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
action: z.enum(['view_app', 'update_app']).describe('The action to perform.'),
|
||||
name: z.string().optional().describe('App name (required for update_app if creating new).'),
|
||||
about: z.string().optional().describe('Short description of the app.'),
|
||||
picture: z.string().optional().describe('URL to the app icon.'),
|
||||
website: z.string().optional().describe('App website URL.'),
|
||||
d: z.string().optional().describe('Unique identifier (d-tag) for the app. Defaults to the project ID. Cannot be changed after first publish.'),
|
||||
supported_kinds: z.array(z.string()).optional().describe('Array of event kind numbers this app handles.'),
|
||||
web_handlers: z.array(z.object({
|
||||
url: z.string().describe('Handler URL pattern with <bech32> placeholder.'),
|
||||
type: z.string().optional().describe('NIP-19 type handled by this URL (e.g. "nevent", "nprofile").'),
|
||||
})).optional().describe('Web handler URL patterns.'),
|
||||
});
|
||||
|
||||
constructor(
|
||||
private fs: JSRuntimeFS,
|
||||
private cwd: string,
|
||||
private signer: NostrSigner | undefined,
|
||||
private pubkey: string | undefined,
|
||||
private relayUrls: string[],
|
||||
) {}
|
||||
|
||||
async execute(args: AppToolParams): Promise<ToolResult> {
|
||||
switch (args.action) {
|
||||
case 'view_app':
|
||||
return this.viewApp();
|
||||
case 'update_app':
|
||||
return this.updateApp(args);
|
||||
default:
|
||||
throw new Error(`Unknown action: ${args.action}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async viewApp(): Promise<ToolResult> {
|
||||
const dotAI = new DotAI(this.fs, this.cwd);
|
||||
const config = await dotAI.readAppConfig();
|
||||
|
||||
if (!config) {
|
||||
this.hasViewed = true;
|
||||
return {
|
||||
content: JSON.stringify({
|
||||
status: 'no_app',
|
||||
message: 'No app has been published for this project yet. Use update_app to create one.',
|
||||
}, null, 2),
|
||||
};
|
||||
}
|
||||
|
||||
// Parse the "a" coordinate
|
||||
const parts = config.a.split(':');
|
||||
if (parts.length < 3) {
|
||||
this.hasViewed = true;
|
||||
return {
|
||||
content: JSON.stringify({
|
||||
status: 'error',
|
||||
message: `Invalid app coordinate stored: ${config.a}`,
|
||||
}, null, 2),
|
||||
};
|
||||
}
|
||||
|
||||
const kind = parseInt(parts[0], 10);
|
||||
const pubkey = parts[1];
|
||||
const dTag = parts.slice(2).join(':');
|
||||
|
||||
// Query relays for the event
|
||||
const pool = this.createPool();
|
||||
|
||||
try {
|
||||
const events = await pool.query(
|
||||
[{
|
||||
kinds: [kind],
|
||||
authors: [pubkey],
|
||||
'#d': [dTag],
|
||||
limit: 1,
|
||||
}],
|
||||
{ signal: AbortSignal.timeout(5000) },
|
||||
);
|
||||
|
||||
this.hasViewed = true;
|
||||
|
||||
if (events.length === 0) {
|
||||
return {
|
||||
content: JSON.stringify({
|
||||
status: 'not_found',
|
||||
a: config.a,
|
||||
message: 'App coordinate is stored locally but the event was not found on relays. It may have been deleted or the relays are unavailable. Use update_app to republish.',
|
||||
}, null, 2),
|
||||
};
|
||||
}
|
||||
|
||||
const event = events.reduce((latest, current) =>
|
||||
current.created_at > latest.created_at ? current : latest,
|
||||
);
|
||||
|
||||
// Parse content metadata
|
||||
let metadata: Record<string, string> = {};
|
||||
try {
|
||||
if (event.content) {
|
||||
metadata = JSON.parse(event.content);
|
||||
}
|
||||
} catch {
|
||||
// Invalid JSON content
|
||||
}
|
||||
|
||||
const supportedKinds = event.tags
|
||||
.filter(([t]) => t === 'k')
|
||||
.map(([, v]) => v);
|
||||
|
||||
const webHandlers = event.tags
|
||||
.filter(([t]) => t === 'web')
|
||||
.map(([, url, type]) => ({ url, type }));
|
||||
|
||||
return {
|
||||
content: JSON.stringify({
|
||||
status: 'found',
|
||||
a: config.a,
|
||||
id: event.id,
|
||||
pubkey: event.pubkey,
|
||||
created_at: event.created_at,
|
||||
metadata: {
|
||||
name: metadata.name ?? null,
|
||||
about: metadata.about ?? null,
|
||||
picture: metadata.picture ?? null,
|
||||
website: metadata.website ?? null,
|
||||
},
|
||||
d_tag: dTag,
|
||||
supported_kinds: supportedKinds,
|
||||
web_handlers: webHandlers,
|
||||
all_tags: event.tags,
|
||||
}, null, 2),
|
||||
};
|
||||
} finally {
|
||||
await pool.close();
|
||||
}
|
||||
}
|
||||
|
||||
private async updateApp(args: AppToolParams): Promise<ToolResult> {
|
||||
if (!this.hasViewed) {
|
||||
throw new Error(
|
||||
'You must call view_app first before updating the app. ' +
|
||||
'This ensures you are aware of the current state of the app before making changes.',
|
||||
);
|
||||
}
|
||||
|
||||
if (!this.signer) {
|
||||
throw new Error('User must be logged in with Nostr to publish an app event.');
|
||||
}
|
||||
|
||||
if (!this.pubkey) {
|
||||
throw new Error('User pubkey is not available.');
|
||||
}
|
||||
|
||||
// Check if an existing app is stored
|
||||
const dotAI = new DotAI(this.fs, this.cwd);
|
||||
const existingConfig = await dotAI.readAppConfig();
|
||||
|
||||
// Determine the d-tag
|
||||
let dTag: string;
|
||||
if (existingConfig) {
|
||||
// Use existing d-tag (cannot be changed)
|
||||
const parts = existingConfig.a.split(':');
|
||||
dTag = parts.slice(2).join(':');
|
||||
} else {
|
||||
// Use provided d-tag or derive from project path
|
||||
dTag = args.d?.trim() || this.cwd.split('/').pop() || crypto.randomUUID();
|
||||
}
|
||||
|
||||
if (!args.name?.trim()) {
|
||||
throw new Error('App name is required. Provide a "name" parameter.');
|
||||
}
|
||||
|
||||
// Build event content and tags
|
||||
const { content, tags } = await buildAppEvent(
|
||||
{
|
||||
name: args.name,
|
||||
about: args.about,
|
||||
picture: args.picture,
|
||||
website: args.website,
|
||||
dTag,
|
||||
supportedKinds: args.supported_kinds,
|
||||
webHandlers: args.web_handlers,
|
||||
},
|
||||
{ fs: this.fs, cwd: this.cwd, pubkey: this.pubkey },
|
||||
);
|
||||
|
||||
// Add client tag
|
||||
if (typeof location !== 'undefined' && location.protocol === 'https:') {
|
||||
tags.push(['client', location.hostname]);
|
||||
}
|
||||
|
||||
// Sign the event
|
||||
const event = await this.signer.signEvent({
|
||||
kind: 31990,
|
||||
content,
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Publish to relays
|
||||
const pool = this.createPool();
|
||||
|
||||
try {
|
||||
await pool.event(event, { signal: AbortSignal.timeout(10_000) });
|
||||
|
||||
// Store the "a" coordinate
|
||||
const aValue = `31990:${event.pubkey}:${dTag}`;
|
||||
await dotAI.writeAppConfig({ a: aValue });
|
||||
|
||||
return {
|
||||
content: JSON.stringify({
|
||||
status: 'published',
|
||||
a: aValue,
|
||||
id: event.id,
|
||||
pubkey: event.pubkey,
|
||||
name: args.name!.trim(),
|
||||
message: existingConfig
|
||||
? `App "${args.name!.trim()}" has been updated on Nostr.`
|
||||
: `App "${args.name!.trim()}" has been published to Nostr.`,
|
||||
}, null, 2),
|
||||
};
|
||||
} finally {
|
||||
await pool.close();
|
||||
}
|
||||
}
|
||||
|
||||
private createPool(): NPool {
|
||||
const relayUrls = this.relayUrls;
|
||||
return new NPool({
|
||||
open(url) {
|
||||
return new NRelay1(url);
|
||||
},
|
||||
eventRouter() {
|
||||
return [...relayUrls];
|
||||
},
|
||||
reqRouter(filters) {
|
||||
return new Map(
|
||||
relayUrls.map((url) => [url, filters]),
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user