feat(gemini): add Gemini CLI as sixth target provider

Add `--to gemini` support for both `convert` and `install` commands,
converting Claude Code plugins into Gemini CLI-compatible format.

- Agents convert to `.gemini/skills/*/SKILL.md` with description frontmatter
- Commands convert to `.gemini/commands/*.toml` with TOML prompt format
- Namespaced commands create directory structure (workflows:plan -> workflows/plan.toml)
- Skills pass through unchanged (identical SKILL.md standard)
- MCP servers written to `.gemini/settings.json` with merge support
- Content transforms: .claude/ paths, Task calls, @agent references
- Hooks emit warning (different format in Gemini)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Kieran Klaassen
2026-02-14 20:33:21 -08:00
parent 134a994c08
commit 201ad6d0fb
8 changed files with 822 additions and 2 deletions

View File

@@ -23,7 +23,7 @@ export default defineCommand({
to: {
type: "string",
default: "opencode",
description: "Target format (opencode | codex | droid | cursor | pi)",
description: "Target format (opencode | codex | droid | cursor | pi | gemini)",
},
output: {
type: "string",
@@ -145,5 +145,6 @@ function resolveTargetOutputRoot(targetName: string, outputRoot: string, codexHo
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

@@ -25,7 +25,7 @@ export default defineCommand({
to: {
type: "string",
default: "opencode",
description: "Target format (opencode | codex | droid | cursor | pi)",
description: "Target format (opencode | codex | droid | cursor | pi | gemini)",
},
output: {
type: "string",
@@ -183,6 +183,10 @@ function resolveTargetOutputRoot(
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
}

View File

@@ -0,0 +1,193 @@
import { formatFrontmatter } from "../utils/frontmatter"
import type { ClaudeAgent, ClaudeCommand, ClaudeMcpServer, ClaudePlugin } from "../types/claude"
import type { GeminiBundle, GeminiCommand, GeminiSkill } from "../types/gemini"
import type { ClaudeToOpenCodeOptions } from "./claude-to-opencode"
export type ClaudeToGeminiOptions = ClaudeToOpenCodeOptions
const GEMINI_DESCRIPTION_MAX_LENGTH = 1024
export function convertClaudeToGemini(
plugin: ClaudePlugin,
_options: ClaudeToGeminiOptions,
): GeminiBundle {
const usedSkillNames = new Set<string>()
const usedCommandNames = new Set<string>()
const skillDirs = plugin.skills.map((skill) => ({
name: skill.name,
sourceDir: skill.sourceDir,
}))
// Reserve skill names from pass-through skills
for (const skill of skillDirs) {
usedSkillNames.add(normalizeName(skill.name))
}
const generatedSkills = plugin.agents.map((agent) => convertAgentToSkill(agent, usedSkillNames))
const commands = plugin.commands.map((command) => convertCommand(command, usedCommandNames))
const mcpServers = convertMcpServers(plugin.mcpServers)
if (plugin.hooks && Object.keys(plugin.hooks.hooks).length > 0) {
console.warn("Warning: Gemini CLI hooks use a different format (BeforeTool/AfterTool with matchers). Hooks were skipped during conversion.")
}
return { generatedSkills, skillDirs, commands, mcpServers }
}
function convertAgentToSkill(agent: ClaudeAgent, usedNames: Set<string>): GeminiSkill {
const name = uniqueName(normalizeName(agent.name), usedNames)
const description = sanitizeDescription(
agent.description ?? `Use this skill for ${agent.name} tasks`,
)
const frontmatter: Record<string, unknown> = { name, description }
let body = transformContentForGemini(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.`
}
const content = formatFrontmatter(frontmatter, body)
return { name, content }
}
function convertCommand(command: ClaudeCommand, usedNames: Set<string>): GeminiCommand {
// Preserve namespace structure: workflows:plan -> workflows/plan
const commandPath = resolveCommandPath(command.name)
const pathKey = commandPath.join("/")
uniqueName(pathKey, usedNames) // Track for dedup
const description = command.description ?? `Converted from Claude command ${command.name}`
const transformedBody = transformContentForGemini(command.body.trim())
let prompt = transformedBody
if (command.argumentHint) {
prompt += `\n\nUser request: {{args}}`
}
const content = toToml(description, prompt)
return { name: pathKey, content }
}
/**
* Transform Claude Code content to Gemini-compatible content.
*
* 1. Task agent calls: Task agent-name(args) -> Use the agent-name skill to: args
* 2. Path rewriting: .claude/ -> .gemini/, ~/.claude/ -> ~/.gemini/
* 3. Agent references: @agent-name -> the agent-name skill
*/
export function transformContentForGemini(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. Rewrite .claude/ paths to .gemini/
result = result
.replace(/~\/\.claude\//g, "~/.gemini/")
.replace(/\.claude\//g, ".gemini/")
// 3. 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)} skill`
})
return result
}
function convertMcpServers(
servers?: Record<string, ClaudeMcpServer>,
): GeminiBundle["mcpServers"] | undefined {
if (!servers || Object.keys(servers).length === 0) return undefined
const result: NonNullable<GeminiBundle["mcpServers"]> = {}
for (const [name, server] of Object.entries(servers)) {
const entry: NonNullable<GeminiBundle["mcpServers"]>[string] = {}
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
}
result[name] = entry
}
return result
}
/**
* Resolve command name to path segments.
* workflows:plan -> ["workflows", "plan"]
* plan -> ["plan"]
*/
function resolveCommandPath(name: string): string[] {
return name.split(":").map((segment) => normalizeName(segment))
}
/**
* Serialize to TOML command format.
* Uses multi-line strings (""") for prompt field.
*/
export function toToml(description: string, prompt: string): string {
const lines: string[] = []
lines.push(`description = ${formatTomlString(description)}`)
// Use multi-line string for prompt
const escapedPrompt = prompt.replace(/\\/g, "\\\\").replace(/"""/g, '\\"\\"\\"')
lines.push(`prompt = """`)
lines.push(escapedPrompt)
lines.push(`"""`)
return lines.join("\n")
}
function formatTomlString(value: string): string {
return JSON.stringify(value)
}
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 sanitizeDescription(value: string, maxLength = GEMINI_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
}

65
src/targets/gemini.ts Normal file
View File

@@ -0,0 +1,65 @@
import path from "path"
import { backupFile, copyDir, ensureDir, pathExists, readJson, writeJson, writeText } from "../utils/files"
import type { GeminiBundle } from "../types/gemini"
export async function writeGeminiBundle(outputRoot: string, bundle: GeminiBundle): Promise<void> {
const paths = resolveGeminiPaths(outputRoot)
await ensureDir(paths.geminiDir)
if (bundle.generatedSkills.length > 0) {
for (const skill of bundle.generatedSkills) {
await writeText(path.join(paths.skillsDir, skill.name, "SKILL.md"), skill.content + "\n")
}
}
if (bundle.skillDirs.length > 0) {
for (const skill of bundle.skillDirs) {
await copyDir(skill.sourceDir, path.join(paths.skillsDir, skill.name))
}
}
if (bundle.commands.length > 0) {
for (const command of bundle.commands) {
await writeText(path.join(paths.commandsDir, `${command.name}.toml`), command.content + "\n")
}
}
if (bundle.mcpServers && Object.keys(bundle.mcpServers).length > 0) {
const settingsPath = path.join(paths.geminiDir, "settings.json")
const backupPath = await backupFile(settingsPath)
if (backupPath) {
console.log(`Backed up existing settings.json to ${backupPath}`)
}
// Merge mcpServers into existing settings if present
let existingSettings: Record<string, unknown> = {}
if (await pathExists(settingsPath)) {
try {
existingSettings = await readJson<Record<string, unknown>>(settingsPath)
} catch {
// If existing file is invalid JSON, start fresh
}
}
const merged = { ...existingSettings, mcpServers: bundle.mcpServers }
await writeJson(settingsPath, merged)
}
}
function resolveGeminiPaths(outputRoot: string) {
const base = path.basename(outputRoot)
// If already pointing at .gemini, write directly into it
if (base === ".gemini") {
return {
geminiDir: outputRoot,
skillsDir: path.join(outputRoot, "skills"),
commandsDir: path.join(outputRoot, "commands"),
}
}
// Otherwise nest under .gemini
return {
geminiDir: path.join(outputRoot, ".gemini"),
skillsDir: path.join(outputRoot, ".gemini", "skills"),
commandsDir: path.join(outputRoot, ".gemini", "commands"),
}
}

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 { GeminiBundle } from "../types/gemini"
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 { convertClaudeToGemini } from "../converters/claude-to-gemini"
import { writeOpenCodeBundle } from "./opencode"
import { writeCodexBundle } from "./codex"
import { writeDroidBundle } from "./droid"
import { writeCursorBundle } from "./cursor"
import { writePiBundle } from "./pi"
import { writeGeminiBundle } from "./gemini"
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"],
},
gemini: {
name: "gemini",
implemented: true,
convert: convertClaudeToGemini as TargetHandler<GeminiBundle>["convert"],
write: writeGeminiBundle as TargetHandler<GeminiBundle>["write"],
},
}

27
src/types/gemini.ts Normal file
View File

@@ -0,0 +1,27 @@
export type GeminiSkill = {
name: string
content: string // Full SKILL.md with YAML frontmatter
}
export type GeminiSkillDir = {
name: string
sourceDir: string
}
export type GeminiCommand = {
name: string // e.g. "plan" or "workflows/plan"
content: string // Full TOML content
}
export type GeminiBundle = {
generatedSkills: GeminiSkill[] // From agents
skillDirs: GeminiSkillDir[] // From skills (pass-through)
commands: GeminiCommand[]
mcpServers?: Record<string, {
command?: string
args?: string[]
env?: Record<string, string>
url?: string
headers?: Record<string, string>
}>
}