feat: Add GitHub Copilot converter target

Add Copilot as the 6th converter target, transforming Claude Code plugins
into Copilot's native format: custom agents (.agent.md), agent skills
(SKILL.md), and MCP server configuration JSON.

Component mapping:
- Agents → .github/agents/{name}.agent.md (with Copilot frontmatter)
- Commands → .github/skills/{name}/SKILL.md
- Skills → .github/skills/{name}/ (copied as-is)
- MCP servers → .github/copilot-mcp-config.json
- Hooks → skipped with warning

Also adds `compound sync copilot` support and fixes YAML quoting for
the `*` character in frontmatter serialization.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Brayan Jules
2026-02-15 00:14:40 -03:00
parent 134a994c08
commit 4f7c598f27
15 changed files with 1765 additions and 6 deletions

View File

@@ -7,9 +7,10 @@ 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 { expandHome } from "../utils/resolve-home"
const validTargets = ["opencode", "codex", "pi", "droid", "cursor"] as const
const validTargets = ["opencode", "codex", "pi", "droid", "cursor", "copilot"] as const
type SyncTarget = (typeof validTargets)[number]
function isValidTarget(value: string): value is SyncTarget {
@@ -42,19 +43,21 @@ function resolveOutputRoot(target: SyncTarget): string {
return path.join(os.homedir(), ".factory")
case "cursor":
return path.join(process.cwd(), ".cursor")
case "copilot":
return path.join(process.cwd(), ".github")
}
}
export default defineCommand({
meta: {
name: "sync",
description: "Sync Claude Code config (~/.claude/) to OpenCode, Codex, Pi, Droid, or Cursor",
description: "Sync Claude Code config (~/.claude/) to OpenCode, Codex, Pi, Droid, Cursor, or Copilot",
},
args: {
target: {
type: "string",
required: true,
description: "Target: opencode | codex | pi | droid | cursor",
description: "Target: opencode | codex | pi | droid | cursor | copilot",
},
claudeHome: {
type: "string",
@@ -100,6 +103,9 @@ export default defineCommand({
case "cursor":
await syncToCursor(config, outputRoot)
break
case "copilot":
await syncToCopilot(config, outputRoot)
break
}
console.log(`✓ Synced to ${args.target}: ${outputRoot}`)

View File

@@ -0,0 +1,212 @@
import { formatFrontmatter } from "../utils/frontmatter"
import type { ClaudeAgent, ClaudeCommand, ClaudeMcpServer, ClaudePlugin } from "../types/claude"
import type {
CopilotAgent,
CopilotBundle,
CopilotGeneratedSkill,
CopilotMcpServer,
} from "../types/copilot"
import type { ClaudeToOpenCodeOptions } from "./claude-to-opencode"
export type ClaudeToCopilotOptions = ClaudeToOpenCodeOptions
const COPILOT_BODY_CHAR_LIMIT = 30_000
export function convertClaudeToCopilot(
plugin: ClaudePlugin,
_options: ClaudeToCopilotOptions,
): CopilotBundle {
const usedAgentNames = new Set<string>()
const usedSkillNames = new Set<string>()
const agents = plugin.agents.map((agent) => convertAgent(agent, usedAgentNames))
// 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: Copilot does not support hooks. Hooks were skipped during conversion.")
}
return { agents, generatedSkills, skillDirs, mcpConfig }
}
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,
tools: ["*"],
infer: true,
}
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()
}
if (body.length === 0) {
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 convertCommandToSkill(
command: ClaudeCommand,
usedNames: Set<string>,
): CopilotGeneratedSkill {
const name = uniqueName(flattenCommandName(command.name), usedNames)
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 = transformContentForCopilot(command.body.trim())
sections.push(transformedBody)
const body = sections.filter(Boolean).join("\n\n").trim()
const content = formatFrontmatter(frontmatter, body)
return { name, content }
}
export function transformContentForCopilot(body: 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) => {
const skillName = normalizeName(agentName)
return `${prefix}Use the ${skillName} skill to: ${args.trim()}`
})
// 2. Transform slash command references (flatten namespaces)
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}`
})
// 3. Rewrite .claude/ paths to .github/ and ~/.claude/ to ~/.copilot/
result = result
.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
result = result.replace(agentRefPattern, (_match, agentName: string) => {
return `the ${normalizeName(agentName)} agent`
})
return result
}
function convertMcpServers(
servers?: Record<string, ClaudeMcpServer>,
): Record<string, CopilotMcpServer> | undefined {
if (!servers || Object.keys(servers).length === 0) return undefined
const result: Record<string, CopilotMcpServer> = {}
for (const [name, server] of Object.entries(servers)) {
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
} 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)
}
function normalizeName(value: string): string {
const trimmed = value.trim()
if (!trimmed) return "item"
const normalized = trimmed
.toLowerCase()
.replace(/[\\/]+/g, "-")
.replace(/[:\s]+/g, "-")
.replace(/[^a-z0-9_-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
return normalized || "item"
}
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
}

100
src/sync/copilot.ts Normal file
View File

@@ -0,0 +1,100 @@
import fs from "fs/promises"
import path from "path"
import type { ClaudeHomeConfig } from "../parsers/claude-home"
import type { ClaudeMcpServer } from "../types/claude"
import { forceSymlink, isValidSkillName } from "../utils/symlink"
type CopilotMcpServer = {
type: string
command?: string
args?: string[]
url?: string
tools: string[]
env?: Record<string, string>
headers?: Record<string, string>
}
type CopilotMcpConfig = {
mcpServers: Record<string, CopilotMcpServer>
}
export async function syncToCopilot(
config: ClaudeHomeConfig,
outputRoot: string,
): Promise<void> {
const skillsDir = path.join(outputRoot, "skills")
await fs.mkdir(skillsDir, { recursive: true })
for (const skill of config.skills) {
if (!isValidSkillName(skill.name)) {
console.warn(`Skipping skill with invalid name: ${skill.name}`)
continue
}
const target = path.join(skillsDir, skill.name)
await forceSymlink(skill.sourceDir, target)
}
if (Object.keys(config.mcpServers).length > 0) {
const mcpPath = path.join(outputRoot, "copilot-mcp-config.json")
const existing = await readJsonSafe(mcpPath)
const converted = convertMcpForCopilot(config.mcpServers)
const merged: CopilotMcpConfig = {
mcpServers: {
...(existing.mcpServers ?? {}),
...converted,
},
}
await fs.writeFile(mcpPath, JSON.stringify(merged, null, 2), { mode: 0o600 })
}
}
async function readJsonSafe(filePath: string): Promise<Partial<CopilotMcpConfig>> {
try {
const content = await fs.readFile(filePath, "utf-8")
return JSON.parse(content) as Partial<CopilotMcpConfig>
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
return {}
}
throw err
}
}
function convertMcpForCopilot(
servers: Record<string, ClaudeMcpServer>,
): Record<string, CopilotMcpServer> {
const result: Record<string, CopilotMcpServer> = {}
for (const [name, server] of Object.entries(servers)) {
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
} 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

@@ -4,16 +4,19 @@ 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 { 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 { writeOpenCodeBundle } from "./opencode"
import { writeCodexBundle } from "./codex"
import { writeDroidBundle } from "./droid"
import { writeCursorBundle } from "./cursor"
import { writePiBundle } from "./pi"
import { writeCopilotBundle } from "./copilot"
export type TargetHandler<TBundle = unknown> = {
name: string
@@ -53,4 +56,10 @@ export const targets: Record<string, TargetHandler> = {
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"],
},
}

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

@@ -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