feat(windsurf): add Windsurf as converter target with global scope support
Add `--to windsurf` target for the converter CLI with full spec compliance
per docs/specs/windsurf.md:
- Claude agents → Windsurf skills (skills/{name}/SKILL.md)
- Claude commands → Windsurf workflows (workflows/{name}.md, flat)
- Pass-through skills copy unchanged
- MCP servers → mcp_config.json (merged with existing, 0o600 permissions)
- Hooks skipped with warning, CLAUDE.md skipped
Global scope support via generic --scope flag (Windsurf as first adopter):
- --to windsurf defaults to global (~/.codeium/windsurf/)
- --scope workspace for project-level .windsurf/ output
- --output overrides scope-derived paths
Shared utilities extracted (resolveTargetOutputRoot, hasPotentialSecrets)
to eliminate duplication across CLI commands.
68 new tests (converter, writer, scope resolution).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -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"
|
||||
|
||||
const permissionModes: PermissionMode[] = ["none", "broad", "from-commands"]
|
||||
|
||||
@@ -23,7 +24,7 @@ export default defineCommand({
|
||||
to: {
|
||||
type: "string",
|
||||
default: "opencode",
|
||||
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro)",
|
||||
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro | windsurf)",
|
||||
},
|
||||
output: {
|
||||
type: "string",
|
||||
@@ -40,6 +41,10 @@ export default defineCommand({
|
||||
alias: "pi-home",
|
||||
description: "Write Pi output to this Pi root (ex: ~/.pi/agent or ./.pi)",
|
||||
},
|
||||
scope: {
|
||||
type: "string",
|
||||
description: "Scope level: global | workspace (default varies by target)",
|
||||
},
|
||||
also: {
|
||||
type: "string",
|
||||
description: "Comma-separated extra targets to generate (ex: codex)",
|
||||
@@ -76,8 +81,11 @@ export default defineCommand({
|
||||
throw new Error(`Unknown permissions mode: ${permissions}`)
|
||||
}
|
||||
|
||||
const resolvedScope = validateScope(targetName, target, args.scope ? String(args.scope) : undefined)
|
||||
|
||||
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"))
|
||||
|
||||
@@ -87,7 +95,14 @@ export default defineCommand({
|
||||
permissions: permissions as PermissionMode,
|
||||
}
|
||||
|
||||
const primaryOutputRoot = resolveTargetOutputRoot(targetName, outputRoot, codexHome, piHome)
|
||||
const primaryOutputRoot = resolveTargetOutputRoot({
|
||||
targetName,
|
||||
outputRoot,
|
||||
codexHome,
|
||||
piHome,
|
||||
hasExplicitOutput,
|
||||
scope: resolvedScope,
|
||||
})
|
||||
const bundle = target.convert(plugin, options)
|
||||
if (!bundle) {
|
||||
throw new Error(`Target ${targetName} did not return a bundle.`)
|
||||
@@ -113,7 +128,14 @@ export default defineCommand({
|
||||
console.warn(`Skipping ${extra}: no output returned.`)
|
||||
continue
|
||||
}
|
||||
const extraRoot = resolveTargetOutputRoot(extra, path.join(outputRoot, extra), codexHome, piHome)
|
||||
const extraRoot = resolveTargetOutputRoot({
|
||||
targetName: extra,
|
||||
outputRoot: path.join(outputRoot, extra),
|
||||
codexHome,
|
||||
piHome,
|
||||
hasExplicitOutput,
|
||||
scope: handler.defaultScope,
|
||||
})
|
||||
await handler.write(extraRoot, extraBundle)
|
||||
console.log(`Converted ${plugin.manifest.name} to ${extra} at ${extraRoot}`)
|
||||
}
|
||||
@@ -140,12 +162,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")
|
||||
if (targetName === "kiro") return path.join(outputRoot, ".kiro")
|
||||
return outputRoot
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
const permissionModes: PermissionMode[] = ["none", "broad", "from-commands"]
|
||||
|
||||
@@ -25,7 +26,7 @@ export default defineCommand({
|
||||
to: {
|
||||
type: "string",
|
||||
default: "opencode",
|
||||
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro)",
|
||||
description: "Target format (opencode | codex | droid | cursor | pi | copilot | gemini | kiro | windsurf)",
|
||||
},
|
||||
output: {
|
||||
type: "string",
|
||||
@@ -42,6 +43,10 @@ export default defineCommand({
|
||||
alias: "pi-home",
|
||||
description: "Write Pi output to this Pi root (ex: ~/.pi/agent or ./.pi)",
|
||||
},
|
||||
scope: {
|
||||
type: "string",
|
||||
description: "Scope level: global | workspace (default varies by target)",
|
||||
},
|
||||
also: {
|
||||
type: "string",
|
||||
description: "Comma-separated extra targets to generate (ex: codex)",
|
||||
@@ -77,6 +82,8 @@ export default defineCommand({
|
||||
throw new Error(`Unknown permissions mode: ${permissions}`)
|
||||
}
|
||||
|
||||
const resolvedScope = validateScope(targetName, target, args.scope ? String(args.scope) : undefined)
|
||||
|
||||
const resolvedPlugin = await resolvePluginPath(String(args.plugin))
|
||||
|
||||
try {
|
||||
@@ -96,7 +103,14 @@ export default defineCommand({
|
||||
throw new Error(`Target ${targetName} did not return a bundle.`)
|
||||
}
|
||||
const hasExplicitOutput = Boolean(args.output && String(args.output).trim())
|
||||
const primaryOutputRoot = resolveTargetOutputRoot(targetName, outputRoot, codexHome, piHome, hasExplicitOutput)
|
||||
const primaryOutputRoot = resolveTargetOutputRoot({
|
||||
targetName,
|
||||
outputRoot,
|
||||
codexHome,
|
||||
piHome,
|
||||
hasExplicitOutput,
|
||||
scope: resolvedScope,
|
||||
})
|
||||
await target.write(primaryOutputRoot, bundle)
|
||||
console.log(`Installed ${plugin.manifest.name} to ${primaryOutputRoot}`)
|
||||
|
||||
@@ -117,7 +131,14 @@ export default defineCommand({
|
||||
console.warn(`Skipping ${extra}: no output returned.`)
|
||||
continue
|
||||
}
|
||||
const extraRoot = resolveTargetOutputRoot(extra, path.join(outputRoot, extra), codexHome, piHome, hasExplicitOutput)
|
||||
const extraRoot = resolveTargetOutputRoot({
|
||||
targetName: extra,
|
||||
outputRoot: path.join(outputRoot, extra),
|
||||
codexHome,
|
||||
piHome,
|
||||
hasExplicitOutput,
|
||||
scope: handler.defaultScope,
|
||||
})
|
||||
await handler.write(extraRoot, extraBundle)
|
||||
console.log(`Installed ${plugin.manifest.name} to ${extraRoot}`)
|
||||
}
|
||||
@@ -169,35 +190,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")
|
||||
}
|
||||
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")
|
||||
}
|
||||
return outputRoot
|
||||
}
|
||||
|
||||
async function resolveGitHubPluginPath(pluginName: string): Promise<ResolvedPluginPath> {
|
||||
const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "compound-plugin-"))
|
||||
const source = resolveGitHubSource()
|
||||
|
||||
@@ -8,6 +8,7 @@ import { syncToPi } from "../sync/pi"
|
||||
import { syncToDroid } from "../sync/droid"
|
||||
import { syncToCopilot } from "../sync/copilot"
|
||||
import { expandHome } from "../utils/resolve-home"
|
||||
import { hasPotentialSecrets } from "../utils/secrets"
|
||||
|
||||
const validTargets = ["opencode", "codex", "pi", "droid", "copilot"] as const
|
||||
type SyncTarget = (typeof validTargets)[number]
|
||||
@@ -16,20 +17,6 @@ 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: SyncTarget): string {
|
||||
switch (target) {
|
||||
case "opencode":
|
||||
|
||||
205
src/converters/claude-to-windsurf.ts
Normal file
205
src/converters/claude-to-windsurf.ts
Normal 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
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type { PiBundle } from "../types/pi"
|
||||
import type { CopilotBundle } from "../types/copilot"
|
||||
import type { GeminiBundle } from "../types/gemini"
|
||||
import type { KiroBundle } from "../types/kiro"
|
||||
import type { WindsurfBundle } from "../types/windsurf"
|
||||
import { convertClaudeToOpenCode, type ClaudeToOpenCodeOptions } from "../converters/claude-to-opencode"
|
||||
import { convertClaudeToCodex } from "../converters/claude-to-codex"
|
||||
import { convertClaudeToDroid } from "../converters/claude-to-droid"
|
||||
@@ -13,6 +14,7 @@ import { convertClaudeToPi } from "../converters/claude-to-pi"
|
||||
import { convertClaudeToCopilot } from "../converters/claude-to-copilot"
|
||||
import { convertClaudeToGemini } from "../converters/claude-to-gemini"
|
||||
import { convertClaudeToKiro } from "../converters/claude-to-kiro"
|
||||
import { convertClaudeToWindsurf } from "../converters/claude-to-windsurf"
|
||||
import { writeOpenCodeBundle } from "./opencode"
|
||||
import { writeCodexBundle } from "./codex"
|
||||
import { writeDroidBundle } from "./droid"
|
||||
@@ -20,10 +22,41 @@ import { writePiBundle } from "./pi"
|
||||
import { writeCopilotBundle } from "./copilot"
|
||||
import { writeGeminiBundle } from "./gemini"
|
||||
import { writeKiroBundle } from "./kiro"
|
||||
import { writeWindsurfBundle } from "./windsurf"
|
||||
|
||||
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>
|
||||
}
|
||||
@@ -71,4 +104,12 @@ export const targets: Record<string, TargetHandler> = {
|
||||
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"],
|
||||
},
|
||||
}
|
||||
|
||||
102
src/targets/windsurf.ts
Normal file
102
src/targets/windsurf.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
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"
|
||||
|
||||
/**
|
||||
* 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): 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 workflows/, per spec)
|
||||
if (bundle.commandWorkflows.length > 0) {
|
||||
const workflowsDir = path.join(outputRoot, "workflows")
|
||||
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"
|
||||
}
|
||||
34
src/types/windsurf.ts
Normal file
34
src/types/windsurf.ts
Normal 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
|
||||
}
|
||||
@@ -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[] = []
|
||||
|
||||
39
src/utils/resolve-output.ts
Normal file
39
src/utils/resolve-output.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
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
|
||||
hasExplicitOutput: boolean
|
||||
scope?: TargetScope
|
||||
}): string {
|
||||
const { targetName, outputRoot, codexHome, piHome, 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")
|
||||
}
|
||||
return outputRoot
|
||||
}
|
||||
24
src/utils/secrets.ts
Normal file
24
src/utils/secrets.ts
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user