From f59d5e905bc786ffe52fa84ce858adbb4127f5dd Mon Sep 17 00:00:00 2001 From: Willie Date: Fri, 29 May 2026 13:57:40 +0800 Subject: [PATCH] refactor(extensions): simplify reference converters --- extensions/README.md | 160 ++++++++++++++++++++++ extensions/codex-agents/convert.js | 71 +--------- extensions/codex-agents/md-toml.js | 87 ++++++++++++ extensions/gemini-commands/convert.js | 59 +------- extensions/gemini-commands/md-toml.js | 87 ++++++++++++ website/docs/reference/commands/extras.md | 5 +- 6 files changed, 349 insertions(+), 120 deletions(-) create mode 100644 extensions/README.md create mode 100644 extensions/codex-agents/md-toml.js create mode 100644 extensions/gemini-commands/md-toml.js diff --git a/extensions/README.md b/extensions/README.md new file mode 100644 index 000000000..1281bcfac --- /dev/null +++ b/extensions/README.md @@ -0,0 +1,160 @@ +# Extensions + +This directory contains reference extensions for transforming Markdown extras into tool-specific files during `skillshare sync extras`. + +The reference extensions use plain JavaScript with Node.js. Extensions are not limited to JavaScript, but plain JS is the most practical cross-platform default for directly editable examples: + +- Windows, macOS, and Linux can run the same script with `node`. +- No TypeScript, npm install, bundling, or build step is required. +- Users can edit the script directly. +- Bash is fine for personal Unix-only scripts, but it is not a good default reference for Windows/macOS/Linux support. + +## How Extensions Run + +An extras target can set `extension: `: + +```yaml +extras: + - name: commands + targets: + - path: ~/.gemini/commands + extension: gemini-commands +``` + +During sync, Skillshare: + +1. Reads each source Markdown file. +2. Sends the file content to the extension on `stdin`. +3. Writes the extension's `stdout` to the target file. +4. Uses `output_ext` from `extension.yaml` to choose the output extension, for example `.md` to `.toml`. + +## Reference Layout + +Each reference extension is self-contained. Copy the whole directory when you want to customize one. + +```text +extensions/gemini-commands/ +├── extension.yaml +├── convert.js +└── md-toml.js +``` + +`extension.yaml` tells Skillshare how to run the extension: + +```yaml +run: ["node", "convert.js"] +output_ext: toml +description: "Markdown slash-command (Claude/Cursor style) → Gemini CLI TOML command" +``` + +`convert.js` is the file users are expected to edit. It only contains the field mapping: + +```js +const { block, convert } = require("./md-toml"); + +convert(({ body, frontmatter }) => ({ + description: frontmatter.description, + prompt: block(body.replace(/\$ARGUMENTS\b|\$\d+/g, "{{args}}")), +})); +``` + +`md-toml.js` is a helper for the repetitive parts that are easy to get wrong: + +- reading `stdin` +- parsing simple Markdown frontmatter +- deriving `stem` from `SS_REL_PATH` +- escaping TOML strings +- writing TOML output + +## Mapping API + +`convert()` receives one object: + +```js +{ + body, // Markdown body after frontmatter + frontmatter, // simple key/value frontmatter + relPath, // SS_REL_PATH, relative to the extras source root + stem // filename without extension +} +``` + +Return an object whose keys become TOML fields: + +```js +convert(({ body, frontmatter, stem }) => ({ + name: frontmatter.name || stem, + description: frontmatter.description, + developer_instructions: block(body), +})); +``` + +Plain values become TOML strings: + +```toml +name = "review" +``` + +Values wrapped with `block()` become TOML multiline strings: + +```toml +developer_instructions = """ +Review carefully. +""" +``` + +Empty values are skipped. + +## Test A Converter Locally + +From the repository root: + +```bash +printf '%s\n' '---' 'description: Run things' '---' 'Use $ARGUMENTS' \ + | SS_REL_PATH=run.md node extensions/gemini-commands/convert.js +``` + +Expected shape: + +```toml +description = "Run things" +prompt = """ +Use {{args}} +""" +``` + +## Create Your Own Extension + +1. Copy one reference directory: + + ```bash + cp -R extensions/gemini-commands ~/.config/skillshare/extensions/my-command-format + ``` + +2. Edit `extension.yaml`: + + ```yaml + run: ["node", "convert.js"] + output_ext: toml + description: "My Markdown command converter" + ``` + +3. Edit `convert.js` to map Markdown into the target tool's format. + +4. Use it from extras config: + + ```yaml + extras: + - name: commands + targets: + - path: ~/.my-tool/commands + extension: my-command-format + ``` + +5. Run: + + ```bash + skillshare sync extras + ``` + +For the full extension contract, see [Extension transforms](../website/docs/reference/commands/extras.md#extension-transforms). diff --git a/extensions/codex-agents/convert.js b/extensions/codex-agents/convert.js index b8cc899ed..4253dfe0e 100644 --- a/extensions/codex-agents/convert.js +++ b/extensions/codex-agents/convert.js @@ -1,66 +1,9 @@ #!/usr/bin/env node -// Convert a markdown subagent (YAML frontmatter + body) to a Codex CLI TOML agent. -// -// Reads markdown from stdin, writes TOML to stdout. -// Mapping: -// frontmatter `name` -> TOML `name` (falls back to SS_REL_PATH filename) -// frontmatter `description` -> TOML `description` -// frontmatter `model` -> TOML `model` (omitted when absent) -// markdown body -> TOML `developer_instructions` (triple-quoted) -// Unknown frontmatter keys are dropped. +const { block, convert } = require("./md-toml"); -const path = require("path"); - -function splitFrontmatter(text) { - if (text.startsWith("---")) { - const end = text.indexOf("\n---", 3); - if (end !== -1) { - const fm = text.slice(3, end).replace(/^\n+|\n+$/g, ""); - const body = text.slice(end + 4).replace(/^\n+/, ""); - return [fm, body]; - } - } - return ["", text]; -} - -function getKey(fm, key) { - const re = new RegExp("^\\s*" + key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\s*:\\s*(.+?)\\s*$"); - for (const line of fm.split("\n")) { - const m = line.match(re); - if (m) return m[1].trim().replace(/^["']|["']$/g, ""); - } - return ""; -} - -function tomlEscapeBasic(s) { - return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); -} - -function readStdin() { - return new Promise((resolve) => { - let data = ""; - process.stdin.setEncoding("utf8"); - process.stdin.on("data", (chunk) => (data += chunk)); - process.stdin.on("end", () => resolve(data)); - }); -} - -(async () => { - const text = await readStdin(); - const [fm, body] = splitFrontmatter(text); - let name = getKey(fm, "name"); - if (!name) { - const rel = process.env.SS_REL_PATH || "agent.md"; - name = path.basename(rel, path.extname(rel)); - } - const description = getKey(fm, "description"); - const model = getKey(fm, "model"); - - const out = [`name = "${tomlEscapeBasic(name)}"`]; - if (description) out.push(`description = "${tomlEscapeBasic(description)}"`); - if (model) out.push(`model = "${tomlEscapeBasic(model)}"`); - let fence = '"""'; - if (body.includes(fence)) fence = "'''"; - out.push(`developer_instructions = ${fence}\n${body.replace(/\n+$/, "")}\n${fence}`); - process.stdout.write(out.join("\n") + "\n"); -})(); +convert(({ body, frontmatter, stem }) => ({ + name: frontmatter.name || stem, + description: frontmatter.description, + model: frontmatter.model, + developer_instructions: block(body), +})); diff --git a/extensions/codex-agents/md-toml.js b/extensions/codex-agents/md-toml.js new file mode 100644 index 000000000..95a2dfd87 --- /dev/null +++ b/extensions/codex-agents/md-toml.js @@ -0,0 +1,87 @@ +const path = require("path"); + +function block(value) { + return { type: "block", value }; +} + +function convert(mapFields) { + readStdin().then((input) => { + const doc = parseMarkdown(input); + const fields = mapFields(doc) || {}; + const lines = []; + + for (const [key, value] of Object.entries(fields)) { + if (value == null || value === "") continue; + if (value.type === "block") { + lines.push(`${key} = ${tomlBlock(value.value)}`); + continue; + } + lines.push(`${key} = ${tomlString(value)}`); + } + + process.stdout.write(lines.join("\n") + (lines.length ? "\n" : "")); + }); +} + +function parseMarkdown(input) { + const { frontmatterText, body } = splitFrontmatter(input); + const relPath = process.env.SS_REL_PATH || "input.md"; + + return { + body, + frontmatter: parseFrontmatter(frontmatterText), + relPath, + stem: path.basename(relPath, path.extname(relPath)), + }; +} + +function splitFrontmatter(input) { + const match = input.match(/^---\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?/); + if (!match) return { frontmatterText: "", body: input }; + + return { + frontmatterText: match[1], + body: input.slice(match[0].length), + }; +} + +function parseFrontmatter(text) { + const frontmatter = {}; + for (const line of text.split(/\r?\n/)) { + const match = line.match(/^\s*([A-Za-z0-9_-]+)\s*:\s*(.*?)\s*$/); + if (match) frontmatter[match[1]] = stripQuotes(match[2]); + } + return frontmatter; +} + +function stripQuotes(value) { + if (value.length < 2) return value; + const first = value[0]; + const last = value[value.length - 1]; + if ((first === `"` && last === `"`) || (first === `'` && last === `'`)) { + return value.slice(1, -1); + } + return value; +} + +function tomlString(value) { + return `"${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +function tomlBlock(value) { + const text = String(value).replace(/\n+$/, ""); + if (!text.includes(`"""`)) return `"""\n${text}\n"""`; + if (!text.includes(`'''`)) return `'''\n${text}\n'''`; + return `"""\n${text.replace(/"""/g, `\\"""`)}\n"""`; +} + +function readStdin() { + return new Promise((resolve) => { + let data = ""; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (chunk) => (data += chunk)); + process.stdin.on("end", () => resolve(data)); + }); +} + +module.exports = { block, convert }; diff --git a/extensions/gemini-commands/convert.js b/extensions/gemini-commands/convert.js index a8500c122..3db86c8c3 100644 --- a/extensions/gemini-commands/convert.js +++ b/extensions/gemini-commands/convert.js @@ -1,56 +1,7 @@ #!/usr/bin/env node -// Convert a markdown command (YAML frontmatter + body) to a Gemini CLI TOML command. -// -// Reads markdown from stdin, writes TOML to stdout. -// Mapping: -// frontmatter `description` -> TOML `description` -// markdown body -> TOML `prompt` (triple-quoted) -// Claude placeholders $ARGUMENTS / $1.. -> Gemini {{args}} -// Unknown frontmatter keys are dropped. +const { block, convert } = require("./md-toml"); -function splitFrontmatter(text) { - if (text.startsWith("---")) { - const end = text.indexOf("\n---", 3); - if (end !== -1) { - const fm = text.slice(3, end).replace(/^\n+|\n+$/g, ""); - const body = text.slice(end + 4).replace(/^\n+/, ""); - return [fm, body]; - } - } - return ["", text]; -} - -function getDescription(fm) { - for (const line of fm.split("\n")) { - const m = line.match(/^\s*description\s*:\s*(.+?)\s*$/); - if (m) return m[1].trim().replace(/^["']|["']$/g, ""); - } - return ""; -} - -function tomlEscapeBasic(s) { - return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); -} - -function readStdin() { - return new Promise((resolve) => { - let data = ""; - process.stdin.setEncoding("utf8"); - process.stdin.on("data", (chunk) => (data += chunk)); - process.stdin.on("end", () => resolve(data)); - }); -} - -(async () => { - const text = await readStdin(); - const [fm, body] = splitFrontmatter(text); - const description = getDescription(fm); - let prompt = body.replace(/\$ARGUMENTS\b/g, "{{args}}").replace(/\$\d+/g, "{{args}}"); - - const out = []; - if (description) out.push(`description = "${tomlEscapeBasic(description)}"`); - let fence = '"""'; - if (prompt.includes(fence)) fence = "'''"; - out.push(`prompt = ${fence}\n${prompt.replace(/\n+$/, "")}\n${fence}`); - process.stdout.write(out.join("\n") + "\n"); -})(); +convert(({ body, frontmatter }) => ({ + description: frontmatter.description, + prompt: block(body.replace(/\$ARGUMENTS\b|\$\d+/g, "{{args}}")), +})); diff --git a/extensions/gemini-commands/md-toml.js b/extensions/gemini-commands/md-toml.js new file mode 100644 index 000000000..95a2dfd87 --- /dev/null +++ b/extensions/gemini-commands/md-toml.js @@ -0,0 +1,87 @@ +const path = require("path"); + +function block(value) { + return { type: "block", value }; +} + +function convert(mapFields) { + readStdin().then((input) => { + const doc = parseMarkdown(input); + const fields = mapFields(doc) || {}; + const lines = []; + + for (const [key, value] of Object.entries(fields)) { + if (value == null || value === "") continue; + if (value.type === "block") { + lines.push(`${key} = ${tomlBlock(value.value)}`); + continue; + } + lines.push(`${key} = ${tomlString(value)}`); + } + + process.stdout.write(lines.join("\n") + (lines.length ? "\n" : "")); + }); +} + +function parseMarkdown(input) { + const { frontmatterText, body } = splitFrontmatter(input); + const relPath = process.env.SS_REL_PATH || "input.md"; + + return { + body, + frontmatter: parseFrontmatter(frontmatterText), + relPath, + stem: path.basename(relPath, path.extname(relPath)), + }; +} + +function splitFrontmatter(input) { + const match = input.match(/^---\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?/); + if (!match) return { frontmatterText: "", body: input }; + + return { + frontmatterText: match[1], + body: input.slice(match[0].length), + }; +} + +function parseFrontmatter(text) { + const frontmatter = {}; + for (const line of text.split(/\r?\n/)) { + const match = line.match(/^\s*([A-Za-z0-9_-]+)\s*:\s*(.*?)\s*$/); + if (match) frontmatter[match[1]] = stripQuotes(match[2]); + } + return frontmatter; +} + +function stripQuotes(value) { + if (value.length < 2) return value; + const first = value[0]; + const last = value[value.length - 1]; + if ((first === `"` && last === `"`) || (first === `'` && last === `'`)) { + return value.slice(1, -1); + } + return value; +} + +function tomlString(value) { + return `"${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +function tomlBlock(value) { + const text = String(value).replace(/\n+$/, ""); + if (!text.includes(`"""`)) return `"""\n${text}\n"""`; + if (!text.includes(`'''`)) return `'''\n${text}\n'''`; + return `"""\n${text.replace(/"""/g, `\\"""`)}\n"""`; +} + +function readStdin() { + return new Promise((resolve) => { + let data = ""; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (chunk) => (data += chunk)); + process.stdin.on("end", () => resolve(data)); + }); +} + +module.exports = { block, convert }; diff --git a/website/docs/reference/commands/extras.md b/website/docs/reference/commands/extras.md index 05ac6cc54..70b368a32 100644 --- a/website/docs/reference/commands/extras.md +++ b/website/docs/reference/commands/extras.md @@ -297,7 +297,8 @@ A single executable, or a directory with a manifest: ``` .skillshare/extensions/gemini-commands/ ├── extension.yaml -└── convert.js +├── convert.js # mapping rules you edit +└── md-toml.js # helper for markdown/frontmatter/TOML ``` `extension.yaml`: @@ -322,7 +323,7 @@ The mechanism is cross-platform; whether an extension runs depends on its interp ### Reference extensions -The skillshare repo ships example extensions under `extensions/` (`gemini-commands`, `codex-agents`). Copy one into your extensions directory and adapt it — they are references, not installed automatically. +The skillshare repo ships example extensions under `extensions/` (`gemini-commands`, `codex-agents`). Copy one into your extensions directory and adapt it — they are references, not installed automatically. Each reference extension keeps `convert.js` short so you edit only the field mapping; `md-toml.js` handles reading markdown, parsing simple frontmatter, and writing TOML. ### Recipe: Codex agents