Merge pull request #217 from TrendpilotAI/feat/openclaw-target

feat: Add OpenClaw as conversion target
This commit is contained in:
Kieran Klaassen
2026-03-01 14:44:24 -08:00
committed by GitHub
6 changed files with 610 additions and 3 deletions

View File

@@ -25,7 +25,7 @@ export default defineCommand({
to: {
type: "string",
default: "opencode",
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro | qwen)",
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro | openclaw | qwen)",
},
output: {
type: "string",
@@ -42,6 +42,11 @@ export default defineCommand({
alias: "pi-home",
description: "Write Pi output to this Pi root (ex: ~/.pi/agent or ./.pi)",
},
openclawHome: {
type: "string",
alias: "openclaw-home",
description: "Write OpenClaw output to this extensions root (ex: ~/.openclaw/extensions)",
},
qwenHome: {
type: "string",
alias: "qwen-home",
@@ -89,6 +94,7 @@ export default defineCommand({
const outputRoot = resolveOutputRoot(args.output)
const codexHome = resolveTargetHome(args.codexHome, path.join(os.homedir(), ".codex"))
const piHome = resolveTargetHome(args.piHome, path.join(os.homedir(), ".pi", "agent"))
const openclawHome = resolveTargetHome(args.openclawHome, path.join(os.homedir(), ".openclaw", "extensions"))
const qwenHome = resolveTargetHome(args.qwenHome, path.join(os.homedir(), ".qwen", "extensions"))
const options = {
@@ -102,7 +108,7 @@ export default defineCommand({
throw new Error(`Target ${targetName} did not return a bundle.`)
}
const hasExplicitOutput = Boolean(args.output && String(args.output).trim())
const primaryOutputRoot = resolveTargetOutputRoot(targetName, outputRoot, codexHome, piHome, qwenHome, plugin.manifest.name, hasExplicitOutput)
const primaryOutputRoot = resolveTargetOutputRoot(targetName, outputRoot, codexHome, piHome, openclawHome, qwenHome, plugin.manifest.name, hasExplicitOutput)
await target.write(primaryOutputRoot, bundle)
console.log(`Installed ${plugin.manifest.name} to ${primaryOutputRoot}`)
@@ -123,7 +129,7 @@ export default defineCommand({
console.warn(`Skipping ${extra}: no output returned.`)
continue
}
const extraRoot = resolveTargetOutputRoot(extra, path.join(outputRoot, extra), codexHome, piHome, qwenHome, plugin.manifest.name, hasExplicitOutput)
const extraRoot = resolveTargetOutputRoot(extra, path.join(outputRoot, extra), codexHome, piHome, openclawHome, qwenHome, plugin.manifest.name, hasExplicitOutput)
await handler.write(extraRoot, extraBundle)
console.log(`Installed ${plugin.manifest.name} to ${extraRoot}`)
}
@@ -180,6 +186,7 @@ function resolveTargetOutputRoot(
outputRoot: string,
codexHome: string,
piHome: string,
openclawHome: string,
qwenHome: string,
pluginName: string,
hasExplicitOutput: boolean,
@@ -206,6 +213,9 @@ function resolveTargetOutputRoot(
const base = hasExplicitOutput ? outputRoot : process.cwd()
return path.join(base, ".kiro")
}
if (targetName === "openclaw") {
return path.join(openclawHome, pluginName)
}
return outputRoot
}

View File

@@ -0,0 +1,240 @@
import { formatFrontmatter } from "../utils/frontmatter"
import type {
ClaudeAgent,
ClaudeCommand,
ClaudePlugin,
ClaudeMcpServer,
} from "../types/claude"
import type {
OpenClawBundle,
OpenClawCommandRegistration,
OpenClawPluginManifest,
OpenClawSkillFile,
} from "../types/openclaw"
import type { ClaudeToOpenCodeOptions } from "./claude-to-opencode"
export type ClaudeToOpenClawOptions = ClaudeToOpenCodeOptions
export function convertClaudeToOpenClaw(
plugin: ClaudePlugin,
_options: ClaudeToOpenClawOptions,
): OpenClawBundle {
const enabledCommands = plugin.commands.filter((cmd) => !cmd.disableModelInvocation)
const agentSkills = plugin.agents.map(convertAgentToSkill)
const commandSkills = enabledCommands.map(convertCommandToSkill)
const commands = enabledCommands.map(convertCommand)
const skills: OpenClawSkillFile[] = [...agentSkills, ...commandSkills]
const skillDirCopies = plugin.skills.map((skill) => ({
sourceDir: skill.sourceDir,
name: skill.name,
}))
const allSkillDirs = [
...agentSkills.map((s) => s.dir),
...commandSkills.map((s) => s.dir),
...plugin.skills.map((s) => s.name),
]
const manifest = buildManifest(plugin, allSkillDirs)
const packageJson = buildPackageJson(plugin)
const openclawConfig = plugin.mcpServers
? buildOpenClawConfig(plugin.mcpServers)
: undefined
const entryPoint = generateEntryPoint(commands)
return {
manifest,
packageJson,
entryPoint,
skills,
skillDirCopies,
commands,
openclawConfig,
}
}
function buildManifest(plugin: ClaudePlugin, skillDirs: string[]): OpenClawPluginManifest {
return {
id: plugin.manifest.name,
name: formatDisplayName(plugin.manifest.name),
kind: "tool",
skills: skillDirs.map((dir) => `skills/${dir}`),
}
}
function buildPackageJson(plugin: ClaudePlugin): Record<string, unknown> {
return {
name: `openclaw-${plugin.manifest.name}`,
version: plugin.manifest.version,
type: "module",
private: true,
description: plugin.manifest.description,
main: "index.ts",
openclaw: {
extensions: [
{
id: plugin.manifest.name,
entry: "./index.ts",
},
],
},
keywords: [
"openclaw",
"openclaw-plugin",
...(plugin.manifest.keywords ?? []),
],
}
}
function convertAgentToSkill(agent: ClaudeAgent): OpenClawSkillFile {
const frontmatter: Record<string, unknown> = {
name: agent.name,
description: agent.description,
}
if (agent.model && agent.model !== "inherit") {
frontmatter.model = agent.model
}
const body = rewritePaths(agent.body)
const content = formatFrontmatter(frontmatter, body)
return {
name: agent.name,
content,
dir: `agent-${agent.name}`,
}
}
function convertCommandToSkill(command: ClaudeCommand): OpenClawSkillFile {
const frontmatter: Record<string, unknown> = {
name: `cmd-${command.name}`,
description: command.description,
}
if (command.model && command.model !== "inherit") {
frontmatter.model = command.model
}
const body = rewritePaths(command.body)
const content = formatFrontmatter(frontmatter, body)
return {
name: command.name,
content,
dir: `cmd-${command.name}`,
}
}
function convertCommand(command: ClaudeCommand): OpenClawCommandRegistration {
return {
name: command.name.replace(/:/g, "-"),
description: command.description ?? `Run ${command.name}`,
acceptsArgs: Boolean(command.argumentHint),
body: rewritePaths(command.body),
}
}
function buildOpenClawConfig(
servers: Record<string, ClaudeMcpServer>,
): Record<string, unknown> {
const mcpServers: Record<string, unknown> = {}
for (const [name, server] of Object.entries(servers)) {
if (server.command) {
mcpServers[name] = {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
}
} else if (server.url) {
mcpServers[name] = {
type: "http",
url: server.url,
headers: server.headers,
}
}
}
return { mcpServers }
}
function generateEntryPoint(commands: OpenClawCommandRegistration[]): string {
const commandRegistrations = commands
.map((cmd) => {
// JSON.stringify produces a fully-escaped string literal safe for JS/TS source embedding
const safeName = JSON.stringify(cmd.name)
const safeDesc = JSON.stringify(cmd.description ?? "")
const safeNotFound = JSON.stringify(`Command ${cmd.name} not found. Check skills directory.`)
return ` api.registerCommand({
name: ${safeName},
description: ${safeDesc},
acceptsArgs: ${cmd.acceptsArgs},
requireAuth: false,
handler: (ctx) => ({
text: skills[${safeName}] ?? ${safeNotFound},
}),
});`
})
.join("\n\n")
return `// Auto-generated OpenClaw plugin entry point
// Converted from Claude Code plugin format by compound-plugin CLI
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Pre-load skill bodies for command responses
const skills: Record<string, string> = {};
async function loadSkills() {
const skillsDir = path.join(__dirname, "skills");
try {
const entries = await fs.readdir(skillsDir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const skillPath = path.join(skillsDir, entry.name, "SKILL.md");
try {
const content = await fs.readFile(skillPath, "utf8");
// Strip frontmatter
const body = content.replace(/^---[\\s\\S]*?---\\n*/, "");
skills[entry.name.replace(/^cmd-/, "")] = body.trim();
} catch {
// Skill file not found, skip
}
}
} catch {
// Skills directory not found
}
}
export default async function register(api) {
await loadSkills();
${commandRegistrations}
}
`
}
function rewritePaths(body: string): string {
return body
.replace(/(?<=^|\s|["'`])~\/\.claude\//gm, "~/.openclaw/")
.replace(/(?<=^|\s|["'`])\.claude\//gm, ".openclaw/")
.replace(/\.claude-plugin\//g, "openclaw-plugin/")
}
function formatDisplayName(name: string): string {
return name
.split("-")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ")
}

View File

@@ -6,6 +6,7 @@ import type { PiBundle } from "../types/pi"
import type { CopilotBundle } from "../types/copilot"
import type { GeminiBundle } from "../types/gemini"
import type { KiroBundle } from "../types/kiro"
import type { OpenClawBundle } from "../types/openclaw"
import type { QwenBundle } from "../types/qwen"
import { convertClaudeToOpenCode, type ClaudeToOpenCodeOptions } from "../converters/claude-to-opencode"
import { convertClaudeToCodex } from "../converters/claude-to-codex"
@@ -14,6 +15,7 @@ import { convertClaudeToPi } from "../converters/claude-to-pi"
import { convertClaudeToCopilot } from "../converters/claude-to-copilot"
import { convertClaudeToGemini } from "../converters/claude-to-gemini"
import { convertClaudeToKiro } from "../converters/claude-to-kiro"
import { convertClaudeToOpenClaw } from "../converters/claude-to-openclaw"
import { convertClaudeToQwen, type ClaudeToQwenOptions } from "../converters/claude-to-qwen"
import { writeOpenCodeBundle } from "./opencode"
import { writeCodexBundle } from "./codex"
@@ -22,6 +24,7 @@ import { writePiBundle } from "./pi"
import { writeCopilotBundle } from "./copilot"
import { writeGeminiBundle } from "./gemini"
import { writeKiroBundle } from "./kiro"
import { writeOpenClawBundle } from "./openclaw"
import { writeQwenBundle } from "./qwen"
export type TargetHandler<TBundle = unknown> = {
@@ -74,6 +77,12 @@ export const targets: Record<string, TargetHandler> = {
convert: convertClaudeToKiro as TargetHandler<KiroBundle>["convert"],
write: writeKiroBundle as TargetHandler<KiroBundle>["write"],
},
openclaw: {
name: "openclaw",
implemented: true,
convert: convertClaudeToOpenClaw as TargetHandler<OpenClawBundle>["convert"],
write: writeOpenClawBundle as TargetHandler<OpenClawBundle>["write"],
},
qwen: {
name: "qwen",
implemented: true,

96
src/targets/openclaw.ts Normal file
View File

@@ -0,0 +1,96 @@
import path from "path"
import { promises as fs } from "fs"
import { backupFile, copyDir, ensureDir, pathExists, readJson, walkFiles, writeJson, writeText } from "../utils/files"
import type { OpenClawBundle } from "../types/openclaw"
export async function writeOpenClawBundle(outputRoot: string, bundle: OpenClawBundle): Promise<void> {
const paths = resolveOpenClawPaths(outputRoot)
await ensureDir(paths.root)
// Write openclaw.plugin.json
await writeJson(paths.manifestPath, bundle.manifest)
// Write package.json
await writeJson(paths.packageJsonPath, bundle.packageJson)
// Write index.ts entry point
await writeText(paths.entryPointPath, bundle.entryPoint)
// Write generated skills (agents + commands converted to SKILL.md)
for (const skill of bundle.skills) {
const skillDir = path.join(paths.skillsDir, skill.dir)
await ensureDir(skillDir)
await writeText(path.join(skillDir, "SKILL.md"), skill.content + "\n")
}
// Copy original skill directories (preserving references/, assets/, scripts/)
// and rewrite .claude/ paths to .openclaw/ in markdown files
for (const skill of bundle.skillDirCopies) {
const destDir = path.join(paths.skillsDir, skill.name)
await copyDir(skill.sourceDir, destDir)
await rewritePathsInDir(destDir)
}
// Write openclaw.json config fragment if MCP servers exist
if (bundle.openclawConfig) {
const configPath = path.join(paths.root, "openclaw.json")
const backupPath = await backupFile(configPath)
if (backupPath) {
console.log(`Backed up existing config to ${backupPath}`)
}
const merged = await mergeOpenClawConfig(configPath, bundle.openclawConfig)
await writeJson(configPath, merged)
}
}
function resolveOpenClawPaths(outputRoot: string) {
return {
root: outputRoot,
manifestPath: path.join(outputRoot, "openclaw.plugin.json"),
packageJsonPath: path.join(outputRoot, "package.json"),
entryPointPath: path.join(outputRoot, "index.ts"),
skillsDir: path.join(outputRoot, "skills"),
}
}
async function rewritePathsInDir(dir: string): Promise<void> {
const files = await walkFiles(dir)
for (const file of files) {
if (!file.endsWith(".md")) continue
const content = await fs.readFile(file, "utf8")
const rewritten = content
.replace(/~\/\.claude\//g, "~/.openclaw/")
.replace(/\.claude\//g, ".openclaw/")
.replace(/\.claude-plugin\//g, "openclaw-plugin/")
if (rewritten !== content) {
await fs.writeFile(file, rewritten, "utf8")
}
}
}
async function mergeOpenClawConfig(
configPath: string,
incoming: Record<string, unknown>,
): Promise<Record<string, unknown>> {
if (!(await pathExists(configPath))) return incoming
let existing: Record<string, unknown>
try {
existing = await readJson<Record<string, unknown>>(configPath)
} catch {
console.warn(
`Warning: existing ${configPath} is not valid JSON. Writing plugin config without merging.`,
)
return incoming
}
// Merge MCP servers: existing takes precedence on conflict
const incomingMcp = (incoming.mcpServers ?? {}) as Record<string, unknown>
const existingMcp = (existing.mcpServers ?? {}) as Record<string, unknown>
const mergedMcp = { ...incomingMcp, ...existingMcp }
return {
...existing,
mcpServers: Object.keys(mergedMcp).length > 0 ? mergedMcp : undefined,
}
}

52
src/types/openclaw.ts Normal file
View File

@@ -0,0 +1,52 @@
export type OpenClawPluginManifest = {
id: string
name: string
kind: "tool"
configSchema?: {
type: "object"
additionalProperties: boolean
properties: Record<string, OpenClawConfigProperty>
required?: string[]
}
uiHints?: Record<string, OpenClawUiHint>
skills?: string[]
}
export type OpenClawConfigProperty = {
type: string
description?: string
default?: unknown
}
export type OpenClawUiHint = {
label: string
sensitive?: boolean
placeholder?: string
}
export type OpenClawSkillFile = {
name: string
content: string
/** Subdirectory path inside skills/ (e.g. "agent-native-reviewer") */
dir: string
}
export type OpenClawCommandRegistration = {
name: string
description: string
acceptsArgs: boolean
/** The prompt body that becomes the command handler response */
body: string
}
export type OpenClawBundle = {
manifest: OpenClawPluginManifest
packageJson: Record<string, unknown>
entryPoint: string
skills: OpenClawSkillFile[]
/** Skill directories to copy verbatim (original Claude skills with references/) */
skillDirCopies: { sourceDir: string; name: string }[]
commands: OpenClawCommandRegistration[]
/** openclaw.json fragment for MCP servers */
openclawConfig?: Record<string, unknown>
}

View File

@@ -0,0 +1,200 @@
import { describe, expect, test } from "bun:test"
import { convertClaudeToOpenClaw } from "../src/converters/claude-to-openclaw"
import { parseFrontmatter } from "../src/utils/frontmatter"
import type { ClaudePlugin } from "../src/types/claude"
const fixturePlugin: ClaudePlugin = {
root: "/tmp/plugin",
manifest: { name: "compound-engineering", version: "1.0.0", description: "A plugin" },
agents: [
{
name: "security-reviewer",
description: "Security-focused agent",
capabilities: ["Threat modeling", "OWASP"],
model: "claude-sonnet-4-20250514",
body: "Focus on vulnerabilities in ~/.claude/settings.",
sourcePath: "/tmp/plugin/agents/security-reviewer.md",
},
],
commands: [
{
name: "workflows:plan",
description: "Planning command",
argumentHint: "[FOCUS]",
model: "inherit",
allowedTools: ["Read"],
body: "Plan the work. See ~/.claude/settings for config.",
sourcePath: "/tmp/plugin/commands/workflows/plan.md",
},
{
name: "disabled-cmd",
description: "Disabled command",
model: "inherit",
allowedTools: [],
body: "Should be excluded.",
disableModelInvocation: true,
sourcePath: "/tmp/plugin/commands/disabled-cmd.md",
},
],
skills: [
{
name: "existing-skill",
description: "Existing skill",
sourceDir: "/tmp/plugin/skills/existing-skill",
skillPath: "/tmp/plugin/skills/existing-skill/SKILL.md",
},
],
hooks: undefined,
mcpServers: {
local: { command: "npx", args: ["-y", "some-mcp-server"] },
remote: { url: "https://mcp.example.com/api", headers: { Authorization: "Bearer token" } },
},
}
const defaultOptions = {
agentMode: "subagent" as const,
inferTemperature: false,
permissions: "none" as const,
}
describe("convertClaudeToOpenClaw", () => {
test("converts agents to skill files with SKILL.md content", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
const skill = bundle.skills.find((s) => s.name === "security-reviewer")
expect(skill).toBeDefined()
expect(skill!.dir).toBe("agent-security-reviewer")
const parsed = parseFrontmatter(skill!.content)
expect(parsed.data.name).toBe("security-reviewer")
expect(parsed.data.description).toBe("Security-focused agent")
expect(parsed.data.model).toBe("claude-sonnet-4-20250514")
expect(parsed.body).toContain("Focus on vulnerabilities")
})
test("converts commands to skill files (excluding disableModelInvocation)", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
const cmdSkill = bundle.skills.find((s) => s.name === "workflows:plan")
expect(cmdSkill).toBeDefined()
expect(cmdSkill!.dir).toBe("cmd-workflows:plan")
const disabledSkill = bundle.skills.find((s) => s.name === "disabled-cmd")
expect(disabledSkill).toBeUndefined()
})
test("commands list excludes disableModelInvocation commands", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
const cmd = bundle.commands.find((c) => c.name === "workflows-plan")
expect(cmd).toBeDefined()
expect(cmd!.description).toBe("Planning command")
expect(cmd!.acceptsArgs).toBe(true)
const disabled = bundle.commands.find((c) => c.name === "disabled-cmd")
expect(disabled).toBeUndefined()
})
test("command colons are replaced with dashes in command registrations", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
const cmd = bundle.commands.find((c) => c.name === "workflows-plan")
expect(cmd).toBeDefined()
expect(cmd!.name).not.toContain(":")
})
test("manifest includes plugin id, display name, and skills list", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
expect(bundle.manifest.id).toBe("compound-engineering")
expect(bundle.manifest.name).toBe("Compound Engineering")
expect(bundle.manifest.kind).toBe("tool")
expect(bundle.manifest.skills).toContain("skills/agent-security-reviewer")
expect(bundle.manifest.skills).toContain("skills/cmd-workflows:plan")
expect(bundle.manifest.skills).toContain("skills/existing-skill")
})
test("package.json uses plugin name and version", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
expect(bundle.packageJson.name).toBe("openclaw-compound-engineering")
expect(bundle.packageJson.version).toBe("1.0.0")
expect(bundle.packageJson.type).toBe("module")
})
test("skillDirCopies includes original skill directories", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
const copy = bundle.skillDirCopies.find((s) => s.name === "existing-skill")
expect(copy).toBeDefined()
expect(copy!.sourceDir).toBe("/tmp/plugin/skills/existing-skill")
})
test("stdio MCP servers included in openclaw config", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
expect(bundle.openclawConfig).toBeDefined()
const mcp = (bundle.openclawConfig!.mcpServers as Record<string, unknown>)
expect(mcp.local).toBeDefined()
expect((mcp.local as any).type).toBe("stdio")
expect((mcp.local as any).command).toBe("npx")
})
test("HTTP MCP servers included as http type in openclaw config", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
const mcp = (bundle.openclawConfig!.mcpServers as Record<string, unknown>)
expect(mcp.remote).toBeDefined()
expect((mcp.remote as any).type).toBe("http")
expect((mcp.remote as any).url).toBe("https://mcp.example.com/api")
})
test("paths are rewritten from .claude/ to .openclaw/ in skill content", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
const agentSkill = bundle.skills.find((s) => s.name === "security-reviewer")
expect(agentSkill!.content).toContain("~/.openclaw/settings")
expect(agentSkill!.content).not.toContain("~/.claude/settings")
const cmdSkill = bundle.skills.find((s) => s.name === "workflows:plan")
expect(cmdSkill!.content).toContain("~/.openclaw/settings")
expect(cmdSkill!.content).not.toContain("~/.claude/settings")
})
test("generateEntryPoint uses JSON.stringify for safe string escaping", () => {
const plugin: ClaudePlugin = {
...fixturePlugin,
commands: [
{
name: "tricky-cmd",
description: 'Has "quotes" and \\backslashes\\ and\nnewlines',
model: "inherit",
allowedTools: [],
body: "body",
sourcePath: "/tmp/cmd.md",
},
],
}
const bundle = convertClaudeToOpenClaw(plugin, defaultOptions)
// Entry point must be valid JS/TS — JSON.stringify handles all special chars
expect(bundle.entryPoint).toContain('"tricky-cmd"')
expect(bundle.entryPoint).toContain('\\"quotes\\"')
expect(bundle.entryPoint).toContain("\\\\backslashes\\\\")
expect(bundle.entryPoint).toContain("\\n")
// No raw unescaped newline inside a string literal
const lines = bundle.entryPoint.split("\n")
const nameLine = lines.find((l) => l.includes("tricky-cmd") && l.includes("name:"))
expect(nameLine).toBeDefined()
})
test("generateEntryPoint emits typed skills record", () => {
const bundle = convertClaudeToOpenClaw(fixturePlugin, defaultOptions)
expect(bundle.entryPoint).toContain("const skills: Record<string, string> = {}")
})
test("plugin without MCP servers has no openclawConfig", () => {
const plugin: ClaudePlugin = { ...fixturePlugin, mcpServers: undefined }
const bundle = convertClaudeToOpenClaw(plugin, defaultOptions)
expect(bundle.openclawConfig).toBeUndefined()
})
})