chore: Resolve conflicts with main, update to v0.12.0

- sync.ts: add gemini + all targets, keep copilot, remove cursor (native), use shared hasPotentialSecrets
- install.ts + convert.ts: import both detectInstalledTools and resolveTargetOutputRoot; update --to all block to use new object API; fix resolvedScope ordering (was referencing target before definition)
- CHANGELOG.md: add v0.12.0 entry (auto-detect + Gemini sync)
- README.md: merge all install targets, collapsible output format table, sync defaults to --target all
- package.json: bump to 0.12.0
- sync --target now defaults to "all" when omitted

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Kieran Klaassen
2026-03-01 15:12:21 -08:00
83 changed files with 9076 additions and 913 deletions

View File

@@ -2,10 +2,11 @@ import { defineCommand } from "citty"
import os from "os"
import path from "path"
import { loadClaudePlugin } from "../parsers/claude"
import { targets } from "../targets"
import { targets, validateScope } from "../targets"
import type { PermissionMode } from "../converters/claude-to-opencode"
import { ensureCodexAgentsFile } from "../utils/codex-agents"
import { expandHome, resolveTargetHome } from "../utils/resolve-home"
import { resolveTargetOutputRoot } from "../utils/resolve-output"
import { detectInstalledTools } from "../utils/detect-tools"
const permissionModes: PermissionMode[] = ["none", "broad", "from-commands"]
@@ -24,7 +25,7 @@ export default defineCommand({
to: {
type: "string",
default: "opencode",
description: "Target format (opencode | codex | droid | cursor | pi | gemini | all)",
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro | windsurf | openclaw | qwen | all)",
},
output: {
type: "string",
@@ -41,6 +42,20 @@ 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",
description: "Write Qwen output to this Qwen extensions root (ex: ~/.qwen/extensions)",
},
scope: {
type: "string",
description: "Scope level: global | workspace (default varies by target)",
},
also: {
type: "string",
description: "Comma-separated extra targets to generate (ex: codex)",
@@ -71,8 +86,11 @@ export default defineCommand({
const plugin = await loadClaudePlugin(String(args.source))
const outputRoot = resolveOutputRoot(args.output)
const hasExplicitOutput = Boolean(args.output && String(args.output).trim())
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 = {
agentMode: String(args.agentMode) === "primary" ? "primary" : "subagent",
@@ -105,7 +123,16 @@ export default defineCommand({
console.warn(`Skipping ${tool.name}: no output returned.`)
continue
}
const root = resolveTargetOutputRoot(tool.name, outputRoot, codexHome, piHome)
const root = resolveTargetOutputRoot({
targetName: tool.name,
outputRoot,
codexHome,
piHome,
openclawHome,
qwenHome,
pluginName: plugin.manifest.name,
hasExplicitOutput,
})
await handler.write(root, bundle)
console.log(`Converted ${plugin.manifest.name} to ${tool.name} at ${root}`)
}
@@ -125,13 +152,25 @@ export default defineCommand({
throw new Error(`Target ${targetName} is registered but not implemented yet.`)
}
const primaryOutputRoot = resolveTargetOutputRoot(targetName, outputRoot, codexHome, piHome)
const resolvedScope = validateScope(targetName, target, args.scope ? String(args.scope) : undefined)
const primaryOutputRoot = resolveTargetOutputRoot({
targetName,
outputRoot,
codexHome,
piHome,
openclawHome,
qwenHome,
pluginName: plugin.manifest.name,
hasExplicitOutput,
scope: resolvedScope,
})
const bundle = target.convert(plugin, options)
if (!bundle) {
throw new Error(`Target ${targetName} did not return a bundle.`)
}
await target.write(primaryOutputRoot, bundle)
await target.write(primaryOutputRoot, bundle, resolvedScope)
console.log(`Converted ${plugin.manifest.name} to ${targetName} at ${primaryOutputRoot}`)
const extraTargets = parseExtraTargets(args.also)
@@ -151,8 +190,18 @@ export default defineCommand({
console.warn(`Skipping ${extra}: no output returned.`)
continue
}
const extraRoot = resolveTargetOutputRoot(extra, path.join(outputRoot, extra), codexHome, piHome)
await handler.write(extraRoot, extraBundle)
const extraRoot = resolveTargetOutputRoot({
targetName: extra,
outputRoot: path.join(outputRoot, extra),
codexHome,
piHome,
openclawHome,
qwenHome,
pluginName: plugin.manifest.name,
hasExplicitOutput,
scope: handler.defaultScope,
})
await handler.write(extraRoot, extraBundle, handler.defaultScope)
console.log(`Converted ${plugin.manifest.name} to ${extra} at ${extraRoot}`)
}
@@ -177,12 +226,3 @@ function resolveOutputRoot(value: unknown): string {
}
return process.cwd()
}
function resolveTargetOutputRoot(targetName: string, outputRoot: string, codexHome: string, piHome: string): string {
if (targetName === "codex") return codexHome
if (targetName === "pi") return piHome
if (targetName === "droid") return path.join(os.homedir(), ".factory")
if (targetName === "cursor") return path.join(outputRoot, ".cursor")
if (targetName === "gemini") return path.join(outputRoot, ".gemini")
return outputRoot
}

View File

@@ -3,11 +3,12 @@ import { promises as fs } from "fs"
import os from "os"
import path from "path"
import { loadClaudePlugin } from "../parsers/claude"
import { targets } from "../targets"
import { targets, validateScope } from "../targets"
import { pathExists } from "../utils/files"
import type { PermissionMode } from "../converters/claude-to-opencode"
import { ensureCodexAgentsFile } from "../utils/codex-agents"
import { expandHome, resolveTargetHome } from "../utils/resolve-home"
import { resolveTargetOutputRoot } from "../utils/resolve-output"
import { detectInstalledTools } from "../utils/detect-tools"
const permissionModes: PermissionMode[] = ["none", "broad", "from-commands"]
@@ -26,7 +27,7 @@ export default defineCommand({
to: {
type: "string",
default: "opencode",
description: "Target format (opencode | codex | droid | cursor | pi | gemini | all)",
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro | windsurf | openclaw | qwen | all)",
},
output: {
type: "string",
@@ -43,14 +44,28 @@ 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",
description: "Write Qwen output to this Qwen extensions root (ex: ~/.qwen/extensions)",
},
scope: {
type: "string",
description: "Scope level: global | workspace (default varies by target)",
},
also: {
type: "string",
description: "Comma-separated extra targets to generate (ex: codex)",
},
permissions: {
type: "string",
default: "broad",
description: "Permission mapping: none | broad | from-commands",
default: "none", // Default is "none" -- writing global permissions to opencode.json pollutes user config. See ADR-003.
description: "Permission mapping written to opencode.json: none (default) | broad | from-command",
},
agentMode: {
type: "string",
@@ -79,6 +94,8 @@ export default defineCommand({
const codexHome = resolveTargetHome(args.codexHome, path.join(os.homedir(), ".codex"))
const piHome = resolveTargetHome(args.piHome, path.join(os.homedir(), ".pi", "agent"))
const hasExplicitOutput = Boolean(args.output && String(args.output).trim())
const openclawHome = resolveTargetHome(args.openclawHome, path.join(os.homedir(), ".openclaw", "extensions"))
const qwenHome = resolveTargetHome(args.qwenHome, path.join(os.homedir(), ".qwen", "extensions"))
const options = {
agentMode: String(args.agentMode) === "primary" ? "primary" : "subagent",
@@ -111,7 +128,16 @@ export default defineCommand({
console.warn(`Skipping ${tool.name}: no output returned.`)
continue
}
const root = resolveTargetOutputRoot(tool.name, outputRoot, codexHome, piHome, hasExplicitOutput)
const root = resolveTargetOutputRoot({
targetName: tool.name,
outputRoot,
codexHome,
piHome,
openclawHome,
qwenHome,
pluginName: plugin.manifest.name,
hasExplicitOutput,
})
await handler.write(root, bundle)
console.log(`Installed ${plugin.manifest.name} to ${tool.name} at ${root}`)
}
@@ -130,12 +156,24 @@ export default defineCommand({
throw new Error(`Target ${targetName} is registered but not implemented yet.`)
}
const resolvedScope = validateScope(targetName, target, args.scope ? String(args.scope) : undefined)
const bundle = target.convert(plugin, options)
if (!bundle) {
throw new Error(`Target ${targetName} did not return a bundle.`)
}
const primaryOutputRoot = resolveTargetOutputRoot(targetName, outputRoot, codexHome, piHome, hasExplicitOutput)
await target.write(primaryOutputRoot, bundle)
const primaryOutputRoot = resolveTargetOutputRoot({
targetName,
outputRoot,
codexHome,
piHome,
openclawHome,
qwenHome,
pluginName: plugin.manifest.name,
hasExplicitOutput,
scope: resolvedScope,
})
await target.write(primaryOutputRoot, bundle, resolvedScope)
console.log(`Installed ${plugin.manifest.name} to ${primaryOutputRoot}`)
const extraTargets = parseExtraTargets(args.also)
@@ -155,8 +193,18 @@ export default defineCommand({
console.warn(`Skipping ${extra}: no output returned.`)
continue
}
const extraRoot = resolveTargetOutputRoot(extra, path.join(outputRoot, extra), codexHome, piHome, hasExplicitOutput)
await handler.write(extraRoot, extraBundle)
const extraRoot = resolveTargetOutputRoot({
targetName: extra,
outputRoot: path.join(outputRoot, extra),
codexHome,
piHome,
openclawHome,
qwenHome,
pluginName: plugin.manifest.name,
hasExplicitOutput,
scope: handler.defaultScope,
})
await handler.write(extraRoot, extraBundle, handler.defaultScope)
console.log(`Installed ${plugin.manifest.name} to ${extraRoot}`)
}
@@ -207,27 +255,6 @@ function resolveOutputRoot(value: unknown): string {
return path.join(os.homedir(), ".config", "opencode")
}
function resolveTargetOutputRoot(
targetName: string,
outputRoot: string,
codexHome: string,
piHome: string,
hasExplicitOutput: boolean,
): string {
if (targetName === "codex") return codexHome
if (targetName === "pi") return piHome
if (targetName === "droid") return path.join(os.homedir(), ".factory")
if (targetName === "cursor") {
const base = hasExplicitOutput ? outputRoot : process.cwd()
return path.join(base, ".cursor")
}
if (targetName === "gemini") {
const base = hasExplicitOutput ? outputRoot : process.cwd()
return path.join(base, ".gemini")
}
return outputRoot
}
async function resolveGitHubPluginPath(pluginName: string): Promise<ResolvedPluginPath> {
const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "compound-plugin-"))
const source = resolveGitHubSource()

View File

@@ -6,32 +6,19 @@ import { syncToOpenCode } from "../sync/opencode"
import { syncToCodex } from "../sync/codex"
import { syncToPi } from "../sync/pi"
import { syncToDroid } from "../sync/droid"
import { syncToCursor } from "../sync/cursor"
import { syncToCopilot } from "../sync/copilot"
import { syncToGemini } from "../sync/gemini"
import { expandHome } from "../utils/resolve-home"
import { hasPotentialSecrets } from "../utils/secrets"
import { detectInstalledTools } from "../utils/detect-tools"
const validTargets = ["opencode", "codex", "pi", "droid", "cursor", "gemini", "all"] as const
const validTargets = ["opencode", "codex", "pi", "droid", "copilot", "gemini", "all"] as const
type SyncTarget = (typeof validTargets)[number]
function isValidTarget(value: string): value is SyncTarget {
return (validTargets as readonly string[]).includes(value)
}
/** Check if any MCP servers have env vars that might contain secrets */
function hasPotentialSecrets(mcpServers: Record<string, unknown>): boolean {
const sensitivePatterns = /key|token|secret|password|credential|api_key/i
for (const server of Object.values(mcpServers)) {
const env = (server as { env?: Record<string, string> }).env
if (env) {
for (const key of Object.keys(env)) {
if (sensitivePatterns.test(key)) return true
}
}
}
return false
}
function resolveOutputRoot(target: string): string {
switch (target) {
case "opencode":
@@ -42,8 +29,8 @@ function resolveOutputRoot(target: string): string {
return path.join(os.homedir(), ".pi", "agent")
case "droid":
return path.join(os.homedir(), ".factory")
case "cursor":
return path.join(process.cwd(), ".cursor")
case "copilot":
return path.join(process.cwd(), ".github")
case "gemini":
return path.join(process.cwd(), ".gemini")
default:
@@ -65,8 +52,8 @@ async function syncTarget(target: string, config: Awaited<ReturnType<typeof load
case "droid":
await syncToDroid(config, outputRoot)
break
case "cursor":
await syncToCursor(config, outputRoot)
case "copilot":
await syncToCopilot(config, outputRoot)
break
case "gemini":
await syncToGemini(config, outputRoot)
@@ -77,13 +64,13 @@ async function syncTarget(target: string, config: Awaited<ReturnType<typeof load
export default defineCommand({
meta: {
name: "sync",
description: "Sync Claude Code config (~/.claude/) to OpenCode, Codex, Pi, Droid, Cursor, or Gemini",
description: "Sync Claude Code config (~/.claude/) to OpenCode, Codex, Pi, Droid, Copilot, or Gemini",
},
args: {
target: {
type: "string",
required: true,
description: "Target: opencode | codex | pi | droid | cursor | gemini | all",
default: "all",
description: "Target: opencode | codex | pi | droid | copilot | gemini | all (default: all)",
},
claudeHome: {
type: "string",

View File

@@ -1,43 +1,63 @@
import { formatFrontmatter } from "../utils/frontmatter"
import type { ClaudeAgent, ClaudeCommand, ClaudeMcpServer, ClaudePlugin } from "../types/claude"
import type { CursorBundle, CursorCommand, CursorMcpServer, CursorRule } from "../types/cursor"
import type {
CopilotAgent,
CopilotBundle,
CopilotGeneratedSkill,
CopilotMcpServer,
} from "../types/copilot"
import type { ClaudeToOpenCodeOptions } from "./claude-to-opencode"
export type ClaudeToCursorOptions = ClaudeToOpenCodeOptions
export type ClaudeToCopilotOptions = ClaudeToOpenCodeOptions
export function convertClaudeToCursor(
const COPILOT_BODY_CHAR_LIMIT = 30_000
export function convertClaudeToCopilot(
plugin: ClaudePlugin,
_options: ClaudeToCursorOptions,
): CursorBundle {
const usedRuleNames = new Set<string>()
const usedCommandNames = new Set<string>()
_options: ClaudeToCopilotOptions,
): CopilotBundle {
const usedAgentNames = new Set<string>()
const usedSkillNames = new Set<string>()
const rules = plugin.agents.map((agent) => convertAgentToRule(agent, usedRuleNames))
const commands = plugin.commands.map((command) => convertCommand(command, usedCommandNames))
const skillDirs = plugin.skills.map((skill) => ({
name: skill.name,
sourceDir: skill.sourceDir,
}))
const agents = plugin.agents.map((agent) => convertAgent(agent, usedAgentNames))
const mcpServers = convertMcpServers(plugin.mcpServers)
// Reserve skill names first so generated skills (from commands) don't collide
const skillDirs = plugin.skills.map((skill) => {
usedSkillNames.add(skill.name)
return {
name: skill.name,
sourceDir: skill.sourceDir,
}
})
const generatedSkills = plugin.commands.map((command) =>
convertCommandToSkill(command, usedSkillNames),
)
const mcpConfig = convertMcpServers(plugin.mcpServers)
if (plugin.hooks && Object.keys(plugin.hooks.hooks).length > 0) {
console.warn("Warning: Cursor does not support hooks. Hooks were skipped during conversion.")
console.warn("Warning: Copilot does not support hooks. Hooks were skipped during conversion.")
}
return { rules, commands, skillDirs, mcpServers }
return { agents, generatedSkills, skillDirs, mcpConfig }
}
function convertAgentToRule(agent: ClaudeAgent, usedNames: Set<string>): CursorRule {
function convertAgent(agent: ClaudeAgent, usedNames: Set<string>): CopilotAgent {
const name = uniqueName(normalizeName(agent.name), usedNames)
const description = agent.description ?? `Converted from Claude agent ${agent.name}`
const frontmatter: Record<string, unknown> = {
description,
alwaysApply: false,
tools: ["*"],
infer: true,
}
let body = transformContentForCursor(agent.body.trim())
if (agent.model) {
frontmatter.model = agent.model
}
let body = transformContentForCopilot(agent.body.trim())
if (agent.capabilities && agent.capabilities.length > 0) {
const capabilities = agent.capabilities.map((c) => `- ${c}`).join("\n")
body = `## Capabilities\n${capabilities}\n\n${body}`.trim()
@@ -46,39 +66,44 @@ function convertAgentToRule(agent: ClaudeAgent, usedNames: Set<string>): CursorR
body = `Instructions converted from the ${agent.name} agent.`
}
if (body.length > COPILOT_BODY_CHAR_LIMIT) {
console.warn(
`Warning: Agent "${agent.name}" body exceeds ${COPILOT_BODY_CHAR_LIMIT} characters (${body.length}). Copilot may truncate it.`,
)
}
const content = formatFrontmatter(frontmatter, body)
return { name, content }
}
function convertCommand(command: ClaudeCommand, usedNames: Set<string>): CursorCommand {
function convertCommandToSkill(
command: ClaudeCommand,
usedNames: Set<string>,
): CopilotGeneratedSkill {
const name = uniqueName(flattenCommandName(command.name), usedNames)
const sections: string[] = []
if (command.description) {
sections.push(`<!-- ${command.description} -->`)
const frontmatter: Record<string, unknown> = {
name,
}
if (command.description) {
frontmatter.description = command.description
}
const sections: string[] = []
if (command.argumentHint) {
sections.push(`## Arguments\n${command.argumentHint}`)
}
const transformedBody = transformContentForCursor(command.body.trim())
const transformedBody = transformContentForCopilot(command.body.trim())
sections.push(transformedBody)
const content = sections.filter(Boolean).join("\n\n").trim()
const body = sections.filter(Boolean).join("\n\n").trim()
const content = formatFrontmatter(frontmatter, body)
return { name, content }
}
/**
* Transform Claude Code content to Cursor-compatible content.
*
* 1. Task agent calls: Task agent-name(args) -> Use the agent-name skill to: args
* 2. Slash commands: /workflows:plan -> /plan (flatten namespace)
* 3. Path rewriting: .claude/ -> .cursor/
* 4. Agent references: @agent-name -> the agent-name rule
*/
export function transformContentForCursor(body: string): string {
export function transformContentForCopilot(body: string): string {
let result = body
// 1. Transform Task agent calls
@@ -88,24 +113,25 @@ export function transformContentForCursor(body: string): string {
return `${prefix}Use the ${skillName} skill to: ${args.trim()}`
})
// 2. Transform slash command references (flatten namespaces)
// 2. Transform slash command references (replace colons with hyphens)
const slashCommandPattern = /(?<![:\w])\/([a-z][a-z0-9_:-]*?)(?=[\s,."')\]}`]|$)/gi
result = result.replace(slashCommandPattern, (match, commandName: string) => {
if (commandName.includes("/")) return match
if (["dev", "tmp", "etc", "usr", "var", "bin", "home"].includes(commandName)) return match
const flattened = flattenCommandName(commandName)
return `/${flattened}`
const normalized = flattenCommandName(commandName)
return `/${normalized}`
})
// 3. Rewrite .claude/ paths to .cursor/
// 3. Rewrite .claude/ paths to .github/ and ~/.claude/ to ~/.copilot/
result = result
.replace(/~\/\.claude\//g, "~/.cursor/")
.replace(/\.claude\//g, ".cursor/")
.replace(/~\/\.claude\//g, "~/.copilot/")
.replace(/\.claude\//g, ".github/")
// 4. Transform @agent-name references
const agentRefPattern = /@([a-z][a-z0-9-]*-(?:agent|reviewer|researcher|analyst|specialist|oracle|sentinel|guardian|strategist))/gi
const agentRefPattern =
/@([a-z][a-z0-9-]*-(?:agent|reviewer|researcher|analyst|specialist|oracle|sentinel|guardian|strategist))/gi
result = result.replace(agentRefPattern, (_match, agentName: string) => {
return `the ${normalizeName(agentName)} rule`
return `the ${normalizeName(agentName)} agent`
})
return result
@@ -113,29 +139,47 @@ export function transformContentForCursor(body: string): string {
function convertMcpServers(
servers?: Record<string, ClaudeMcpServer>,
): Record<string, CursorMcpServer> | undefined {
): Record<string, CopilotMcpServer> | undefined {
if (!servers || Object.keys(servers).length === 0) return undefined
const result: Record<string, CursorMcpServer> = {}
const result: Record<string, CopilotMcpServer> = {}
for (const [name, server] of Object.entries(servers)) {
const entry: CursorMcpServer = {}
const entry: CopilotMcpServer = {
type: server.command ? "local" : "sse",
tools: ["*"],
}
if (server.command) {
entry.command = server.command
if (server.args && server.args.length > 0) entry.args = server.args
if (server.env && Object.keys(server.env).length > 0) entry.env = server.env
} else if (server.url) {
entry.url = server.url
if (server.headers && Object.keys(server.headers).length > 0) entry.headers = server.headers
}
if (server.env && Object.keys(server.env).length > 0) {
entry.env = prefixEnvVars(server.env)
}
result[name] = entry
}
return result
}
function prefixEnvVars(env: Record<string, string>): Record<string, string> {
const result: Record<string, string> = {}
for (const [key, value] of Object.entries(env)) {
if (key.startsWith("COPILOT_MCP_")) {
result[key] = value
} else {
result[`COPILOT_MCP_${key}`] = value
}
}
return result
}
function flattenCommandName(name: string): string {
const colonIndex = name.lastIndexOf(":")
const base = colonIndex >= 0 ? name.slice(colonIndex + 1) : name
return normalizeName(base)
return normalizeName(name)
}
function normalizeName(value: string): string {

View File

@@ -0,0 +1,262 @@
import { readFileSync, existsSync } from "fs"
import path from "path"
import { formatFrontmatter } from "../utils/frontmatter"
import type { ClaudeAgent, ClaudeCommand, ClaudeMcpServer, ClaudePlugin } from "../types/claude"
import type {
KiroAgent,
KiroAgentConfig,
KiroBundle,
KiroMcpServer,
KiroSkill,
KiroSteeringFile,
} from "../types/kiro"
import type { ClaudeToOpenCodeOptions } from "./claude-to-opencode"
export type ClaudeToKiroOptions = ClaudeToOpenCodeOptions
const KIRO_SKILL_NAME_MAX_LENGTH = 64
const KIRO_SKILL_NAME_PATTERN = /^[a-z][a-z0-9-]*$/
const KIRO_DESCRIPTION_MAX_LENGTH = 1024
const CLAUDE_TO_KIRO_TOOLS: Record<string, string> = {
Bash: "shell",
Write: "write",
Read: "read",
Edit: "write", // NOTE: Kiro write is full-file, not surgical edit. Lossy mapping.
Glob: "glob",
Grep: "grep",
WebFetch: "web_fetch",
Task: "use_subagent",
}
export function convertClaudeToKiro(
plugin: ClaudePlugin,
_options: ClaudeToKiroOptions,
): KiroBundle {
const usedSkillNames = new Set<string>()
// Pass-through skills are processed first — they're the source of truth
const skillDirs = plugin.skills.map((skill) => ({
name: skill.name,
sourceDir: skill.sourceDir,
}))
for (const skill of skillDirs) {
usedSkillNames.add(normalizeName(skill.name))
}
// Convert agents to Kiro custom agents
const agentNames = plugin.agents.map((a) => normalizeName(a.name))
const agents = plugin.agents.map((agent) => convertAgentToKiroAgent(agent, agentNames))
// Convert commands to skills (generated)
const generatedSkills = plugin.commands.map((command) =>
convertCommandToSkill(command, usedSkillNames, agentNames),
)
// Convert MCP servers (stdio only)
const mcpServers = convertMcpServers(plugin.mcpServers)
// Build steering files from CLAUDE.md
const steeringFiles = buildSteeringFiles(plugin, agentNames)
// Warn about hooks
if (plugin.hooks && Object.keys(plugin.hooks.hooks).length > 0) {
console.warn(
"Warning: Kiro CLI hooks use a different format (preToolUse/postToolUse inside agent configs). Hooks were skipped during conversion.",
)
}
return { agents, generatedSkills, skillDirs, steeringFiles, mcpServers }
}
function convertAgentToKiroAgent(agent: ClaudeAgent, knownAgentNames: string[]): KiroAgent {
const name = normalizeName(agent.name)
const description = sanitizeDescription(
agent.description ?? `Use this agent for ${agent.name} tasks`,
)
const config: KiroAgentConfig = {
name,
description,
prompt: `file://./prompts/${name}.md`,
tools: ["*"],
resources: [
"file://.kiro/steering/**/*.md",
"skill://.kiro/skills/**/SKILL.md",
],
includeMcpJson: true,
welcomeMessage: `Switching to the ${name} agent. ${description}`,
}
let body = transformContentForKiro(agent.body.trim(), knownAgentNames)
if (agent.capabilities && agent.capabilities.length > 0) {
const capabilities = agent.capabilities.map((c) => `- ${c}`).join("\n")
body = `## Capabilities\n${capabilities}\n\n${body}`.trim()
}
if (body.length === 0) {
body = `Instructions converted from the ${agent.name} agent.`
}
return { name, config, promptContent: body }
}
function convertCommandToSkill(
command: ClaudeCommand,
usedNames: Set<string>,
knownAgentNames: string[],
): KiroSkill {
const rawName = normalizeName(command.name)
const name = uniqueName(rawName, usedNames)
const description = sanitizeDescription(
command.description ?? `Converted from Claude command ${command.name}`,
)
const frontmatter: Record<string, unknown> = { name, description }
let body = transformContentForKiro(command.body.trim(), knownAgentNames)
if (body.length === 0) {
body = `Instructions converted from the ${command.name} command.`
}
const content = formatFrontmatter(frontmatter, body)
return { name, content }
}
/**
* Transform Claude Code content to Kiro-compatible content.
*
* 1. Task agent calls: Task agent-name(args) -> Use the use_subagent tool ...
* 2. Path rewriting: .claude/ -> .kiro/, ~/.claude/ -> ~/.kiro/
* 3. Slash command refs: /workflows:plan -> use the workflows-plan skill
* 4. Claude tool names: Bash -> shell, Read -> read, etc.
* 5. Agent refs: @agent-name -> the agent-name agent (only for known agent names)
*/
export function transformContentForKiro(body: string, knownAgentNames: string[] = []): string {
let result = body
// 1. Transform Task agent calls
const taskPattern = /^(\s*-?\s*)Task\s+([a-z][a-z0-9-]*)\(([^)]+)\)/gm
result = result.replace(taskPattern, (_match, prefix: string, agentName: string, args: string) => {
return `${prefix}Use the use_subagent tool to delegate to the ${normalizeName(agentName)} agent: ${args.trim()}`
})
// 2. Rewrite .claude/ paths to .kiro/ (with word-boundary-like lookbehind)
result = result.replace(/(?<=^|\s|["'`])~\/\.claude\//gm, "~/.kiro/")
result = result.replace(/(?<=^|\s|["'`])\.claude\//gm, ".kiro/")
// 3. Slash command refs: /command-name -> skill activation language
result = result.replace(/(?<=^|\s)`?\/([a-zA-Z][a-zA-Z0-9_:-]*)`?/gm, (_match, cmdName: string) => {
const skillName = normalizeName(cmdName)
return `the ${skillName} skill`
})
// 4. Claude tool names -> Kiro tool names
for (const [claudeTool, kiroTool] of Object.entries(CLAUDE_TO_KIRO_TOOLS)) {
// Match tool name references: "the X tool", "using X", "use X to"
const toolPattern = new RegExp(`\\b${claudeTool}\\b(?=\\s+tool|\\s+to\\s)`, "g")
result = result.replace(toolPattern, kiroTool)
}
// 5. Transform @agent-name references (only for known agent names)
if (knownAgentNames.length > 0) {
const escapedNames = knownAgentNames.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
const agentRefPattern = new RegExp(`@(${escapedNames.join("|")})\\b`, "g")
result = result.replace(agentRefPattern, (_match, agentName: string) => {
return `the ${normalizeName(agentName)} agent`
})
}
return result
}
function convertMcpServers(
servers?: Record<string, ClaudeMcpServer>,
): Record<string, KiroMcpServer> {
if (!servers || Object.keys(servers).length === 0) return {}
const result: Record<string, KiroMcpServer> = {}
for (const [name, server] of Object.entries(servers)) {
if (!server.command) {
console.warn(
`Warning: MCP server "${name}" has no command (HTTP/SSE transport). Kiro only supports stdio. Skipping.`,
)
continue
}
const entry: KiroMcpServer = { command: server.command }
if (server.args && server.args.length > 0) entry.args = server.args
if (server.env && Object.keys(server.env).length > 0) entry.env = server.env
console.log(`MCP server "${name}" will execute: ${server.command}${server.args ? " " + server.args.join(" ") : ""}`)
result[name] = entry
}
return result
}
function buildSteeringFiles(plugin: ClaudePlugin, knownAgentNames: string[]): KiroSteeringFile[] {
const claudeMdPath = path.join(plugin.root, "CLAUDE.md")
if (!existsSync(claudeMdPath)) return []
let content: string
try {
content = readFileSync(claudeMdPath, "utf8")
} catch {
return []
}
if (!content || content.trim().length === 0) return []
const transformed = transformContentForKiro(content, knownAgentNames)
return [{ name: "compound-engineering", content: transformed }]
}
function normalizeName(value: string): string {
const trimmed = value.trim()
if (!trimmed) return "item"
let normalized = trimmed
.toLowerCase()
.replace(/[\\/]+/g, "-")
.replace(/[:\s]+/g, "-")
.replace(/[^a-z0-9_-]+/g, "-")
.replace(/-+/g, "-") // Collapse consecutive hyphens (Agent Skills standard)
.replace(/^-+|-+$/g, "")
// Enforce max length (truncate at last hyphen boundary)
if (normalized.length > KIRO_SKILL_NAME_MAX_LENGTH) {
normalized = normalized.slice(0, KIRO_SKILL_NAME_MAX_LENGTH)
const lastHyphen = normalized.lastIndexOf("-")
if (lastHyphen > 0) {
normalized = normalized.slice(0, lastHyphen)
}
normalized = normalized.replace(/-+$/g, "")
}
// Ensure name starts with a letter
if (normalized.length === 0 || !/^[a-z]/.test(normalized)) {
return "item"
}
return normalized
}
function sanitizeDescription(value: string, maxLength = KIRO_DESCRIPTION_MAX_LENGTH): string {
const normalized = value.replace(/\s+/g, " ").trim()
if (normalized.length <= maxLength) return normalized
const ellipsis = "..."
return normalized.slice(0, Math.max(0, maxLength - ellipsis.length)).trimEnd() + ellipsis
}
function uniqueName(base: string, used: Set<string>): string {
if (!used.has(base)) {
used.add(base)
return base
}
let index = 2
while (used.has(`${base}-${index}`)) {
index += 1
}
const name = `${base}-${index}`
used.add(name)
return name
}

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

@@ -8,7 +8,7 @@ import type {
} from "../types/claude"
import type {
OpenCodeBundle,
OpenCodeCommandConfig,
OpenCodeCommandFile,
OpenCodeConfig,
OpenCodeMcpServer,
} from "../types/opencode"
@@ -66,13 +66,12 @@ export function convertClaudeToOpenCode(
options: ClaudeToOpenCodeOptions,
): OpenCodeBundle {
const agentFiles = plugin.agents.map((agent) => convertAgent(agent, options))
const commandMap = convertCommands(plugin.commands)
const cmdFiles = convertCommands(plugin.commands)
const mcp = plugin.mcpServers ? convertMcp(plugin.mcpServers) : undefined
const plugins = plugin.hooks ? [convertHooks(plugin.hooks)] : []
const config: OpenCodeConfig = {
$schema: "https://opencode.ai/config.json",
command: Object.keys(commandMap).length > 0 ? commandMap : undefined,
mcp: mcp && Object.keys(mcp).length > 0 ? mcp : undefined,
}
@@ -81,6 +80,7 @@ export function convertClaudeToOpenCode(
return {
config,
agents: agentFiles,
commandFiles: cmdFiles,
plugins,
skillDirs: plugin.skills.map((skill) => ({ sourceDir: skill.sourceDir, name: skill.name })),
}
@@ -111,20 +111,22 @@ function convertAgent(agent: ClaudeAgent, options: ClaudeToOpenCodeOptions) {
}
}
function convertCommands(commands: ClaudeCommand[]): Record<string, OpenCodeCommandConfig> {
const result: Record<string, OpenCodeCommandConfig> = {}
// Commands are written as individual .md files rather than entries in opencode.json.
// Chosen over JSON map because opencode resolves commands by filename at runtime (ADR-001).
function convertCommands(commands: ClaudeCommand[]): OpenCodeCommandFile[] {
const files: OpenCodeCommandFile[] = []
for (const command of commands) {
if (command.disableModelInvocation) continue
const entry: OpenCodeCommandConfig = {
const frontmatter: Record<string, unknown> = {
description: command.description,
template: rewriteClaudePaths(command.body),
}
if (command.model && command.model !== "inherit") {
entry.model = normalizeModel(command.model)
frontmatter.model = normalizeModel(command.model)
}
result[command.name] = entry
const content = formatFrontmatter(frontmatter, rewriteClaudePaths(command.body))
files.push({ name: command.name, content })
}
return result
return files
}
function convertMcp(servers: Record<string, ClaudeMcpServer>): Record<string, OpenCodeMcpServer> {

View File

@@ -0,0 +1,238 @@
import { formatFrontmatter } from "../utils/frontmatter"
import type { ClaudeAgent, ClaudeCommand, ClaudeMcpServer, ClaudePlugin } from "../types/claude"
import type {
QwenAgentFile,
QwenBundle,
QwenCommandFile,
QwenExtensionConfig,
QwenMcpServer,
QwenSetting,
} from "../types/qwen"
export type ClaudeToQwenOptions = {
agentMode: "primary" | "subagent"
inferTemperature: boolean
}
export function convertClaudeToQwen(plugin: ClaudePlugin, options: ClaudeToQwenOptions): QwenBundle {
const agentFiles = plugin.agents.map((agent) => convertAgent(agent, options))
const cmdFiles = convertCommands(plugin.commands)
const mcp = plugin.mcpServers ? convertMcp(plugin.mcpServers) : undefined
const settings = extractSettings(plugin.mcpServers)
const config: QwenExtensionConfig = {
name: plugin.manifest.name,
version: plugin.manifest.version || "1.0.0",
commands: "commands",
skills: "skills",
agents: "agents",
}
if (mcp && Object.keys(mcp).length > 0) {
config.mcpServers = mcp
}
if (settings && settings.length > 0) {
config.settings = settings
}
const contextFile = generateContextFile(plugin)
return {
config,
agents: agentFiles,
commandFiles: cmdFiles,
skillDirs: plugin.skills.map((skill) => ({ sourceDir: skill.sourceDir, name: skill.name })),
contextFile,
}
}
function convertAgent(agent: ClaudeAgent, options: ClaudeToQwenOptions): QwenAgentFile {
const frontmatter: Record<string, unknown> = {
name: agent.name,
description: agent.description,
}
if (agent.model && agent.model !== "inherit") {
frontmatter.model = normalizeModel(agent.model)
}
if (options.inferTemperature) {
const temperature = inferTemperature(agent)
if (temperature !== undefined) {
frontmatter.temperature = temperature
}
}
// Qwen supports both YAML and Markdown for agents
// Using YAML format for structured config
const content = formatFrontmatter(frontmatter, rewriteQwenPaths(agent.body))
return {
name: agent.name,
content,
format: "yaml",
}
}
function convertCommands(commands: ClaudeCommand[]): QwenCommandFile[] {
const files: QwenCommandFile[] = []
for (const command of commands) {
if (command.disableModelInvocation) continue
const frontmatter: Record<string, unknown> = {
description: command.description,
}
if (command.model && command.model !== "inherit") {
frontmatter.model = normalizeModel(command.model)
}
if (command.allowedTools && command.allowedTools.length > 0) {
frontmatter.allowedTools = command.allowedTools
}
const content = formatFrontmatter(frontmatter, rewriteQwenPaths(command.body))
files.push({ name: command.name, content })
}
return files
}
function convertMcp(servers: Record<string, ClaudeMcpServer>): Record<string, QwenMcpServer> {
const result: Record<string, QwenMcpServer> = {}
for (const [name, server] of Object.entries(servers)) {
if (server.command) {
result[name] = {
command: server.command,
args: server.args,
env: server.env,
}
continue
}
if (server.url) {
// Qwen only supports stdio (command-based) MCP servers — skip remote servers
console.warn(
`Warning: Remote MCP server '${name}' (URL: ${server.url}) is not supported in Qwen format. Qwen only supports stdio MCP servers. Skipping.`,
)
}
}
return result
}
function extractSettings(mcpServers?: Record<string, ClaudeMcpServer>): QwenSetting[] {
const settings: QwenSetting[] = []
if (!mcpServers) return settings
for (const [name, server] of Object.entries(mcpServers)) {
if (server.env) {
for (const [envVar, value] of Object.entries(server.env)) {
// Only add settings for environment variables that look like placeholders
if (value.startsWith("${") || value.includes("YOUR_") || value.includes("XXX")) {
settings.push({
name: formatSettingName(envVar),
description: `Environment variable for ${name} MCP server`,
envVar,
sensitive: envVar.toLowerCase().includes("key") || envVar.toLowerCase().includes("token") || envVar.toLowerCase().includes("secret"),
})
}
}
}
}
return settings
}
function formatSettingName(envVar: string): string {
return envVar
.replace(/_/g, " ")
.toLowerCase()
.replace(/\b\w/g, (c) => c.toUpperCase())
}
function generateContextFile(plugin: ClaudePlugin): string {
const sections: string[] = []
// Plugin description
sections.push(`# ${plugin.manifest.name}`)
sections.push("")
if (plugin.manifest.description) {
sections.push(plugin.manifest.description)
sections.push("")
}
// Agents section
if (plugin.agents.length > 0) {
sections.push("## Agents")
sections.push("")
for (const agent of plugin.agents) {
sections.push(`- **${agent.name}**: ${agent.description || "No description"}`)
}
sections.push("")
}
// Commands section
if (plugin.commands.length > 0) {
sections.push("## Commands")
sections.push("")
for (const command of plugin.commands) {
if (!command.disableModelInvocation) {
sections.push(`- **/${command.name}**: ${command.description || "No description"}`)
}
}
sections.push("")
}
// Skills section
if (plugin.skills.length > 0) {
sections.push("## Skills")
sections.push("")
for (const skill of plugin.skills) {
sections.push(`- ${skill.name}`)
}
sections.push("")
}
return sections.join("\n")
}
function rewriteQwenPaths(body: string): string {
return body
.replace(/(?<=^|\s|["'`])~\/\.claude\//gm, "~/.qwen/")
.replace(/(?<=^|\s|["'`])\.claude\//gm, ".qwen/")
}
const CLAUDE_FAMILY_ALIASES: Record<string, string> = {
haiku: "claude-haiku",
sonnet: "claude-sonnet",
opus: "claude-opus",
}
function normalizeModel(model: string): string {
if (model.includes("/")) return model
if (CLAUDE_FAMILY_ALIASES[model]) {
const resolved = `anthropic/${CLAUDE_FAMILY_ALIASES[model]}`
console.warn(
`Warning: bare model alias "${model}" mapped to "${resolved}".`,
)
return resolved
}
if (/^claude-/.test(model)) return `anthropic/${model}`
if (/^(gpt-|o1-|o3-)/.test(model)) return `openai/${model}`
if (/^gemini-/.test(model)) return `google/${model}`
if (/^qwen-/.test(model)) return `qwen/${model}`
return `anthropic/${model}`
}
function inferTemperature(agent: ClaudeAgent): number | undefined {
const sample = `${agent.name} ${agent.description ?? ""}`.toLowerCase()
if (/(review|audit|security|sentinel|oracle|lint|verification|guardian)/.test(sample)) {
return 0.1
}
if (/(plan|planning|architecture|strategist|analysis|research)/.test(sample)) {
return 0.2
}
if (/(doc|readme|changelog|editor|writer)/.test(sample)) {
return 0.3
}
if (/(brainstorm|creative|ideate|design|concept)/.test(sample)) {
return 0.6
}
return undefined
}

View File

@@ -0,0 +1,205 @@
import { formatFrontmatter } from "../utils/frontmatter"
import { findServersWithPotentialSecrets } from "../utils/secrets"
import type { ClaudeAgent, ClaudeCommand, ClaudeMcpServer, ClaudePlugin } from "../types/claude"
import type { WindsurfBundle, WindsurfGeneratedSkill, WindsurfMcpConfig, WindsurfMcpServerEntry, WindsurfWorkflow } from "../types/windsurf"
import type { ClaudeToOpenCodeOptions } from "./claude-to-opencode"
export type ClaudeToWindsurfOptions = ClaudeToOpenCodeOptions
const WINDSURF_WORKFLOW_CHAR_LIMIT = 12_000
export function convertClaudeToWindsurf(
plugin: ClaudePlugin,
_options: ClaudeToWindsurfOptions,
): WindsurfBundle {
const knownAgentNames = plugin.agents.map((a) => normalizeName(a.name))
// Pass-through skills (collected first so agent skill names can deduplicate against them)
const skillDirs = plugin.skills.map((skill) => ({
name: skill.name,
sourceDir: skill.sourceDir,
}))
// Convert agents to skills (seed usedNames with pass-through skill names)
const usedSkillNames = new Set<string>(skillDirs.map((s) => s.name))
const agentSkills = plugin.agents.map((agent) =>
convertAgentToSkill(agent, knownAgentNames, usedSkillNames),
)
// Convert commands to workflows
const usedCommandNames = new Set<string>()
const commandWorkflows = plugin.commands.map((command) =>
convertCommandToWorkflow(command, knownAgentNames, usedCommandNames),
)
// Build MCP config
const mcpConfig = buildMcpConfig(plugin.mcpServers)
// Warn about hooks
if (plugin.hooks && Object.keys(plugin.hooks.hooks).length > 0) {
console.warn(
"Warning: Windsurf has no hooks equivalent. Hooks were skipped during conversion.",
)
}
return { agentSkills, commandWorkflows, skillDirs, mcpConfig }
}
function convertAgentToSkill(
agent: ClaudeAgent,
knownAgentNames: string[],
usedNames: Set<string>,
): WindsurfGeneratedSkill {
const name = uniqueName(normalizeName(agent.name), usedNames)
const description = sanitizeDescription(
agent.description ?? `Converted from Claude agent ${agent.name}`,
)
let body = transformContentForWindsurf(agent.body.trim(), knownAgentNames)
if (agent.capabilities && agent.capabilities.length > 0) {
const capabilities = agent.capabilities.map((c) => `- ${c}`).join("\n")
body = `## Capabilities\n${capabilities}\n\n${body}`.trim()
}
if (body.length === 0) {
body = `Instructions converted from the ${agent.name} agent.`
}
const content = formatFrontmatter({ name, description }, `# ${name}\n\n${body}`) + "\n"
return { name, content }
}
function convertCommandToWorkflow(
command: ClaudeCommand,
knownAgentNames: string[],
usedNames: Set<string>,
): WindsurfWorkflow {
const name = uniqueName(normalizeName(command.name), usedNames)
const description = sanitizeDescription(
command.description ?? `Converted from Claude command ${command.name}`,
)
let body = transformContentForWindsurf(command.body.trim(), knownAgentNames)
if (command.argumentHint) {
body = `> Arguments: ${command.argumentHint}\n\n${body}`
}
if (body.length === 0) {
body = `Instructions converted from the ${command.name} command.`
}
const frontmatter: Record<string, unknown> = { description }
const fullContent = formatFrontmatter(frontmatter, `# ${name}\n\n${body}`)
if (fullContent.length > WINDSURF_WORKFLOW_CHAR_LIMIT) {
console.warn(
`Warning: Workflow "${name}" is ${fullContent.length} characters (limit: ${WINDSURF_WORKFLOW_CHAR_LIMIT}). It may be truncated by Windsurf.`,
)
}
return { name, description, body }
}
/**
* Transform Claude Code content to Windsurf-compatible content.
*
* 1. Path rewriting: .claude/ -> .windsurf/, ~/.claude/ -> ~/.codeium/windsurf/
* 2. Slash command refs: /workflows:plan -> /workflows-plan (Windsurf invokes workflows as /{name})
* 3. @agent-name refs: kept as @agent-name (already Windsurf skill invocation syntax)
* 4. Task agent calls: Task agent-name(args) -> Use the @agent-name skill: args
*/
export function transformContentForWindsurf(body: string, knownAgentNames: string[] = []): string {
let result = body
// 1. Rewrite paths
result = result.replace(/(?<=^|\s|["'`])~\/\.claude\//gm, "~/.codeium/windsurf/")
result = result.replace(/(?<=^|\s|["'`])\.claude\//gm, ".windsurf/")
// 2. Slash command refs: /workflows:plan -> /workflows-plan (Windsurf invokes as /{name})
result = result.replace(/(?<=^|\s)`?\/([a-zA-Z][a-zA-Z0-9_:-]*)`?/gm, (_match, cmdName: string) => {
const workflowName = normalizeName(cmdName)
return `/${workflowName}`
})
// 3. @agent-name references: no transformation needed.
// In Windsurf, @skill-name is the native invocation syntax for skills.
// Since agents are now mapped to skills, @agent-name already works correctly.
// 4. Transform Task agent calls to skill references
const taskPattern = /^(\s*-?\s*)Task\s+([a-z][a-z0-9-]*)\(([^)]+)\)/gm
result = result.replace(taskPattern, (_match, prefix: string, agentName: string, args: string) => {
return `${prefix}Use the @${normalizeName(agentName)} skill: ${args.trim()}`
})
return result
}
function buildMcpConfig(servers?: Record<string, ClaudeMcpServer>): WindsurfMcpConfig | null {
if (!servers || Object.keys(servers).length === 0) return null
const result: Record<string, WindsurfMcpServerEntry> = {}
for (const [name, server] of Object.entries(servers)) {
if (server.command) {
// stdio transport
const entry: WindsurfMcpServerEntry = { command: server.command }
if (server.args?.length) entry.args = server.args
if (server.env && Object.keys(server.env).length > 0) entry.env = server.env
result[name] = entry
} else if (server.url) {
// HTTP/SSE transport
const entry: WindsurfMcpServerEntry = { serverUrl: server.url }
if (server.headers && Object.keys(server.headers).length > 0) entry.headers = server.headers
if (server.env && Object.keys(server.env).length > 0) entry.env = server.env
result[name] = entry
} else {
console.warn(`Warning: MCP server "${name}" has no command or URL. Skipping.`)
continue
}
}
if (Object.keys(result).length === 0) return null
// Warn about secrets (don't redact — they're needed for the config to work)
const flagged = findServersWithPotentialSecrets(result)
if (flagged.length > 0) {
console.warn(
`Warning: MCP servers contain env vars that may include secrets: ${flagged.join(", ")}.\n` +
" These will be written to mcp_config.json. Review before sharing the config file.",
)
}
return { mcpServers: result }
}
export function normalizeName(value: string): string {
const trimmed = value.trim()
if (!trimmed) return "item"
let normalized = trimmed
.toLowerCase()
.replace(/[\\/]+/g, "-")
.replace(/[:\s]+/g, "-")
.replace(/[^a-z0-9_-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
if (normalized.length === 0 || !/^[a-z]/.test(normalized)) {
return "item"
}
return normalized
}
function sanitizeDescription(value: string): string {
return value.replace(/\s+/g, " ").trim()
}
function uniqueName(base: string, used: Set<string>): string {
if (!used.has(base)) {
used.add(base)
return base
}
let index = 2
while (used.has(`${base}-${index}`)) {
index += 1
}
const name = `${base}-${index}`
used.add(name)
return name
}

View File

@@ -4,19 +4,21 @@ import type { ClaudeHomeConfig } from "../parsers/claude-home"
import type { ClaudeMcpServer } from "../types/claude"
import { forceSymlink, isValidSkillName } from "../utils/symlink"
type CursorMcpServer = {
type CopilotMcpServer = {
type: string
command?: string
args?: string[]
url?: string
tools: string[]
env?: Record<string, string>
headers?: Record<string, string>
}
type CursorMcpConfig = {
mcpServers: Record<string, CursorMcpServer>
type CopilotMcpConfig = {
mcpServers: Record<string, CopilotMcpServer>
}
export async function syncToCursor(
export async function syncToCopilot(
config: ClaudeHomeConfig,
outputRoot: string,
): Promise<void> {
@@ -33,10 +35,10 @@ export async function syncToCursor(
}
if (Object.keys(config.mcpServers).length > 0) {
const mcpPath = path.join(outputRoot, "mcp.json")
const mcpPath = path.join(outputRoot, "copilot-mcp-config.json")
const existing = await readJsonSafe(mcpPath)
const converted = convertMcpForCursor(config.mcpServers)
const merged: CursorMcpConfig = {
const converted = convertMcpForCopilot(config.mcpServers)
const merged: CopilotMcpConfig = {
mcpServers: {
...(existing.mcpServers ?? {}),
...converted,
@@ -46,10 +48,10 @@ export async function syncToCursor(
}
}
async function readJsonSafe(filePath: string): Promise<Partial<CursorMcpConfig>> {
async function readJsonSafe(filePath: string): Promise<Partial<CopilotMcpConfig>> {
try {
const content = await fs.readFile(filePath, "utf-8")
return JSON.parse(content) as Partial<CursorMcpConfig>
return JSON.parse(content) as Partial<CopilotMcpConfig>
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
return {}
@@ -58,21 +60,41 @@ async function readJsonSafe(filePath: string): Promise<Partial<CursorMcpConfig>>
}
}
function convertMcpForCursor(
function convertMcpForCopilot(
servers: Record<string, ClaudeMcpServer>,
): Record<string, CursorMcpServer> {
const result: Record<string, CursorMcpServer> = {}
): Record<string, CopilotMcpServer> {
const result: Record<string, CopilotMcpServer> = {}
for (const [name, server] of Object.entries(servers)) {
const entry: CursorMcpServer = {}
const entry: CopilotMcpServer = {
type: server.command ? "local" : "sse",
tools: ["*"],
}
if (server.command) {
entry.command = server.command
if (server.args && server.args.length > 0) entry.args = server.args
if (server.env && Object.keys(server.env).length > 0) entry.env = server.env
} else if (server.url) {
entry.url = server.url
if (server.headers && Object.keys(server.headers).length > 0) entry.headers = server.headers
}
if (server.env && Object.keys(server.env).length > 0) {
entry.env = prefixEnvVars(server.env)
}
result[name] = entry
}
return result
}
function prefixEnvVars(env: Record<string, string>): Record<string, string> {
const result: Record<string, string> = {}
for (const [key, value] of Object.entries(env)) {
if (key.startsWith("COPILOT_MCP_")) {
result[key] = value
} else {
result[`COPILOT_MCP_${key}`] = value
}
}
return result
}

48
src/targets/copilot.ts Normal file
View File

@@ -0,0 +1,48 @@
import path from "path"
import { backupFile, copyDir, ensureDir, writeJson, writeText } from "../utils/files"
import type { CopilotBundle } from "../types/copilot"
export async function writeCopilotBundle(outputRoot: string, bundle: CopilotBundle): Promise<void> {
const paths = resolveCopilotPaths(outputRoot)
await ensureDir(paths.githubDir)
if (bundle.agents.length > 0) {
const agentsDir = path.join(paths.githubDir, "agents")
for (const agent of bundle.agents) {
await writeText(path.join(agentsDir, `${agent.name}.agent.md`), agent.content + "\n")
}
}
if (bundle.generatedSkills.length > 0) {
const skillsDir = path.join(paths.githubDir, "skills")
for (const skill of bundle.generatedSkills) {
await writeText(path.join(skillsDir, skill.name, "SKILL.md"), skill.content + "\n")
}
}
if (bundle.skillDirs.length > 0) {
const skillsDir = path.join(paths.githubDir, "skills")
for (const skill of bundle.skillDirs) {
await copyDir(skill.sourceDir, path.join(skillsDir, skill.name))
}
}
if (bundle.mcpConfig && Object.keys(bundle.mcpConfig).length > 0) {
const mcpPath = path.join(paths.githubDir, "copilot-mcp-config.json")
const backupPath = await backupFile(mcpPath)
if (backupPath) {
console.log(`Backed up existing copilot-mcp-config.json to ${backupPath}`)
}
await writeJson(mcpPath, { mcpServers: bundle.mcpConfig })
}
}
function resolveCopilotPaths(outputRoot: string) {
const base = path.basename(outputRoot)
// If already pointing at .github, write directly into it
if (base === ".github") {
return { githubDir: outputRoot }
}
// Otherwise nest under .github
return { githubDir: path.join(outputRoot, ".github") }
}

View File

@@ -1,48 +0,0 @@
import path from "path"
import { backupFile, copyDir, ensureDir, writeJson, writeText } from "../utils/files"
import type { CursorBundle } from "../types/cursor"
export async function writeCursorBundle(outputRoot: string, bundle: CursorBundle): Promise<void> {
const paths = resolveCursorPaths(outputRoot)
await ensureDir(paths.cursorDir)
if (bundle.rules.length > 0) {
const rulesDir = path.join(paths.cursorDir, "rules")
for (const rule of bundle.rules) {
await writeText(path.join(rulesDir, `${rule.name}.mdc`), rule.content + "\n")
}
}
if (bundle.commands.length > 0) {
const commandsDir = path.join(paths.cursorDir, "commands")
for (const command of bundle.commands) {
await writeText(path.join(commandsDir, `${command.name}.md`), command.content + "\n")
}
}
if (bundle.skillDirs.length > 0) {
const skillsDir = path.join(paths.cursorDir, "skills")
for (const skill of bundle.skillDirs) {
await copyDir(skill.sourceDir, path.join(skillsDir, skill.name))
}
}
if (bundle.mcpServers && Object.keys(bundle.mcpServers).length > 0) {
const mcpPath = path.join(paths.cursorDir, "mcp.json")
const backupPath = await backupFile(mcpPath)
if (backupPath) {
console.log(`Backed up existing mcp.json to ${backupPath}`)
}
await writeJson(mcpPath, { mcpServers: bundle.mcpServers })
}
}
function resolveCursorPaths(outputRoot: string) {
const base = path.basename(outputRoot)
// If already pointing at .cursor, write directly into it
if (base === ".cursor") {
return { cursorDir: outputRoot }
}
// Otherwise nest under .cursor
return { cursorDir: path.join(outputRoot, ".cursor") }
}

View File

@@ -2,27 +2,69 @@ import type { ClaudePlugin } from "../types/claude"
import type { OpenCodeBundle } from "../types/opencode"
import type { CodexBundle } from "../types/codex"
import type { DroidBundle } from "../types/droid"
import type { CursorBundle } from "../types/cursor"
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 { WindsurfBundle } from "../types/windsurf"
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"
import { convertClaudeToDroid } from "../converters/claude-to-droid"
import { convertClaudeToCursor } from "../converters/claude-to-cursor"
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 { convertClaudeToWindsurf } from "../converters/claude-to-windsurf"
import { convertClaudeToOpenClaw } from "../converters/claude-to-openclaw"
import { convertClaudeToQwen } from "../converters/claude-to-qwen"
import { writeOpenCodeBundle } from "./opencode"
import { writeCodexBundle } from "./codex"
import { writeDroidBundle } from "./droid"
import { writeCursorBundle } from "./cursor"
import { writePiBundle } from "./pi"
import { writeCopilotBundle } from "./copilot"
import { writeGeminiBundle } from "./gemini"
import { writeKiroBundle } from "./kiro"
import { writeWindsurfBundle } from "./windsurf"
import { writeOpenClawBundle } from "./openclaw"
import { writeQwenBundle } from "./qwen"
export type TargetScope = "global" | "workspace"
export function isTargetScope(value: string): value is TargetScope {
return value === "global" || value === "workspace"
}
/**
* Validate a --scope flag against a target's supported scopes.
* Returns the resolved scope (explicit or default) or throws on invalid input.
*/
export function validateScope(
targetName: string,
target: TargetHandler,
scopeArg: string | undefined,
): TargetScope | undefined {
if (scopeArg === undefined) return target.defaultScope
if (!target.supportedScopes) {
throw new Error(`Target "${targetName}" does not support the --scope flag.`)
}
if (!isTargetScope(scopeArg) || !target.supportedScopes.includes(scopeArg)) {
throw new Error(`Target "${targetName}" does not support --scope ${scopeArg}. Supported: ${target.supportedScopes.join(", ")}`)
}
return scopeArg
}
export type TargetHandler<TBundle = unknown> = {
name: string
implemented: boolean
/** Default scope when --scope is not provided. Only meaningful when supportedScopes is defined. */
defaultScope?: TargetScope
/** Valid scope values. If absent, the --scope flag is rejected for this target. */
supportedScopes?: TargetScope[]
convert: (plugin: ClaudePlugin, options: ClaudeToOpenCodeOptions) => TBundle | null
write: (outputRoot: string, bundle: TBundle) => Promise<void>
write: (outputRoot: string, bundle: TBundle, scope?: TargetScope) => Promise<void>
}
export const targets: Record<string, TargetHandler> = {
@@ -44,22 +86,48 @@ export const targets: Record<string, TargetHandler> = {
convert: convertClaudeToDroid as TargetHandler<DroidBundle>["convert"],
write: writeDroidBundle as TargetHandler<DroidBundle>["write"],
},
cursor: {
name: "cursor",
implemented: true,
convert: convertClaudeToCursor as TargetHandler<CursorBundle>["convert"],
write: writeCursorBundle as TargetHandler<CursorBundle>["write"],
},
pi: {
name: "pi",
implemented: true,
convert: convertClaudeToPi as TargetHandler<PiBundle>["convert"],
write: writePiBundle as TargetHandler<PiBundle>["write"],
},
copilot: {
name: "copilot",
implemented: true,
convert: convertClaudeToCopilot as TargetHandler<CopilotBundle>["convert"],
write: writeCopilotBundle as TargetHandler<CopilotBundle>["write"],
},
gemini: {
name: "gemini",
implemented: true,
convert: convertClaudeToGemini as TargetHandler<GeminiBundle>["convert"],
write: writeGeminiBundle as TargetHandler<GeminiBundle>["write"],
},
kiro: {
name: "kiro",
implemented: true,
convert: convertClaudeToKiro as TargetHandler<KiroBundle>["convert"],
write: writeKiroBundle as TargetHandler<KiroBundle>["write"],
},
windsurf: {
name: "windsurf",
implemented: true,
defaultScope: "global",
supportedScopes: ["global", "workspace"],
convert: convertClaudeToWindsurf as TargetHandler<WindsurfBundle>["convert"],
write: writeWindsurfBundle as TargetHandler<WindsurfBundle>["write"],
},
openclaw: {
name: "openclaw",
implemented: true,
convert: convertClaudeToOpenClaw as TargetHandler<OpenClawBundle>["convert"],
write: writeOpenClawBundle as TargetHandler<OpenClawBundle>["write"],
},
qwen: {
name: "qwen",
implemented: true,
convert: convertClaudeToQwen as TargetHandler<QwenBundle>["convert"],
write: writeQwenBundle as TargetHandler<QwenBundle>["write"],
},
}

122
src/targets/kiro.ts Normal file
View File

@@ -0,0 +1,122 @@
import path from "path"
import { backupFile, copyDir, ensureDir, pathExists, readJson, writeJson, writeText } from "../utils/files"
import type { KiroBundle } from "../types/kiro"
export async function writeKiroBundle(outputRoot: string, bundle: KiroBundle): Promise<void> {
const paths = resolveKiroPaths(outputRoot)
await ensureDir(paths.kiroDir)
// Write agents
if (bundle.agents.length > 0) {
for (const agent of bundle.agents) {
// Validate name doesn't escape agents directory
validatePathSafe(agent.name, "agent")
// Write agent JSON config
await writeJson(
path.join(paths.agentsDir, `${agent.name}.json`),
agent.config,
)
// Write agent prompt file
await writeText(
path.join(paths.agentsDir, "prompts", `${agent.name}.md`),
agent.promptContent + "\n",
)
}
}
// Write generated skills (from commands)
if (bundle.generatedSkills.length > 0) {
for (const skill of bundle.generatedSkills) {
validatePathSafe(skill.name, "skill")
await writeText(
path.join(paths.skillsDir, skill.name, "SKILL.md"),
skill.content + "\n",
)
}
}
// Copy skill directories (pass-through)
if (bundle.skillDirs.length > 0) {
for (const skill of bundle.skillDirs) {
validatePathSafe(skill.name, "skill directory")
const destDir = path.join(paths.skillsDir, skill.name)
// Validate destination doesn't escape skills directory
const resolvedDest = path.resolve(destDir)
if (!resolvedDest.startsWith(path.resolve(paths.skillsDir))) {
console.warn(`Warning: Skill name "${skill.name}" escapes .kiro/skills/. Skipping.`)
continue
}
await copyDir(skill.sourceDir, destDir)
}
}
// Write steering files
if (bundle.steeringFiles.length > 0) {
for (const file of bundle.steeringFiles) {
validatePathSafe(file.name, "steering file")
await writeText(
path.join(paths.steeringDir, `${file.name}.md`),
file.content + "\n",
)
}
}
// Write MCP servers to mcp.json
if (Object.keys(bundle.mcpServers).length > 0) {
const mcpPath = path.join(paths.settingsDir, "mcp.json")
const backupPath = await backupFile(mcpPath)
if (backupPath) {
console.log(`Backed up existing mcp.json to ${backupPath}`)
}
// Merge with existing mcp.json if present
let existingConfig: Record<string, unknown> = {}
if (await pathExists(mcpPath)) {
try {
existingConfig = await readJson<Record<string, unknown>>(mcpPath)
} catch {
console.warn("Warning: existing mcp.json could not be parsed and will be replaced.")
}
}
const existingServers =
existingConfig.mcpServers && typeof existingConfig.mcpServers === "object"
? (existingConfig.mcpServers as Record<string, unknown>)
: {}
const merged = { ...existingConfig, mcpServers: { ...existingServers, ...bundle.mcpServers } }
await writeJson(mcpPath, merged)
}
}
function resolveKiroPaths(outputRoot: string) {
const base = path.basename(outputRoot)
// If already pointing at .kiro, write directly into it
if (base === ".kiro") {
return {
kiroDir: outputRoot,
agentsDir: path.join(outputRoot, "agents"),
skillsDir: path.join(outputRoot, "skills"),
steeringDir: path.join(outputRoot, "steering"),
settingsDir: path.join(outputRoot, "settings"),
}
}
// Otherwise nest under .kiro
const kiroDir = path.join(outputRoot, ".kiro")
return {
kiroDir,
agentsDir: path.join(kiroDir, "agents"),
skillsDir: path.join(kiroDir, "skills"),
steeringDir: path.join(kiroDir, "steering"),
settingsDir: path.join(kiroDir, "settings"),
}
}
function validatePathSafe(name: string, label: string): void {
if (name.includes("..") || name.includes("/") || name.includes("\\")) {
throw new Error(`${label} name contains unsafe path characters: ${name}`)
}
}

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

View File

@@ -1,31 +1,93 @@
import path from "path"
import { backupFile, copyDir, ensureDir, writeJson, writeText } from "../utils/files"
import type { OpenCodeBundle } from "../types/opencode"
import { backupFile, copyDir, ensureDir, pathExists, readJson, writeJson, writeText } from "../utils/files"
import type { OpenCodeBundle, OpenCodeConfig } from "../types/opencode"
// Merges plugin config into existing opencode.json. User keys win on conflict. See ADR-002.
async function mergeOpenCodeConfig(
configPath: string,
incoming: OpenCodeConfig,
): Promise<OpenCodeConfig> {
// If no existing config, write plugin config as-is
if (!(await pathExists(configPath))) return incoming
let existing: OpenCodeConfig
try {
existing = await readJson<OpenCodeConfig>(configPath)
} catch {
// Safety first per AGENTS.md -- do not destroy user data even if their config is malformed.
// Warn and fall back to plugin-only config rather than crashing.
console.warn(
`Warning: existing ${configPath} is not valid JSON. Writing plugin config without merging.`
)
return incoming
}
// User config wins on conflict -- see ADR-002
// MCP servers: add plugin entry, skip keys already in user config.
const mergedMcp = {
...(incoming.mcp ?? {}),
...(existing.mcp ?? {}), // existing takes precedence (overwrites same-named plugin entry)
}
// Permission: add plugin entry, skip keys already in user config.
const mergedPermission = incoming.permission
? {
...(incoming.permission),
...(existing.permission ?? {}), // existing takes precedence
}
: existing.permission
// Tools: same pattern
const mergedTools = incoming.tools
? {
...(incoming.tools),
...(existing.tools ?? {}),
}
: existing.tools
return {
...existing, // all user keys preserved
$schema: incoming.$schema ?? existing.$schema,
mcp: Object.keys(mergedMcp).length > 0 ? mergedMcp : undefined,
permission: mergedPermission,
tools: mergedTools,
}
}
export async function writeOpenCodeBundle(outputRoot: string, bundle: OpenCodeBundle): Promise<void> {
const paths = resolveOpenCodePaths(outputRoot)
await ensureDir(paths.root)
const openCodePaths = resolveOpenCodePaths(outputRoot)
await ensureDir(openCodePaths.root)
const backupPath = await backupFile(paths.configPath)
const backupPath = await backupFile(openCodePaths.configPath)
if (backupPath) {
console.log(`Backed up existing config to ${backupPath}`)
}
await writeJson(paths.configPath, bundle.config)
const merged = await mergeOpenCodeConfig(openCodePaths.configPath, bundle.config)
await writeJson(openCodePaths.configPath, merged)
const agentsDir = paths.agentsDir
const agentsDir = openCodePaths.agentsDir
for (const agent of bundle.agents) {
await writeText(path.join(agentsDir, `${agent.name}.md`), agent.content + "\n")
}
for (const commandFile of bundle.commandFiles) {
const dest = path.join(openCodePaths.commandDir, `${commandFile.name}.md`)
const cmdBackupPath = await backupFile(dest)
if (cmdBackupPath) {
console.log(`Backed up existing command file to ${cmdBackupPath}`)
}
await writeText(dest, commandFile.content + "\n")
}
if (bundle.plugins.length > 0) {
const pluginsDir = paths.pluginsDir
const pluginsDir = openCodePaths.pluginsDir
for (const plugin of bundle.plugins) {
await writeText(path.join(pluginsDir, plugin.name), plugin.content + "\n")
}
}
if (bundle.skillDirs.length > 0) {
const skillsRoot = paths.skillsDir
const skillsRoot = openCodePaths.skillsDir
for (const skill of bundle.skillDirs) {
await copyDir(skill.sourceDir, path.join(skillsRoot, skill.name))
}
@@ -43,6 +105,8 @@ function resolveOpenCodePaths(outputRoot: string) {
agentsDir: path.join(outputRoot, "agents"),
pluginsDir: path.join(outputRoot, "plugins"),
skillsDir: path.join(outputRoot, "skills"),
// .md command files; alternative to the command key in opencode.json
commandDir: path.join(outputRoot, "commands"),
}
}
@@ -53,5 +117,7 @@ function resolveOpenCodePaths(outputRoot: string) {
agentsDir: path.join(outputRoot, ".opencode", "agents"),
pluginsDir: path.join(outputRoot, ".opencode", "plugins"),
skillsDir: path.join(outputRoot, ".opencode", "skills"),
// .md command files; alternative to the command key in opencode.json
commandDir: path.join(outputRoot, ".opencode", "commands"),
}
}
}

64
src/targets/qwen.ts Normal file
View File

@@ -0,0 +1,64 @@
import path from "path"
import { backupFile, copyDir, ensureDir, writeJson, writeText } from "../utils/files"
import type { QwenBundle, QwenExtensionConfig } from "../types/qwen"
export async function writeQwenBundle(outputRoot: string, bundle: QwenBundle): Promise<void> {
const qwenPaths = resolveQwenPaths(outputRoot)
await ensureDir(qwenPaths.root)
// Write qwen-extension.json config
const configPath = qwenPaths.configPath
const backupPath = await backupFile(configPath)
if (backupPath) {
console.log(`Backed up existing config to ${backupPath}`)
}
await writeJson(configPath, bundle.config)
// Write context file (QWEN.md)
if (bundle.contextFile) {
await writeText(qwenPaths.contextPath, bundle.contextFile + "\n")
}
// Write agents
const agentsDir = qwenPaths.agentsDir
await ensureDir(agentsDir)
for (const agent of bundle.agents) {
const ext = agent.format === "yaml" ? "yaml" : "md"
await writeText(path.join(agentsDir, `${agent.name}.${ext}`), agent.content + "\n")
}
// Write commands
const commandsDir = qwenPaths.commandsDir
await ensureDir(commandsDir)
for (const commandFile of bundle.commandFiles) {
// Support nested commands with colon separator
const parts = commandFile.name.split(":")
if (parts.length > 1) {
const nestedDir = path.join(commandsDir, ...parts.slice(0, -1))
await ensureDir(nestedDir)
await writeText(path.join(nestedDir, `${parts[parts.length - 1]}.md`), commandFile.content + "\n")
} else {
await writeText(path.join(commandsDir, `${commandFile.name}.md`), commandFile.content + "\n")
}
}
// Copy skills
if (bundle.skillDirs.length > 0) {
const skillsRoot = qwenPaths.skillsDir
await ensureDir(skillsRoot)
for (const skill of bundle.skillDirs) {
await copyDir(skill.sourceDir, path.join(skillsRoot, skill.name))
}
}
}
function resolveQwenPaths(outputRoot: string) {
return {
root: outputRoot,
configPath: path.join(outputRoot, "qwen-extension.json"),
contextPath: path.join(outputRoot, "QWEN.md"),
agentsDir: path.join(outputRoot, "agents"),
commandsDir: path.join(outputRoot, "commands"),
skillsDir: path.join(outputRoot, "skills"),
}
}

104
src/targets/windsurf.ts Normal file
View File

@@ -0,0 +1,104 @@
import path from "path"
import { backupFile, copyDir, ensureDir, pathExists, readJson, writeJsonSecure, writeText } from "../utils/files"
import { formatFrontmatter } from "../utils/frontmatter"
import type { WindsurfBundle } from "../types/windsurf"
import type { TargetScope } from "./index"
/**
* Write a WindsurfBundle directly into outputRoot.
*
* Unlike other target writers, this writer expects outputRoot to be the final
* resolved directory — the CLI handles scope-based nesting (global vs workspace).
*/
export async function writeWindsurfBundle(outputRoot: string, bundle: WindsurfBundle, scope?: TargetScope): Promise<void> {
await ensureDir(outputRoot)
// Write agent skills (before pass-through copies so pass-through takes precedence on collision)
if (bundle.agentSkills.length > 0) {
const skillsDir = path.join(outputRoot, "skills")
await ensureDir(skillsDir)
for (const skill of bundle.agentSkills) {
validatePathSafe(skill.name, "agent skill")
const destDir = path.join(skillsDir, skill.name)
const resolvedDest = path.resolve(destDir)
if (!resolvedDest.startsWith(path.resolve(skillsDir))) {
console.warn(`Warning: Agent skill name "${skill.name}" escapes skills/. Skipping.`)
continue
}
await ensureDir(destDir)
await writeText(path.join(destDir, "SKILL.md"), skill.content)
}
}
// Write command workflows (flat in global_workflows/ for global scope, workflows/ for workspace)
if (bundle.commandWorkflows.length > 0) {
const workflowsDirName = scope === "global" ? "global_workflows" : "workflows"
const workflowsDir = path.join(outputRoot, workflowsDirName)
await ensureDir(workflowsDir)
for (const workflow of bundle.commandWorkflows) {
validatePathSafe(workflow.name, "command workflow")
const content = formatWorkflowContent(workflow.name, workflow.description, workflow.body)
await writeText(path.join(workflowsDir, `${workflow.name}.md`), content)
}
}
// Copy pass-through skill directories (after generated skills so copies overwrite on collision)
if (bundle.skillDirs.length > 0) {
const skillsDir = path.join(outputRoot, "skills")
await ensureDir(skillsDir)
for (const skill of bundle.skillDirs) {
validatePathSafe(skill.name, "skill directory")
const destDir = path.join(skillsDir, skill.name)
const resolvedDest = path.resolve(destDir)
if (!resolvedDest.startsWith(path.resolve(skillsDir))) {
console.warn(`Warning: Skill name "${skill.name}" escapes skills/. Skipping.`)
continue
}
await copyDir(skill.sourceDir, destDir)
}
}
// Merge MCP config
if (bundle.mcpConfig) {
const mcpPath = path.join(outputRoot, "mcp_config.json")
const backupPath = await backupFile(mcpPath)
if (backupPath) {
console.log(`Backed up existing mcp_config.json to ${backupPath}`)
}
let existingConfig: Record<string, unknown> = {}
if (await pathExists(mcpPath)) {
try {
const parsed = await readJson<unknown>(mcpPath)
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
existingConfig = parsed as Record<string, unknown>
}
} catch {
console.warn("Warning: existing mcp_config.json could not be parsed and will be replaced.")
}
}
const existingServers =
existingConfig.mcpServers &&
typeof existingConfig.mcpServers === "object" &&
!Array.isArray(existingConfig.mcpServers)
? (existingConfig.mcpServers as Record<string, unknown>)
: {}
const merged = { ...existingConfig, mcpServers: { ...existingServers, ...bundle.mcpConfig.mcpServers } }
await writeJsonSecure(mcpPath, merged)
}
}
function validatePathSafe(name: string, label: string): void {
if (name.includes("..") || name.includes("/") || name.includes("\\")) {
throw new Error(`${label} name contains unsafe path characters: ${name}`)
}
}
function formatWorkflowContent(name: string, description: string, body: string): string {
return formatFrontmatter({ description }, `# ${name}\n\n${body}`) + "\n"
}

31
src/types/copilot.ts Normal file
View File

@@ -0,0 +1,31 @@
export type CopilotAgent = {
name: string
content: string
}
export type CopilotGeneratedSkill = {
name: string
content: string
}
export type CopilotSkillDir = {
name: string
sourceDir: string
}
export type CopilotMcpServer = {
type: string
command?: string
args?: string[]
url?: string
tools: string[]
env?: Record<string, string>
headers?: Record<string, string>
}
export type CopilotBundle = {
agents: CopilotAgent[]
generatedSkills: CopilotGeneratedSkill[]
skillDirs: CopilotSkillDir[]
mcpConfig?: Record<string, CopilotMcpServer>
}

View File

@@ -1,29 +0,0 @@
export type CursorRule = {
name: string
content: string
}
export type CursorCommand = {
name: string
content: string
}
export type CursorSkillDir = {
name: string
sourceDir: string
}
export type CursorMcpServer = {
command?: string
args?: string[]
env?: Record<string, string>
url?: string
headers?: Record<string, string>
}
export type CursorBundle = {
rules: CursorRule[]
commands: CursorCommand[]
skillDirs: CursorSkillDir[]
mcpServers?: Record<string, CursorMcpServer>
}

44
src/types/kiro.ts Normal file
View File

@@ -0,0 +1,44 @@
export type KiroAgent = {
name: string
config: KiroAgentConfig
promptContent: string
}
export type KiroAgentConfig = {
name: string
description: string
prompt: `file://${string}`
tools: ["*"]
resources: string[]
includeMcpJson: true
welcomeMessage?: string
}
export type KiroSkill = {
name: string
content: string // Full SKILL.md with YAML frontmatter
}
export type KiroSkillDir = {
name: string
sourceDir: string
}
export type KiroSteeringFile = {
name: string
content: string
}
export type KiroMcpServer = {
command: string
args?: string[]
env?: Record<string, string>
}
export type KiroBundle = {
agents: KiroAgent[]
generatedSkills: KiroSkill[]
skillDirs: KiroSkillDir[]
steeringFiles: KiroSteeringFile[]
mcpServers: Record<string, KiroMcpServer>
}

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

@@ -7,7 +7,6 @@ export type OpenCodeConfig = {
tools?: Record<string, boolean>
permission?: Record<string, OpenCodePermission | Record<string, OpenCodePermission>>
agent?: Record<string, OpenCodeAgentConfig>
command?: Record<string, OpenCodeCommandConfig>
mcp?: Record<string, OpenCodeMcpServer>
}
@@ -20,13 +19,6 @@ export type OpenCodeAgentConfig = {
permission?: Record<string, OpenCodePermission>
}
export type OpenCodeCommandConfig = {
description?: string
model?: string
agent?: string
template: string
}
export type OpenCodeMcpServer = {
type: "local" | "remote"
command?: string[]
@@ -46,9 +38,16 @@ export type OpenCodePluginFile = {
content: string
}
export type OpenCodeCommandFile = {
name: string
content: string
}
export type OpenCodeBundle = {
config: OpenCodeConfig
agents: OpenCodeAgentFile[]
// Commands are written as individual .md files, not in opencode.json. See ADR-001.
commandFiles: OpenCodeCommandFile[]
plugins: OpenCodePluginFile[]
skillDirs: { sourceDir: string; name: string }[]
}

48
src/types/qwen.ts Normal file
View File

@@ -0,0 +1,48 @@
export type QwenExtensionConfig = {
name: string
version: string
mcpServers?: Record<string, QwenMcpServer>
contextFileName?: string
commands?: string
skills?: string
agents?: string
settings?: QwenSetting[]
}
export type QwenMcpServer = {
command?: string
args?: string[]
env?: Record<string, string>
cwd?: string
}
export type QwenSetting = {
name: string
description: string
envVar: string
sensitive?: boolean
}
export type QwenAgentFile = {
name: string
content: string
format: "yaml" | "markdown"
}
export type QwenSkillDir = {
sourceDir: string
name: string
}
export type QwenCommandFile = {
name: string
content: string
}
export type QwenBundle = {
config: QwenExtensionConfig
agents: QwenAgentFile[]
commandFiles: QwenCommandFile[]
skillDirs: QwenSkillDir[]
contextFile?: string
}

34
src/types/windsurf.ts Normal file
View File

@@ -0,0 +1,34 @@
export type WindsurfWorkflow = {
name: string
description: string
body: string
}
export type WindsurfGeneratedSkill = {
name: string
content: string
}
export type WindsurfSkillDir = {
name: string
sourceDir: string
}
export type WindsurfMcpServerEntry = {
command?: string
args?: string[]
env?: Record<string, string>
serverUrl?: string
headers?: Record<string, string>
}
export type WindsurfMcpConfig = {
mcpServers: Record<string, WindsurfMcpServerEntry>
}
export type WindsurfBundle = {
agentSkills: WindsurfGeneratedSkill[]
commandWorkflows: WindsurfWorkflow[]
skillDirs: WindsurfSkillDir[]
mcpConfig: WindsurfMcpConfig | null
}

View File

@@ -46,6 +46,13 @@ export async function writeJson(filePath: string, data: unknown): Promise<void>
await writeText(filePath, content + "\n")
}
/** Write JSON with restrictive permissions (0o600) for files containing secrets */
export async function writeJsonSecure(filePath: string, data: unknown): Promise<void> {
const content = JSON.stringify(data, null, 2)
await ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, content + "\n", { encoding: "utf8", mode: 0o600 })
}
export async function walkFiles(root: string): Promise<string[]> {
const entries = await fs.readdir(root, { withFileTypes: true })
const results: string[] = []

View File

@@ -58,7 +58,7 @@ function formatYamlValue(value: unknown): string {
if (raw.includes("\n")) {
return `|\n${raw.split("\n").map((line) => ` ${line}`).join("\n")}`
}
if (raw.includes(":") || raw.startsWith("[") || raw.startsWith("{")) {
if (raw.includes(":") || raw.startsWith("[") || raw.startsWith("{") || raw === "*") {
return JSON.stringify(raw)
}
return raw

View File

@@ -0,0 +1,50 @@
import os from "os"
import path from "path"
import type { TargetScope } from "../targets"
export function resolveTargetOutputRoot(options: {
targetName: string
outputRoot: string
codexHome: string
piHome: string
openclawHome?: string
qwenHome?: string
pluginName?: string
hasExplicitOutput: boolean
scope?: TargetScope
}): string {
const { targetName, outputRoot, codexHome, piHome, openclawHome, qwenHome, pluginName, hasExplicitOutput, scope } = options
if (targetName === "codex") return codexHome
if (targetName === "pi") return piHome
if (targetName === "droid") return path.join(os.homedir(), ".factory")
if (targetName === "cursor") {
const base = hasExplicitOutput ? outputRoot : process.cwd()
return path.join(base, ".cursor")
}
if (targetName === "gemini") {
const base = hasExplicitOutput ? outputRoot : process.cwd()
return path.join(base, ".gemini")
}
if (targetName === "copilot") {
const base = hasExplicitOutput ? outputRoot : process.cwd()
return path.join(base, ".github")
}
if (targetName === "kiro") {
const base = hasExplicitOutput ? outputRoot : process.cwd()
return path.join(base, ".kiro")
}
if (targetName === "windsurf") {
if (hasExplicitOutput) return outputRoot
if (scope === "global") return path.join(os.homedir(), ".codeium", "windsurf")
return path.join(process.cwd(), ".windsurf")
}
if (targetName === "openclaw") {
const home = openclawHome ?? path.join(os.homedir(), ".openclaw", "extensions")
return path.join(home, pluginName ?? "plugin")
}
if (targetName === "qwen") {
const home = qwenHome ?? path.join(os.homedir(), ".qwen", "extensions")
return path.join(home, pluginName ?? "plugin")
}
return outputRoot
}

24
src/utils/secrets.ts Normal file
View File

@@ -0,0 +1,24 @@
export const SENSITIVE_PATTERN = /key|token|secret|password|credential|api_key/i
/** Check if any MCP servers have env vars that might contain secrets */
export function hasPotentialSecrets(
servers: Record<string, { env?: Record<string, string> }>,
): boolean {
for (const server of Object.values(servers)) {
if (server.env) {
for (const key of Object.keys(server.env)) {
if (SENSITIVE_PATTERN.test(key)) return true
}
}
}
return false
}
/** Return names of MCP servers whose env vars may contain secrets */
export function findServersWithPotentialSecrets(
servers: Record<string, { env?: Record<string, string> }>,
): string[] {
return Object.entries(servers)
.filter(([, s]) => s.env && Object.keys(s.env).some((k) => SENSITIVE_PATTERN.test(k)))
.map(([name]) => name)
}