Communitygithub.com

majiayu000/claude-skill-registry

CRITICAL: 用於 MolyKit AI 聊天工具組。觸發關鍵詞:BotClient, OpenAI, SSE 串流, AI 聊天, molykit, PlatformSend, spawn(), ThreadToken, 跨平台非同步, 聊天小工具, Messages, PromptInput, Avatar, LLM

claude-skill-registry 是什麼?

此技能專注於 MolyKit,這是一個專為 Makepad 框架設計的跨平台 AI 聊天工具組。它能協助開發者在原生平台(如桌面、行動裝置)和 WASM(WebAssembly)環境中,建立功能完整的 AI 聊天介面。技能涵蓋了從 AI 提供者(如 OpenAI)整合、SSE 串流處理、到 UI 元件的完整開發流程。其核心優勢在於提供了統一的跨平台非同步程式設計模式,包括 PlatformSend(區分 Send trait 在原生和 WASM 上的行為)、spawn()(平台無關的任務啟動器,自動選擇 tokio 或 wasm-bindgen-futures)、以及 ThreadToken(解決 WASM 中非 Send 型別的問題)。此外,它還定義了豐富的協定型別(Message、BotId 等)、可複用的聊天小工具(Chat、Messages、PromptInput、Avatar)、以及 UiRunner 模式,讓非同步操作的結果能安全地更新 UI。此技能支援 Claude Code、Cursor 等基於 Makepad 的開發工具,幫助開發者快速搭建具備串流對話、工具呼叫、自訂 Bot 客戶端等功能的跨平台 AI 應用。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

MolyKit 技能

使用 MolyKit 在 Makepad 中建構 AI 聊天介面的最佳實踐 - 這是一個用於跨平台 AI 聊天應用程式的工具組。

原始碼目錄:/Users/zhangalex/Work/Projects/FW/robius/moly/moly-kit

使用時機

在以下情況使用此技能:

  • 使用 Makepad 建構 AI 聊天介面
  • 整合 OpenAI 或其他 LLM API
  • 實作支援原生與 WASM 的跨平台非同步
  • 建立聊天小工具(訊息、提示輸入、頭像)
  • 處理 SSE 串流回應
  • 關鍵詞:molykit, moly-kit, ai chat, bot client, openai makepad, chat widget, sse streaming

概覽

MolyKit 提供:

  • 跨平台非同步工具(PlatformSend, spawn(), ThreadToken)
  • 即用型聊天小工具(Chat, Messages, PromptInput, Avatar)
  • 用於 AI 提供者整合的 BotClient 特徵
  • 支援 SSE 串流的 OpenAI 相容客戶端
  • 訊息、機器人與工具呼叫的協定型別
  • MCP(模型上下文協定)支援

跨平台非同步模式

PlatformSend - 僅在原生平台要求 Send

/// 在原生平台上表示實作 Send,在 WASM 上則不要求
/// - 在原生:由實作 Send 的型別實作
/// - 在 WASM:所有型別都實作
pub trait PlatformSend: PlatformSendInner {}

/// 跨平台可用的 Box Future 型別
pub type BoxPlatformSendFuture<'a, T> = Pin<Box<dyn PlatformSendFuture<Output = T> + 'a>>;

/// 跨平台可用的 Box Stream 型別
pub type BoxPlatformSendStream<'a, T> = Pin<Box<dyn PlatformSendStream<Item = T> + 'a>>;

平台無關的任務啟動

/// 獨立執行一個 Future
/// - 在原生使用 tokio(需 Send)
/// - 在 WASM 使用 wasm-bindgen-futures(不需 Send)
pub fn spawn(fut: impl PlatformSendFuture<Output = ()> + 'static);

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

使用 AbortOnDropHandle 取消任務

/// 當 Handle 被丟棄時中止其 Future
pub struct AbortOnDropHandle(AbortHandle);

// 使用範例 - 當小工具被丟棄時,任務自動取消
#[rust]
task_handle: Option<AbortOnDropHandle>,

fn start_task(&mut self) {
    let (future, handle) = abort_on_drop(async move {
        // 非同步工作...
    });
    self.task_handle = Some(handle);
    spawn(async move { let _ = future.await; });
}

ThreadToken 處理 WASM 上的非 Send 型別

/// 將非 Send 值儲存在執行緒區域變數中,透過權杖存取
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;
}

// 使用範例 - 包裝非 Send 型別以便在 Send 邊界中使用
let token = ThreadToken::new(non_send_value);
spawn(async move {
    token.peek(|value| {
        // 使用 value...
    });
});

BotClient 特徵

實作 AI 提供者整合

pub trait BotClient: Send {
    /// 發送訊息並接收串流回應
    fn send(
        &mut self,
        bot_id: &BotId,
        messages: &[Message],
        tools: &[Tool],
    ) -> BoxPlatformSendStream<'static, ClientResult<MessageContent>>;

    /// 取得可用的機器人/模型
    fn bots(&self) -> BoxPlatformSendFuture<'static, ClientResult<Vec<Bot>>>;

    /// 用於四處傳遞的複製
    fn clone_box(&self) -> Box<dyn BotClient>;
}

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

BotContext - 可共享的包裝器

/// 可共享的包裝器,內含已載入的機器人,用於同步 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>;
}

// 使用範例
let mut context = BotContext::from(client);
spawn(async move {
    if let Err(errors) = context.load().await.into_result() {
        // 處理錯誤
    }
    Cx::post_action(BotsLoaded);
});

協定型別

訊息結構

pub struct Message {
    pub from: EntityId,         // 使用者、系統、機器人(BotId)、應用程式
    pub metadata: MessageMetadata,
    pub content: MessageContent,
}

pub struct MessageContent {
    pub text: String,           // 主要內容(Markdown)
    pub reasoning: String,      // AI 推理/思考
    pub citations: Vec<String>, // 來源 URL
    pub attachments: Vec<Attachment>,
    pub tool_calls: Vec<ToolCall>,
    pub tool_results: Vec<ToolResult>,
}

pub struct MessageMetadata {
    pub is_writing: bool,       // 仍在串流中
    pub created_at: DateTime<Utc>,
}

機器人識別

/// 全域唯一的機器人 ID:<len>;<id>@<provider>
pub struct BotId(Arc<str>);

impl BotId {
    pub fn new(id: &str, provider: &str) -> Self;
    pub fn id(&self) -> &str;       // 提供者內的 ID
    pub fn provider(&self) -> &str; // 提供者網域
}

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

小工具模式

Slot 小工具 - 執行時期內容替換

live_design! {
    pub Slot = {{Slot}} {
        width: Fill, height: Fit,
        slot = <View> {}  // 預設內容
    }
}

// 使用範例 - 在執行時期替換內容
let mut slot = widget.slot(id!(content));
if let Some(custom) = client.content_widget(cx, ...) {
    slot.replace(custom);
} else {
    slot.restore();  // 恢復為預設
    slot.default().as_standard_message_content().set_content(cx, &content);
}

Avatar 小工具 - 文字/圖片切換

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)
    }
}

PromptInput 小工具

#[derive(Live, Widget)]
pub struct PromptInput {
    #[deref] deref: CommandTextInput,
    #[live] pub send_icon: LiveValue,
    #[live] pub stop_icon: LiveValue,
    #[rust] pub task: Task,           // 發送或停止
    #[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);
}

Messages 小工具 - 對話視圖

#[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;
}

非同步轉 UI 的 UiRunner 模式

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(_) => {}
            });
        }
    }
}

SSE 串流

/// 將 SSE 位元組串流解析為訊息串流
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]>,
{
    // 以 "\n\n" 分割,提取 "data:" 內容
    // 過濾註解和 [DONE] 訊息
}

// 在 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)
}

最佳實踐

  1. 使用 PlatformSend 進行跨平台開發:同一份程式碼可在原生和 WASM 上執行
  2. 使用 spawn() 而非 tokio::spawn:平台無關的任務啟動方式
  3. 使用 AbortOnDropHandle:當小工具被丟棄時取消任務
  4. 使用 ThreadToken 處理 WASM 上的非 Send 型別:透過權杖存取執行緒區域儲存
  5. 使用 Slot 自訂內容:允許 BotClient 提供自訂小工具
  6. 使用 read()/write() 模式:透過 WidgetRef 安全借用存取
  7. 使用 UiRunner::defer_with_redraw:從非同步上下文更新小工具
  8. 處理 ClientResult 的部分成功:可能同時包含數值和錯誤

參考檔案

  • llms.txt - 完整的 MolyKit API 參考

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.

相關技能