Communitygithub.com

majiayu000/claude-skill-registry

CRÍTICO: Úsalo para el kit de chat AI MolyKit. Se activa con: BotClient, OpenAI, streaming SSE, chat AI, molykit, PlatformSend, spawn(), ThreadToken, async multiplataforma, widget de chat, Mensajes, PromptInput, Avatar, LLM

¿Qué es claude-skill-registry?

Este skill proporciona las mejores prácticas para construir interfaces de chat con inteligencia artificial utilizando Makepad y el toolkit MolyKit. MolyKit es una biblioteca diseñada para aplicaciones de chat AI multiplataforma que funcionan tanto en entornos nativos como en WebAssembly (WASM). Incluye utilidades de async multiplataforma como PlatformSend, spawn() y ThreadToken, que permiten ejecutar tareas asíncronas de forma segura en ambos entornos. También ofrece widgets de chat listos para usar (Chat, Messages, PromptInput, Avatar), un trait BotClient para integrar proveedores de IA como OpenAI, y soporte para transmisión SSE de respuestas en tiempo real. El skill es útil para desarrolladores que deseen crear aplicaciones de chat con Makepad, manejar streaming de respuestas de LLM, y gestionar la concurrencia de manera eficiente en distintas plataformas.

Compatible con✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/majiayu000/claude-skill-registry/tree/HEAD/skills/ai-llm/molykit-galacticvraj-vraj-portfolio

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

MolyKit Skill

Mejores prácticas para construir interfaces de chat AI con Makepad usando MolyKit, un kit de herramientas para aplicaciones de chat AI multiplataforma.

Código fuente: /Users/zhangalex/Work/Projects/FW/robius/moly/moly-kit

Cuándo usar

Usa este skill cuando:

  • Construyas interfaces de chat AI con Makepad
  • Integres OpenAI u otras APIs de LLM
  • Implementes async multiplataforma para entornos nativos y WASM
  • Crear widgets de chat (mensajes, prompts, avatares)
  • Manejar respuestas con streaming SSE
  • Palabras clave: molykit, moly-kit, chat ai, bot client, openai makepad, chat widget, sse streaming

Resumen

MolyKit proporciona:

  • Utilidades de async multiplataforma (PlatformSend, spawn(), ThreadToken)
  • Widgets de chat listos para usar (Chat, Messages, PromptInput, Avatar)
  • Trait BotClient para integración con proveedores de IA
  • Cliente compatible con OpenAI y streaming SSE
  • Tipos de protocolo para mensajes, bots y llamadas a herramientas
  • Soporte para MCP (Model Context Protocol)

Patrones de async multiplataforma

PlatformSend - Solo enviar en nativo

/// Implica Send solo en plataformas nativas, no en WASM
/// - En nativo: implementado por tipos que implementan Send
/// - En WASM: implementado por TODOS los tipos
pub trait PlatformSend: PlatformSendInner {}

/// Tipo de future empaquetado para uso multiplataforma
pub type BoxPlatformSendFuture<'a, T> = Pin<Box<dyn PlatformSendFuture<Output = T> + 'a>>;

/// Tipo de stream empaquetado para uso multiplataforma
pub type BoxPlatformSendStream<'a, T> = Pin<Box<dyn PlatformSendStream<Item = T> + 'a>>;

Spawning agnóstico de plataforma

/// Ejecuta un future de forma independiente
/// - Usa tokio en nativo (requiere Send)
/// - Usa wasm-bindgen-futures en WASM (no requiere Send)
pub fn spawn(fut: impl PlatformSendFuture<Output = ()> + 'static);

// Uso
spawn(async move {
    let result = fetch_data().await;
    Cx::post_action(DataReady(result));
    SignalToUI::set_ui_signal();
});

Cancelación de tareas con AbortOnDropHandle

/// Manejador que aborta su future al soltarse
pub struct AbortOnDropHandle(AbortHandle);

// Uso - la tarea se cancela cuando el widget se suelta
#[rust]
task_handle: Option<AbortOnDropHandle>,

fn start_task(&mut self) {
    let (future, handle) = abort_on_drop(async move {
        // trabajo asíncrono...
    });
    self.task_handle = Some(handle);
    spawn(async move { let _ = future.await; });
}

ThreadToken para tipos no Send en WASM

/// Almacena un valor no Send en un hilo-local, accede mediante token
pub struct ThreadToken<T: 'static>;

impl<T> ThreadToken<T> {
    pub fn new(value: T) -> Self;
    pub fn peek<R>(&self, f: impl FnOnce(&T) -> R) -> R;
    pub fn peek_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
}

// Uso - envuelve un tipo no Send para usarlo a través de límites Send
let token = ThreadToken::new(non_send_value);
spawn(async move {
    token.peek(|value| {
        // usar valor...
    });
});

Trait BotClient

Implementación de integración con proveedores de IA

pub trait BotClient: Send {
    /// Envía mensaje con respuesta en stream
    fn send(
        &mut self,
        bot_id: &BotId,
        messages: &[Message],
        tools: &[Tool],
    ) -> BoxPlatformSendStream<'static, ClientResult<MessageContent>>;

    /// Obtiene bots/modelos disponibles
    fn bots(&self) -> BoxPlatformSendFuture<'static, ClientResult<Vec<Bot>>>;

    /// Clonar para pasar alrededor
    fn clone_box(&self) -> Box<dyn BotClient>;
}

// Uso
let client = OpenAIClient::new("https://api.openai.com/v1".into());
client.set_key("sk-...")?;
let context = BotContext::from(client);

BotContext - Envoltorio compartible

/// Envoltorio compartible con bots cargados para acceso síncrono a UI
pub struct BotContext(Arc<Mutex<InnerBotContext>>);

impl BotContext {
    pub fn load(&mut self) -> BoxPlatformSendFuture<ClientResult<()>>;
    pub fn bots(&self) -> Vec<Bot>;
    pub fn get_bot(&self, id: &BotId) -> Option<Bot>;
    pub fn client(&self) -> Box<dyn BotClient>;
}

// Uso
let mut context = BotContext::from(client);
spawn(async move {
    if let Err(errors) = context.load().await.into_result() {
        // manejar errores
    }
    Cx::post_action(BotsLoaded);
});

Tipos de protocolo

Estructura de Mensaje

pub struct Message {
    pub from: EntityId,         // Usuario, Sistema, Bot(BotId), App
    pub metadata: MessageMetadata,
    pub content: MessageContent,
}

pub struct MessageContent {
    pub text: String,           // Contenido principal (markdown)
    pub reasoning: String,      // Razonamiento/pensamiento de IA
    pub citations: Vec<String>, // URLs de fuentes
    pub attachments: Vec<Attachment>,
    pub tool_calls: Vec<ToolCall>,
    pub tool_results: Vec<ToolResult>,
}

pub struct MessageMetadata {
    pub is_writing: bool,       // Aún se está transmitiendo
    pub created_at: DateTime<Utc>,
}

Identificación de Bot

/// ID de bot único global: <len>;<id>@<provider>
pub struct BotId(Arc<str>);

impl BotId {
    pub fn new(id: &str, provider: &str) -> Self;
    pub fn id(&self) -> &str;       // id local del proveedor
    pub fn provider(&self) -> &str; // dominio del proveedor
}

// Ejemplo: BotId::new("gpt-4", "api.openai.com")
// -> "5;[email protected]"

Patrones de widgets

Widget Slot - Reemplazo de contenido en tiempo de ejecución

live_design! {
    pub Slot = {{Slot}} {
        width: Fill, height: Fit,
        slot = <View> {}  // contenido por defecto
    }
}

// Uso - reemplaza contenido en tiempo de ejecución
let mut slot = widget.slot(id!(content));
if let Some(custom) = client.content_widget(cx, ...) {
    slot.replace(custom);
} else {
    slot.restore();  // vuelve al defecto
    slot.default().as_standard_message_content().set_content(cx, &content);
}

Widget Avatar - Alternar texto/imagen

live_design! {
    pub Avatar = {{Avatar}} <View> {
        grapheme = <RoundedView> {
            visible: false,
            label = <Label> { text: "P" }
        }
        dependency = <RoundedView> {
            visible: false,
            image = <Image> {}
        }
    }
}

impl Widget for Avatar {
    fn draw_walk(&mut self, cx: &mut Cx2d, ...) -> DrawStep {
        if let Some(avatar) = &self.avatar {
            match avatar {
                Picture::Grapheme(g) => {
                    self.view(id!(grapheme)).set_visible(cx, true);
                    self.view(id!(dependency)).set_visible(cx, false);
                    self.label(id!(label)).set_text(cx, &g);
                }
                Picture::Dependency(d) => {
                    self.view(id!(dependency)).set_visible(cx, true);
                    self.view(id!(grapheme)).set_visible(cx, false);
                    self.image(id!(image)).load_image_dep_by_path(cx, d.as_str());
                }
            }
        }
        self.deref.draw_walk(cx, scope, walk)
    }
}

Widget PromptInput

#[derive(Live, Widget)]
pub struct PromptInput {
    #[deref] deref: CommandTextInput,
    #[live] pub send_icon: LiveValue,
    #[live] pub stop_icon: LiveValue,
    #[rust] pub task: Task,           // Enviar o Detener
    #[rust] pub interactivity: Interactivity,
}

impl PromptInput {
    pub fn submitted(&self, actions: &Actions) -> bool;
    pub fn reset(&mut self, cx: &mut Cx);
    pub fn set_send(&mut self);
    pub fn set_stop(&mut self);
    pub fn enable(&mut self);
    pub fn disable(&mut self);
}

Widget Messages - Vista de conversación

#[derive(Live, Widget)]
pub struct Messages {
    #[deref] deref: View,
    #[rust] pub messages: Vec<Message>,
    #[rust] pub bot_context: Option<BotContext>,
}

impl Messages {
    pub fn set_messages(&mut self, messages: Vec<Message>, scroll_to_bottom: bool);
    pub fn scroll_to_bottom(&mut self, cx: &mut Cx, triggered_by_stream: bool);
    pub fn is_at_bottom(&self) -> bool;
}

Patrón UiRunner para Async-a-UI

impl Widget for PromptInput {
    fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
        self.deref.handle_event(cx, event, scope);
        self.ui_runner().handle(cx, event, scope, self);

        if self.button(id!(attach)).clicked(event.actions()) {
            let ui = self.ui_runner();
            Attachment::pick_multiple(move |result| match result {
                Ok(attachments) => {
                    ui.defer_with_redraw(move |me, cx, _| {
                        me.attachment_list_ref().write().attachments.extend(attachments);
                    });
                }
                Err(_) => {}
            });
        }
    }
}

Streaming SSE

/// Analiza un stream de bytes SSE en un stream de mensajes
pub fn parse_sse<S, B, E>(s: S) -> impl Stream<Item = Result<String, E>>
where
    S: Stream<Item = Result<B, E>>,
    B: AsRef<[u8]>,
{
    // Dividir en "\n\n", extraer contenido "data:"
    // Filtrar comentarios y mensajes [DONE]
}

// Uso en BotClient::send
fn send(&mut self, ...) -> BoxPlatformSendStream<...> {
    let stream = stream! {
        let response = client.post(url).send().await?;
        let events = parse_sse(response.bytes_stream());

        for await event in events {
            let completion: Completion = serde_json::from_str(&event)?;
            content.text.push_str(&completion.delta.content);
            yield ClientResult::new_ok(content.clone());
        }
    };
    Box::pin(stream)
}

Mejores prácticas

  1. Usa PlatformSend para multiplataforma: El mismo código funciona en nativo y WASM
  2. Usa spawn() no tokio::spawn: Spawning de tareas agnóstico de plataforma
  3. Usa AbortOnDropHandle: Cancela tareas cuando se suelta el widget
  4. Usa ThreadToken para tipos no Send en WASM: Almacenamiento en hilo-local con acceso mediante token
  5. Usa Slot para contenido personalizado: Permite que BotClient proporcione widgets personalizados
  6. Usa el patrón read()/write(): Acceso seguro mediante préstamos a través de WidgetRef
  7. Usa UiRunner::defer_with_redraw: Actualiza el widget desde un contexto asíncrono
  8. Maneja ClientResult con éxito parcial: Puede tener valor Y errores

Archivos de referencia

  • llms.txt - Referencia completa de la API de MolyKit

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

majiayu000/claude-skill-registry

Builds, edit or validate Agent Skill through conversational discovery. Use when the user requests to "Create an Agent", "Optimize an Agent" or "Edit an Agent".

majiayu000/claude-skill-registry

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry

Analyzes current state and user query to answer BMad questions or recommend the next workflow or agent. Use when user says what should I do next, what do I do now, or asks a question about BMad

majiayu000/claude-skill-registry

Build AI agents with Google ADK Python (Agent Development Kit). Use for multi-agent systems, workflow agents (sequential/parallel/loop), Vertex AI deployment, tool integration, human-in-the-loop.

majiayu000/claude-skill-registry

Build AI agents with Google ADK Python (Agent Development Kit). Use for multi-agent systems, workflow agents (sequential/parallel/loop), Vertex AI deployment, tool integration, human-in-the-loop.

majiayu000/claude-skill-registry

Portfolio allocation and rebalancing optimizer. Manages asset allocation across stocks/cash/bonds, performs periodic rebalancing, and ensures diversification according to market regime and risk tolerance.

majiayu000/claude-skill-registry

Create a hilarious and ultra-realistic video of an anthropomorphic animal acting like a human vlogger in a real-world setting.

majiayu000/claude-skill-registry

Speech-to-text transcription and translation via OpenAI Audio API -- models, response formats, timestamps, prompting, streaming, chunking, and diarization

majiayu000/claude-skill-registry

BlockRun works with Claude Code and Google Antigravity.

majiayu000/claude-skill-registry

This skill should be used when the user asks about libraries, frameworks, API references, or needs code examples. Activates for setup questions, code generation involving libraries, or mentions of specific frameworks like React, Vue, Next.js, Prisma, Supabase, etc.

majiayu000/claude-skill-registry

小省导购员数字人带货版即梦视频提示词生成系统,基于四大智能体协同(提示词生成师、质量管控师、知识库运维师、跨环节适配师),按照"主体+运动+场景+(镜头语言+光影+氛围)"公式输出中英文双版提示词,适配5s短视频。确保人物一致性、视觉连贯性、情绪连贯性,支持知识库智能复用和跨工具适配(Suno音乐、AI绘画),为数字人带货视频提供高质量提示词生成服务。

majiayu000/claude-skill-registry

Upload and manage files using Google Gemini File API via scripts/. Use for uploading images, audio, video, PDFs, and other files for use with Gemini models. Supports file upload, status checking, and file management. Triggers on "upload file", "file API", "upload image", "upload PDF", "upload video", "file management".

majiayu000/claude-skill-registry

AI and machine learning workflow covering LLM application development, RAG implementation, agent architecture, ML pipelines, and AI-powered features.

majiayu000/claude-skill-registry

Analyze images/audio/video with Gemini API (better vision than Claude). Generate images (Imagen 4), videos (Veo 3). Use for vision analysis, transcription, OCR, design extraction, multimodal AI.

majiayu000/claude-skill-registry

Analyze images/audio/video with Gemini API (better vision than Claude). Generate images (Imagen 4), videos (Veo 3). Use for vision analysis, transcription, OCR, design extraction, multimodal AI.

majiayu000/claude-skill-registry

Conduct domain and industry research. Use when the user says "lets create a research report on [domain or industry]

majiayu000/claude-skill-registry

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

Skills relacionados