ok-skills
Curated AI coding agent skills and AGENTS.md playbooks for Codex, Claude Code, Cursor, OpenClaw, and other SKILL.md-compatible tools.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/mxyhi/ok-skills with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/mxyhi/ok-skills'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/mxyhi--ok-skills)HTML
<a href="/listings/mxyhi--ok-skills"><img src="/api/listings/mxyhi--ok-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
mkdir -p ~/.agents/skills cd ~/.agents/skills git clone https://github.com/mxyhi/ok-skills.git ok-skills
For Autohand Code, clone the repo into either the user-level or project-level skills directory:
# User-level skills mkdir -p ~/.autohand/skills git clone https://github.com/mxyhi/ok-skills.git ~/.autohand/skills/ok-skills # Project-level skills mkdir -p .autohand/skills git clone https://github.com/mxyhi/ok-skills.git .autohand/skills/ok-skills
After cloning, the repo lives at `~/.agents/skills/ok-skills`, and the directories inside already follow the expected layout:
~/.agents/skills/ok-skills/
CLAUDE_AGENTS.md
planning-with-files/
SKILL.md
find-docs/
SKILL.md
agent-browser/
SKILL.md
...For Claude Code or Codex global instructions, start from [`CLAUDE_AGENTS.md`](CLAUDE_AGENTS.md) and copy or merge it into Claude Code's `CLAUDE.md` or Codex's `AGENTS.md`. It packages a Chinese-first, KISS-oriented workflow with current-doc/source checks, multi-agent preference, `planning-with-files` / `karpathy-guidelines` defaults, strict TypeScript expectations, and context-mode routing rules. Before reusing it, edit the `语言要求` section for your project. The `其他注意项` section is intentionally project-local and can be edited as needed.
Add simple trigger rules to your `AGENTS.md`, or merge the same skill triggers into `CLAUDE.md` / `AGENTS.md`:
## Skills - planning-with-files: Use for complex tasks, research, or anything that will take 5+ tool calls. - find-docs: Use when you need current library docs, API references, or Context7-backed examples. - agent-browser: Use for browser automation, screenshots, scraping, web testing, or form filling.
Then ask naturally:
- `Use planning-with-files before refactoring this module.` - `Use find-docs to fetch the latest docs for this SDK.` - `Use agent-browser to reproduce this UI bug.`
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 210 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # OK Skills: AI Coding Agent Skills for Codex, Claude Code, Cursor, OpenClaw, Autohand Code, and More
- English | [简体中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Deutsch](README.de.md) | [Español](README.es.md) | [Tiếng Việt](README.vi.md) | [Русский](README.ru.md) | [हिन्दी](README.hi.md)
- [](https://github.com/RoggeOhta/awesome-codex-cli) [](https://www.aipm-registry.com/skills/mxyhi/agent-browser/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
- Curated AI coding agent skills and `CLAUDE.md` / `AGENTS.md` playbooks for Codex, Claude Code, Cursor, OpenClaw, Autohand Code, Trae, and other `SKILL.md`-compatible tools.
- This repo currently bundles **33 reusable skills**, all maintained as top-level skill directories in this repo. Clone it into `~/.agents/skills/ok-skills`; the directories inside already match the layout expected by `AGENTS.md`-driven workflows, and [`CLAUDE_AGENTS.md`](CLAUDE_AGENTS.md) provides a Claude Code-oriented agent playbook.
- If you are looking for **Codex skills**, **Claude Code skills**, **Cursor skills**, **OpenClaw skills**, reusable **CLAUDE.md / AGENTS.md** playbooks, or practical **SKILL.md** examples, this repository is designed to be both searchable and immediately usable.
- **Popular use cases:** docs lookup, browser automation, prompt engineering, planning workflows, task management, codebase understanding, frontend design, PDF/Word/PPTX/XLSX authoring.
- ## Who This Repo Is For
- - You use Codex, Claude Code, Cursor, OpenClaw, Autohand Code, Trae, or another AI coding agent and want reusable skills instead of ad-hoc prompts.
- - You maintain `CLAUDE.md` / `AGENTS.md` / `SKILL.md` workflows and want portable instructions that work across projects.
- - You need battle-tested skills for docs lookup, browser automation, planning, prompt engineering, frontend design, PDFs, Office documents, slide decks, and spreadsheets.
- ## Start Here
- If you only install a few skills first, start with these:
- - [planning-with-files](planning-with-files/SKILL.md): file-based planning for complex tasks, research, and long-running work.
- - [find-docs](find-docs/SKILL.md): fetch current library docs, API references, and Context7-backed examples.
- - [agent-browser](agent-browser/SKILL.md): browser automation for screenshots, forms, scraping, and web QA.
- ## 1-Minute Quick Start
- ```bash
- mkdir -p ~/.agents/skills
- cd ~/.agents/skills
- git clone https://github.com/mxyhi/ok-skills.git ok-skills
- ```
- For Autohand Code, clone the repo into either the user-level or project-level skills directory:
- ```bash
- # User-level skills
- mkdir -p ~/.autohand/skills
- git clone https://github.com/mxyhi/ok-skills.git ~/.autohand/skills/ok-skills
- # Project-level skills
- mkdir -p .autohand/skills
- git clone https://github.com/mxyhi/ok-skills.git .autohand/skills/ok-skills
- ```
- After cloning, the repo lives at `~/.agents/skills/ok-skills`, and the directories inside already follow the expected layout:
- ```text
- ~/.agents/skills/ok-skills/
- CLAUDE_AGENTS.md
- planning-with-files/
- SKILL.md
- find-docs/
- SKILL.md
- agent-browser/
- SKILL.md
- ...
- ```
- For Claude Code or Codex global instructions, start from [`CLAUDE_AGENTS.md`](CLAUDE_AGENTS.md) and copy or merge it into Claude Code's `CLAUDE.md` or Codex's `AGENTS.md`. It packages a Chinese-first, KISS-oriented workflow with current-doc/source checks, multi-agent preference, `planning-with-files` / `karpathy-guidelines` defaults, strict TypeScript expectations, and context-mode routing rules. Before reusing it, edit the `语言要求` section for your project. The `其他注意项` section is intentionally project-local and can be edited as needed.
- Add simple trigger rules to your `AGENTS.md`, or merge the same skill triggers into `CLAUDE.md` / `AGENTS.md`:
- ```md
- ## Skills
- - planning-with-files: Use for complex tasks, research, or anything that will take 5+ tool calls.
- - find-docs: Use when you need current library docs, API references, or Context7-backed examples.
- - agent-browser: Use for browser automation, screenshots, scraping, web testing, or form filling.
- ```
- Then ask naturally:
- - `Use planning-with-files before refactoring this module.`
- - `Use find-docs to fetch the latest docs for this SDK.`
- - `Use agent-browser to reproduce this UI bug.`
- ## Browse Skills by Use Case
- ### Research & Docs
- - [find-docs](find-docs/SKILL.md): focused Context7 CLI workflow for current documentation lookup.
- - [exa-search](exa-search/SKILL.md): web, code, and company research with Exa search tools.
- - [reverse-engineer-anything](reverse-engineer-anything/SKILL.md): investigate shipped applications and binaries when source code does not explain behavior; use REA's CLI/MCP to gather evidence and compare versions.
- - [get-api-docs](get-api-docs/SKILL.md): fetch current third-party API and SDK documentation before coding.
- - [find-skills](find-skills/SKILL.md): discover existing skills when a user asks for a capability.
- - [ax](ax/SKILL.md): AI-era curl — fetch pages, discover structure, extract structured data without throwaway parsing scripts.
- ### Planning & Prompting
- - [planning-with-files](planning-with-files/SKILL.md): persistent markdown planning with `task_plan.md`, `findings.md`, and `progress.md`.
- - [ledger-tasks-yylo](ledger-tasks-yylo/SKILL.md): durable in-repo task state for coding agents — Kanban tasks with stable IDs, evidence-backed status marks, blocked-by dependencies, and next-ready selection.
- - [product-decision-agent](product-decision-agent/SKILL.md): Chinese-first product decision support for bottleneck diagnosis, prioritization, growth, metrics, operations, and cross-team delivery.
- - [autoresearch](autoresearch/SKILL.md): autonomous goal-directed iteration with explicit goals, metrics, verify loops, and keep/discard gates.
- - [diagnosing-bugs](diagnosing-bugs/SKILL.md): disciplined diagnosis loop for hard bugs and performance regressions.
- - [grilling](grilling/SKILL.md): reusable design-tree interview loop for direct grill sessions.
- - [teach](teach/SKILL.md): run a stateful teaching workspace with missions, resources, lessons, and learning records.
- - [domain-modeling](domain-modeling/SKILL.md): build and sharpen project domain terminology, `GLOSSARY.md`, and ADRs.
- - [codebase-design](codebase-design/SKILL.md): shared deep-module vocabulary for seams, interfaces, leverage, locality, and testability.
- - [improve-codebase-architecture](improve-codebase-architecture/SKILL.md): find deepening opportunities that improve locality, leverage, testability, and AI navigation.
- - [prototype](prototype/SKILL.md): build throwaway logic or UI prototypes to answer design questions quickly.
- - [karpathy-guidelines](karpathy-guidelines/SKILL.md): behavioral coding guidelines that reduce overcomplication, hidden assumptions, and unverifiable changes.
- - [ponytail](ponytail/SKILL.md): Apply YAGNI, reuse existing code, and prefer standard-library and native-platform solutions to reduce over-engineering; supports lite, full, and ultra modes.
- - [migrate-to-shoehorn](migrate-to-shoehorn/SKILL.md): migrate test `as` assertions to `@total-typescript/shoehorn`.
- - [tdd](tdd/SKILL.md): test-first red-green-refactor for features, bugfixes, refactors, and behavior changes.
- ### Automation & QA
- - [agent-browser](agent-browser/SKILL.md): browser automation for navigation, forms, screenshots, and scraping.
- - [kimi-webbridge](kimi-webbridge/SKILL.md): control the user's real browser through a local daemon for navigation, forms, screenshots, page reading, and authenticated sessions.
- - [browser-trace](browser-trace/SKILL.md): CDP trace capture for browser automation runs, with screenshots, DOM dumps, and per-page buckets.
- - [opencli](opencli/opencli-usage/SKILL.md): turn websites into CLI commands with browser session reuse, public API access, and AI-generated adapters.
- - [orca-replay](orca-replay/SKILL.md): answer questions about an earlier agent run from its recording instead of from memory, and replay or fork that run offline.
- ### Frontend & Design
- - [ai-elements](ai-elements/SKILL.md): build AI chat UI components for the `ai-elements` library.
- - [huashu-design](huashu-design/SKILL.md): produce high-fidelity HTML prototypes, slide decks, motion demos, design variants, video exports, and design critiques.
- - [imagegen-frontend-web](imagegen-frontend-web/SKILL.md): generate premium frontend reference images, one horizontal image per section, with strong art direction.
- - [better-icons](better-icons/SKILL.md): search, browse, and retrieve SVG icons from 200+ Iconify libraries via CLI or MCP.
- - [unslop](unslop/SKILL.md): turn AI-looking interfaces into deliberate, product-specific designs through a structured visual polish pass.
- ### Utilities & Authoring
- - [bopomofo-rescue](bopomofo-rescue/SKILL.md): recover Chinese typed on a Taiwanese Bopomofo (注音) keyboard while the IME was stuck in English mode, e.g. su3cl3a8 → 你好嗎.
- - [huashu-design](huashu-design/SKILL.md): create HTML decks, editable PPTX exports, MP4/GIF motion pieces, and narrated design videos.
- ## Vendored Skill Packs
- [`planning-with-files/`](planning-with-files/) tracks [`OthmanAdi/planning-with-files/.codex/skills/planning-with-files`](https://github.com/OthmanAdi/planning-with-files/tree/master/.codex/skills/planning-with-files) as its upstream baseline. This repository keeps that upstream directory as the canonical baseline for the local skill. Local differences are limited to `skills-ref`-compatible `SKILL.md` frontmatter and install-location-independent relative script paths in docs.
- ### Upstream Migration Notes (2026-09-30)
- - The Matt Pocock engineering skills now use `GLOSSARY.md` and `GLOSSARY-MAP.md` for domain vocabulary. Existing `CONTEXT.md` / `CONTEXT-MAP.md` glossaries need to be renamed and their links updated; ADRs stay under `docs/adr/`.
- - OpenCLI upstream removed sitemap skills, bundled sitemaps, and external CLI passthrough. Use the current browser/adapter skills and site memory; invoke external CLIs directly.
- ### Upstream Migration Notes (2026-10-18)
- - OpenCLI commands now default to `{ok:true,data:...}` JSON results. Adapter creation and validation use `opencli adapter init|check|test`; update scripts that parse the old output or use the former browser adapter commands. The CLI itself must support these commands.
- - Huashu Design 3.0 organizes work by output module and starts new visual designs with six thumbnails and three complete directions for selection. Pure exports and mechanical edits are exempt.
- - Kimi WebBridge skill 2.0.24 documents tab attachment and paginated ARIA snapshots. These features require a matching daemon and browser extension; syncing this repository only updates the skill files.
- ### Upstream Migration Notes (2026-10-29)
- - Planning with Files 3.26.0 adds explicit plan-format validation (`check-complete.sh --validate` / `check-complete.ps1 -Validate`). New plans must retain native phase headings and status markers; existing plans are reported without being rewritten. `PWF_SKIP_SUBAGENTS=1` optionally skips subagent tool-hook injection.
- - REA skill version 55 adds AgentEnv bundles, more artifact/runtime workflows, and separate recovery guidance for plugin-owned and setup-owned MCP registrations. Use the capabilities advertised by the installed REA runtime; syncing the skill does not upgrade it.
- - `imagegen-frontend-web` moved to [`Leonxlnx/imagegen-skills`](https://github.com/Leonxlnx/imagegen-skills/tree/main/skills/imagegen-frontend-web). Its skill name and vendored content are unchanged.
- ## Common Prerequisites
- - Some skills assume `gh` is installed and authenticated.
- - Browser-focused skills may require a Chrome/CDP-capable environment.
- - Third-party doc lookup skills may depend on external CLIs or MCP tools; check each `SKILL.md` for details.
- ## Full Skill Index
- `Source URL` points to the canonical upstream when a skill is vendored/imported; otherwise it points to the skill directory in this repository.
- ### Top-Level Skills
- | Skill | Description | Source URL |
- | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
- | [agent-browser](agent-browser/SKILL.md) | Browser automation CLI for AI agents: navigation, form filling, screenshots, extraction, and web testing. | [vercel-labs/agent-browser](https://github.com/vercel-labs/agent-browser/tree/main/skills/agent-browser) |
- | [ai-elements](ai-elements/SKILL.md) | Create new AI chat interface components for the ai-elements library with composable patterns and shadcn/ui conventions. | [vercel/ai-elements](https://github.com/vercel/ai-elements/tree/main/skills/ai-elements) |
- | [autoresearch](autoresearch/SKILL.md) | Autonomous goal-directed iteration engine for modify, verify, keep/discard, and repeat workflows. | [uditgoenka/autoresearch](https://github.com/uditgoenka/autoresearch/tree/master/.agents/skills/autoresearch) |
- | [ax](ax/SKILL.md) | AI-era curl: fetch URLs, discover page structure, and extract structured data from HTML without throwaway parsing scripts. | [yusukebe/ax](https://github.com/yusukebe/ax/tree/main/skills/ax) |
- | [better-icons](better-icons/SKILL.md) | Search 200+ Iconify libraries and retrieve SVG icons through CLI or MCP tools. | [better-auth/better-icons](https://github.com/better-auth/better-icons/tree/main/skills) |
- | [bopomofo-rescue](bopomofo-rescue/SKILL.md) | Recover Chinese typed on a Taiwanese Bopomofo (注音) keyboard while the IME was stuck in English mode, e.g. su3cl3a8 → 你好嗎. | [Oliviaiii/bopomofo-rescue](https://github.com/Oliviaiii/bopomofo-rescue) |
- | [kimi-webbridge](kimi-webbridge/SKILL.md) | Control the user's real browser through a local daemon for navigation, forms, screenshots, page reading, and authenticated sessions. | [install.sh](https://cdn.kimi.com/webbridge/install.sh) |
- | [browser-trace](browser-trace/SKILL.md) | Capture CDP traces, screenshots, and DOM dumps for browser automation debugging. | [browserbase/skills](https://github.com/browserbase/skills/tree/main/skills/browser-trace) |
- | [diagnosing-bugs](diagnosing-bugs/SKILL.md) | Disciplined diagnosis loop for hard bugs and performance regressions. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/engineering/diagnosing-bugs) |
- | [deep-research](deep-research/SKILL.md) | Professional deep research reports with multi-agent parallel writing, current-data targeting, multilingual output, and built-in quality checks. | [hoolulu/deep-research](https://github.com/hoolulu/deep-research/tree/main) |
- | [find-docs](find-docs/SKILL.md) | Use the Context7 CLI for current documentation lookup, API references, and code examples. | [upstash/context7](https://github.com/upstash/context7/tree/master/skills/find-docs) |
- | [exa-search](exa-search/SKILL.md) | Use Exa for web, code, and company research. | Custom |
- | [reverse-engineer-anything](reverse-engineer-anything/SKILL.md) | Investigate shipped applications and binaries when source code does not explain behavior; use REA's CLI/MCP to gather evidence and compare versions. | [morluto/rea](https://github.com/morluto/rea/tree/main/.agents/skills/reverse-engineer-anything) |
- | [find-skills](find-skills/SKILL.md) | Discover existing skills when users need specialized capabilities. | [vercel-labs/skills](https://github.com/vercel-labs/skills/tree/main/skills/find-skills) |
- | [huashu-design](huashu-design/SKILL.md) | Create high-fidelity HTML prototypes, interactive demos, slide decks, motion design, design variants, video exports, and critiques. | [alchaincyf/huashu-design](https://github.com/alchaincyf/huashu-design) |
- | [imagegen-frontend-web](imagegen-frontend-web/SKILL.md) | Generate premium frontend reference images, one horizontal image per section, with strong art direction. | [Leonxlnx/imagegen-skills](https://github.com/Leonxlnx/imagegen-skills/tree/main/skills/imagegen-frontend-web) |
- | [unslop](unslop/SKILL.md) | Turn AI-looking interfaces into deliberate, product-specific designs through a structured visual polish pass. | [heydamir/unslop](https://github.com/heydamir/unslop/tree/main/skills/unslop) |
- | [get-api-docs](get-api-docs/SKILL.md) | Fetch current third-party API or SDK docs before writing code. | [andrewyng/context-hub](https://github.com/andrewyng/context-hub/tree/main/cli/skills/get-api-docs) |
- | [grilling](grilling/SKILL.md) | Reusable design-tree interview loop for direct grill sessions. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/productivity/grilling) |
- | [teach](teach/SKILL.md) | Teach a user a skill or concept through a stateful workspace of missions, resources, lessons, and learning records. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/productivity/teach) |
- | [domain-modeling](domain-modeling/SKILL.md) | Build and sharpen project domain terminology, `GLOSSARY.md`, and ADRs. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/engineering/domain-modeling) |
- | [codebase-design](codebase-design/SKILL.md) | Shared deep-module vocabulary for seams, interfaces, leverage, locality, and testability. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/engineering/codebase-design) |
- | [improve-codebase-architecture](improve-codebase-architecture/SKILL.md) | Find deepening opportunities that improve locality, leverage, testability, and AI navigation. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/engineering/improve-codebase-architecture) |
- | [prototype](prototype/SKILL.md) | Build throwaway logic or UI prototypes to answer design questions quickly. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/engineering/prototype) |
- | [karpathy-guidelines](karpathy-guidelines/SKILL.md) | Behavioral coding guidelines that reduce overcomplication, hidden assumptions, and unverifiable changes. | [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills/tree/main/skills/karpathy-guidelines) |
- | [ponytail](ponytail/SKILL.md) | Apply YAGNI, reuse existing code, and prefer standard-library and native-platform solutions to reduce over-engineering; supports lite, full, and ultra modes. | [DietrichGebert/ponytail](https://github.com/DietrichGebert/ponytail/tree/main/skills/ponytail) |
- | [migrate-to-shoehorn](migrate-to-shoehorn/SKILL.md) | Migrate test files from `as` type assertions to `@total-typescript/shoehorn`. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/misc/migrate-to-shoehorn) |
- | [opencli](opencli/opencli-usage/SKILL.md) | Turn websites into CLI commands with browser session reuse, public API access, and AI-generated adapters. | [jackwener/opencli](https://github.com/jackwener/opencli/tree/main/skills) |
- | [planning-with-files](planning-with-files/SKILL.md) | File-based planning for complex tasks using `task_plan.md`, `findings.md`, and `progress.md`. | [OthmanAdi/planning-with-files](https://github.com/OthmanAdi/planning-with-files/tree/master/.codex/skills/planning-with-files) |
- | [product-decision-agent](product-decision-agent/SKILL.md) | Chinese-first product decision support for bottleneck diagnosis, prioritization, growth, metrics, operations, and cross-team delivery. | [atdy/maoxuan-product-agent](https://github.com/atdy/maoxuan-product-agent/tree/main/product-decision-agent) |
- | [ledger-tasks-yylo](ledger-tasks-yylo/SKILL.md) | Durable in-repo task state for coding agents: Kanban tasks with stable IDs, evidence-backed status marks, blocked-by dependencies, and next-ready selection. | [yylo-dev/yylo-skills](https://github.com/yylo-dev/yylo-skills/tree/main/skills/ledger-tasks-yylo) |
- | [tdd](tdd/SKILL.md) | Use before any feature, bugfix, refactor, or behavior change; prefers public-interface integration tests. | [mattpocock/skills](https://github.com/mattpocock/skills/tree/main/skills/engineering/tdd) |
- ## Contributing
- Contributions are welcome for new skills or improvements to existing ones.
- 1. Keep trigger conditions explicit and testable.
- 2. Keep examples concise and execution-oriented.
- 3. If a skill depends on external tools, document that dependency in `SKILL.md`.
- 4. Update `README.md` and `README.zh-CN.md` when you add or rename a skill, and refresh the other translated READMEs when the public-facing skill index changes.
- ## License
- This repository is licensed under [LICENSE](LICENSE).
huashu-design/scripts/cloud/tts-doubao.mjs · Bundled script · 287 lines · 1 finding marked
- #!/usr/bin/env node
- /**
- * tts-doubao.mjs · 豆包语音 TTS(火山引擎 openspeech)
- *
- * ⚠️ 可选云能力:本脚本会把待配音文本发送到字节跳动官方 TTS 接口(openspeech.bytedance.com),
- * 使用你自己的 key,endpoint 强制校验域名白名单。首次调用需 --yes 或 HUASHU_CLOUD_OK=1
- * 显式确认。数据流向声明见仓库根 SECURITY.md。
- *
- * 用法:
- * node scripts/cloud/tts-doubao.mjs --text "你好" --out demo.mp3 --yes
- * node scripts/cloud/tts-doubao.mjs --text-file script.txt --out out.mp3 --speed 1.0 --yes
- * node scripts/cloud/tts-doubao.mjs --text "你好" --out demo.mp3 --timestamps --yes # 附带字级时间戳
- *
- * 输出:
- * - mp3 文件写到 --out 路径
- * - stdout 打印一行 JSON: {"path":"...","duration":12.34,"bytes":54321}
- * - 带 --timestamps 时额外含 words: [{text,start,end,confidence}](秒,相对本段音频开头)
- * 注意:时间戳文本是 TN 后文本(如 "2025" 会变成 "二零二五"),标点附在前一个字上;
- * 需要 2.0 资源(seed-tts-2.0 / seed-icl-2.0),仅中英文。
- *
- * 依赖:Node 18+(自带 fetch/crypto)、ffprobe(测时长,brew install ffmpeg)
- *
- * env(自动从 skill 根目录 .env 读取,也可走 process.env 覆盖):
- * DOUBAO_TTS_API_KEY 可选(新版 API Key 鉴权)
- * DOUBAO_APP_ID 可选(控制台 App ID,与 DOUBAO_ACCESS_KEY 配套)
- * DOUBAO_ACCESS_KEY 可选(控制台 Access Token,与 DOUBAO_APP_ID 配套)
- * DOUBAO_TTS_VOICE_ID 必填(音色 id)
- * DOUBAO_TTS_RESOURCE_ID 可选(默认按音色自动推断)
- * DOUBAO_TTS_ENDPOINT 默认 https://openspeech.bytedance.com/api/v3/tts/unidirectional
- */
- import fs from 'node:fs';
- import path from 'node:path';
- import { execFileSync } from 'node:child_process';
- import { fileURLToPath } from 'node:url';
- import { randomUUID } from 'node:crypto';
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const SKILL_ROOT = path.resolve(__dirname, '..', '..');
- function loadEnv() {
- const envPath = path.join(SKILL_ROOT, '.env');
- if (!fs.existsSync(envPath)) return;
- const text = fs.readFileSync(envPath, 'utf8');
- for (const line of text.split('\n')) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith('#')) continue;
- const idx = trimmed.indexOf('=');
- if (idx < 0) continue;
- const key = trimmed.slice(0, idx).trim();
- let val = trimmed.slice(idx + 1).trim();
- if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
- val = val.slice(1, -1);
- }
- if (!(key in process.env)) process.env[key] = val;
- Dismissed after review: Copies every environment variable, where API keys and tokens live, in a file that sends data
- Line 55 on GitHub
- }
- }
- loadEnv();
- function parseArgs(argv) {
- const args = { speed: '1.0', encoding: 'mp3' };
- for (let i = 2; i < argv.length; i++) {
- const a = argv[i];
- if (a === '--text') args.text = argv[++i];
- else if (a === '--text-file') args.textFile = argv[++i];
- else if (a === '--out') args.out = argv[++i];
- else if (a === '--speed') args.speed = argv[++i];
- else if (a === '--voice') args.voice = argv[++i];
- else if (a === '--encoding') args.encoding = argv[++i];
- else if (a === '--timestamps') args.timestamps = true;
- else if (a === '--yes') args.yes = true;
- else if (a === '--help' || a === '-h') args.help = true;
- }
- return args;
- }
- function usage() {
- console.error(`
- tts-doubao.mjs · 豆包语音 TTS
- --text <str> 要合成的文本
- --text-file <path> 从文件读取文本(与 --text 二选一)
- --out <path> 输出 mp3 路径(必填)
- --speed <float> 语速倍率,默认 1.0(0.5-2.0)
- --voice <voice_id> 覆盖 .env 里的音色 id
- --encoding <ext> mp3 / wav / pcm,默认 mp3
- --timestamps 请求字级时间戳(enable_subtitle),结果 JSON 多一个 words 数组
- --yes 确认将文本发送到豆包 TTS 官方接口(或设 HUASHU_CLOUD_OK=1)
- `.trim());
- process.exit(1);
- }
- function getDuration(filePath) {
- try {
- const out = execFileSync('ffprobe', [
- '-v', 'error',
- '-show_entries', 'format=duration',
- '-of', 'default=noprint_wrappers=1:nokey=1',
- filePath,
- ], { encoding: 'utf8' });
- return parseFloat(out.trim());
- } catch (e) {
- return null;
- }
- }
- function inferResourceId(voiceId) {
- // 复刻音色默认走 2.0:本账号只开通了 seed-icl-2.0(1.0 会 403 resource not granted),
- // 且字级时间戳(enable_subtitle)只有 2.0 资源支持。
- if (voiceId.startsWith('S_')) return 'seed-icl-2.0';
- if (voiceId.includes('uranus')) return 'seed-tts-2.0';
- return 'seed-tts-1.0';
- }
- function speedToSpeechRate(speed) {
- const ratio = parseFloat(speed);
- if (!Number.isFinite(ratio)) return 0;
- return Math.max(-50, Math.min(100, Math.round((ratio - 1) * 100)));
- }
- function buildAuthHeaders({ requestId, resourceId }) {
- const apiKey = process.env.DOUBAO_TTS_API_KEY;
- const appId = process.env.DOUBAO_APP_ID;
- const accessKey = process.env.DOUBAO_ACCESS_KEY;
- const headers = {
- 'Content-Type': 'application/json',
- 'X-Api-Resource-Id': resourceId,
- 'X-Api-Request-Id': requestId,
- };
- if (apiKey) {
- headers['X-Api-Key'] = apiKey;
- return headers;
- }
- if (!appId) throw new Error('缺 DOUBAO_TTS_API_KEY 或 DOUBAO_APP_ID(检查 .env)');
- if (!accessKey) throw new Error('缺 DOUBAO_ACCESS_KEY(检查 .env)');
- headers['X-Api-App-Id'] = appId;
- headers['X-Api-Access-Key'] = accessKey;
- return headers;
- }
- async function readV3Audio(res) {
- const text = await res.text();
- const chunks = [];
- const words = []; // 字级时间戳(enable_subtitle 开启时服务端按句返回 sentence.words)
- let finalCode = null;
- let finalMessage = '';
- for (const line of text.split(/\r?\n/)) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- let json;
- try {
- json = JSON.parse(trimmed);
- } catch (e) {
- throw new Error(`API 响应行不是 JSON:${trimmed.slice(0, 200)}`);
- }
- const code = json.code ?? 0;
- if (code === 20000000) {
- finalCode = code;
- finalMessage = json.message || '';
- break;
- }
- if (code !== 0) {
- throw new Error(`API 返回错误 code=${code} msg=${json.message || JSON.stringify(json)}`);
- }
- if (json.data) chunks.push(Buffer.from(json.data, 'base64'));
- if (json.sentence && Array.isArray(json.sentence.words)) {
- for (const w of json.sentence.words) {
- words.push({
- text: w.word,
- start: w.startTime,
- end: w.endTime,
- confidence: w.confidence,
- });
- }
- }
- }
- if (!chunks.length) {
- const detail = finalCode ? `结束码 ${finalCode} ${finalMessage}` : text.slice(0, 500);
- throw new Error(`API 响应无音频数据:${detail}`);
- }
- return { audio: Buffer.concat(chunks), words };
- }
- // endpoint 域名白名单:key 和文本只允许发往字节官方域名,防 .env 被篡改后重定向
- const ALLOWED_ENDPOINT_HOSTS = /(^|\.)(bytedance\.com|volces\.com)$/;
- async function tts({ text, voice, speed, encoding, timestamps }) {
- const endpoint = process.env.DOUBAO_TTS_ENDPOINT || 'https://openspeech.bytedance.com/api/v3/tts/unidirectional';
- const host = new URL(endpoint).hostname;
- if (!ALLOWED_ENDPOINT_HOSTS.test(host)) {
- throw new Error(`DOUBAO_TTS_ENDPOINT 域名 ${host} 不在白名单(*.bytedance.com / *.volces.com),拒绝发送`);
- }
- const voiceId = voice || process.env.DOUBAO_TTS_VOICE_ID || process.env.DOUBAO_SPEAKER;
- const resourceId = process.env.DOUBAO_TTS_RESOURCE_ID || inferResourceId(voiceId || '');
- const requestId = randomUUID();
- if (!voiceId) throw new Error('缺 DOUBAO_TTS_VOICE_ID(检查 .env 或用 --voice 传)');
- const body = {
- user: { uid: 'huashu-design' },
- req_params: {
- text,
- speaker: voiceId,
- audio_params: {
- format: encoding,
- sample_rate: 24000,
- speech_rate: speedToSpeechRate(speed),
- // 字级时间戳:仅 2.0 资源(seed-tts-2.0 / seed-icl-2.0)支持,中英文 only
- ...(timestamps ? { enable_subtitle: true } : {}),
- },
- },
- };
- const res = await fetch(endpoint, {
- method: 'POST',
- headers: buildAuthHeaders({ requestId, resourceId }),
- body: JSON.stringify(body),
- });
- if (!res.ok) {
- const errText = await res.text();
- throw new Error(`HTTP ${res.status}: ${errText.slice(0, 500)}`);
- }
- return readV3Audio(res);
- }
- async function main() {
- const args = parseArgs(process.argv);
- if (args.help) usage();
- let text = args.text;
- if (!text && args.textFile) {
- text = fs.readFileSync(args.textFile, 'utf8').trim();
- }
- if (!text) {
- console.error('错:缺 --text 或 --text-file');
- usage();
- }
- if (!args.out) {
- console.error('错:缺 --out');
- usage();
- }
- if (!args.yes && process.env.HUASHU_CLOUD_OK !== '1') {
- const host = new URL(process.env.DOUBAO_TTS_ENDPOINT || 'https://openspeech.bytedance.com').hostname;
- console.error(
- `[云能力确认] 本次将把约${text.length}字文本发送到 ${host}(豆包TTS官方接口,使用你自己的key合成语音)。\n` +
- `确认无误请重跑并加 --yes,或设置环境变量 HUASHU_CLOUD_OK=1。数据流向声明见 SECURITY.md。`,
- );
- process.exit(2);
- }
- const outPath = path.resolve(args.out);
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
- const { audio, words } = await tts({
- text,
- voice: args.voice,
- speed: args.speed,
- encoding: args.encoding,
- timestamps: args.timestamps,
- });
- fs.writeFileSync(outPath, audio);
- const duration = getDuration(outPath);
- const result = {
- path: outPath,
- bytes: audio.length,
- duration,
- text_chars: text.length,
- };
- if (args.timestamps) result.words = words;
- console.log(JSON.stringify(result));
- }
- main().catch((err) => {
- console.error(`TTS 失败:${err.message}`);
- process.exit(1);
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.