-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconverter.ts
More file actions
273 lines (232 loc) · 7.88 KB
/
converter.ts
File metadata and controls
273 lines (232 loc) · 7.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import fs from 'node:fs'
import { formatFrontmatter, parseFrontmatter } from './frontmatter.js'
export type ContentType = 'skill' | 'agent' | 'command'
export type SourceType = 'bundled' | 'external'
export type AgentMode = 'primary' | 'subagent'
export interface ConvertOptions {
source?: SourceType
agentMode?: AgentMode
/** Skip body content transformations (tool names, paths, etc.) */
skipBodyTransform?: boolean
}
interface CacheEntry {
mtimeMs: number
converted: string
}
const cache = new Map<string, CacheEntry>()
/**
* Claude Code tool names mapped to OpenCode equivalents.
* Only includes tools that need transformation (case changes or renames).
*
* Task transformation strategy:
* - Match Task followed by parentheses or agent-name pattern (tool invocation)
* - Match "Task tool" explicitly
* - Avoid standalone "Task" as noun (e.g., "Complete the Task")
*/
const TOOL_MAPPINGS: ReadonlyArray<readonly [RegExp, string]> = [
// Semantic tool renames (different names in OC)
// Task tool explicit reference
[/\bTask\s+tool\b/gi, 'delegate_task tool'],
// Task followed by agent name + colon: Task agent-name: "prompt"
[/\bTask\s+([\w-]+)\s*:/g, 'delegate_task $1:'],
// Task followed by agent name + parens: Task agent-name(args)
[/\bTask\s+([\w-]+)\s*\(/g, 'delegate_task $1('],
// Task with immediate parens: Task(args) or Task (args)
[/\bTask\s*\(/g, 'delegate_task('],
// Task followed by "to" verb pattern: use Task to spawn
[/\bTask\b(?=\s+to\s+\w)/g, 'delegate_task'],
[/\bTodoWrite\b/g, 'todowrite'],
[/\bAskUserQuestion\b/g, 'question'],
[/\bWebSearch\b/g, 'google_search'],
// Case normalization (CC uses PascalCase, OC uses lowercase)
[/\bRead\b(?=\s+tool|\s+to\s+|\()/g, 'read'],
[/\bWrite\b(?=\s+tool|\s+to\s+|\()/g, 'write'],
[/\bEdit\b(?=\s+tool|\s+to\s+|\()/g, 'edit'],
[/\bBash\b(?=\s+tool|\s+to\s+|\()/g, 'bash'],
[/\bGrep\b(?=\s+tool|\s+to\s+|\()/g, 'grep'],
[/\bGlob\b(?=\s+tool|\s+to\s+|\()/g, 'glob'],
[/\bWebFetch\b/g, 'webfetch'],
// Skill tool invocation: Skill("name") or Skill tool reference
[/\bSkill\b(?=\s+tool|\s*\()/g, 'skill'],
] as const
/**
* Path and reference replacements for CC → OC migration.
*/
const PATH_REPLACEMENTS: ReadonlyArray<readonly [RegExp, string]> = [
[/\.claude\/skills\//g, '.opencode/skills/'],
[/\.claude\/commands\//g, '.opencode/commands/'],
[/\.claude\/agents\//g, '.opencode/agents/'],
[/~\/\.claude\//g, '~/.config/opencode/'],
[/CLAUDE\.md/g, 'AGENTS.md'],
[/\/compound-engineering:/g, '/systematic:'],
[/compound-engineering:/g, 'systematic:'],
] as const
/**
* CC-only frontmatter fields that should be removed from skills.
*/
const CC_ONLY_SKILL_FIELDS = [
'model',
'allowed-tools',
'allowedTools',
'disable-model-invocation',
'disableModelInvocation',
'user-invocable',
'userInvocable',
'context',
'agent',
] as const
/**
* CC-only frontmatter fields that should be removed from commands.
*/
const CC_ONLY_COMMAND_FIELDS = ['argument-hint', 'argumentHint'] as const
function inferTemperature(name: string, description?: string): number {
const sample = `${name} ${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 0.3
}
const CODE_BLOCK_PATTERN = /```[\s\S]*?```|`[^`\n]+`/g
function transformBody(body: string): string {
const codeBlocks: string[] = []
let placeholderIndex = 0
const withPlaceholders = body.replace(CODE_BLOCK_PATTERN, (match) => {
codeBlocks.push(match)
return `__CODE_BLOCK_${placeholderIndex++}__`
})
let result = withPlaceholders
for (const [pattern, replacement] of TOOL_MAPPINGS) {
result = result.replace(pattern, replacement)
}
for (const [pattern, replacement] of PATH_REPLACEMENTS) {
result = result.replace(pattern, replacement)
}
for (let i = 0; i < codeBlocks.length; i++) {
result = result.replace(`__CODE_BLOCK_${i}__`, codeBlocks[i])
}
return result
}
function removeFields(
data: Record<string, unknown>,
fieldsToRemove: readonly string[],
): Record<string, unknown> {
const result: Record<string, unknown> = {}
for (const [key, value] of Object.entries(data)) {
if (!fieldsToRemove.includes(key)) {
result[key] = value
}
}
return result
}
function transformSkillFrontmatter(
data: Record<string, unknown>,
): Record<string, unknown> {
return removeFields(data, CC_ONLY_SKILL_FIELDS)
}
function transformCommandFrontmatter(
data: Record<string, unknown>,
): Record<string, unknown> {
const cleaned = removeFields(data, CC_ONLY_COMMAND_FIELDS)
if (typeof cleaned.model === 'string' && cleaned.model !== 'inherit') {
cleaned.model = normalizeModel(cleaned.model)
} else if (cleaned.model === 'inherit') {
delete cleaned.model
}
return cleaned
}
function normalizeModel(model: string): string {
if (model.includes('/')) return model
if (model === 'inherit') return model
if (/^claude-/.test(model)) return `anthropic/${model}`
if (/^(gpt-|o1-|o3-)/.test(model)) return `openai/${model}`
if (/^gemini-/.test(model)) return `google/${model}`
return `anthropic/${model}`
}
function transformAgentFrontmatter(
data: Record<string, unknown>,
agentMode: AgentMode,
): Record<string, unknown> {
const name = typeof data.name === 'string' ? data.name : ''
const description =
typeof data.description === 'string' ? data.description : ''
const newData: Record<string, unknown> = {
description: description || `${name} agent`,
mode: agentMode,
}
if (typeof data.model === 'string' && data.model !== 'inherit') {
newData.model = normalizeModel(data.model)
}
if (typeof data.temperature === 'number') {
newData.temperature = data.temperature
} else {
newData.temperature = inferTemperature(name, description)
}
return newData
}
export function convertContent(
content: string,
type: ContentType,
options: ConvertOptions = {},
): string {
if (content === '') return ''
const { data, body, hadFrontmatter } =
parseFrontmatter<Record<string, unknown>>(content)
if (!hadFrontmatter) {
return options.skipBodyTransform ? content : transformBody(content)
}
const shouldTransformBody = !options.skipBodyTransform
const transformedBody = shouldTransformBody ? transformBody(body) : body
if (type === 'agent') {
const agentMode = options.agentMode ?? 'subagent'
const transformedData = transformAgentFrontmatter(data, agentMode)
return `${formatFrontmatter(transformedData)}\n${transformedBody}`
}
if (type === 'skill') {
const transformedData = transformSkillFrontmatter(data)
return `${formatFrontmatter(transformedData)}\n${transformedBody}`
}
if (type === 'command') {
const transformedData = transformCommandFrontmatter(data)
return `${formatFrontmatter(transformedData)}\n${transformedBody}`
}
return content
}
export function convertFileWithCache(
filePath: string,
type: ContentType,
options: ConvertOptions = {},
): string {
const fd = fs.openSync(filePath, 'r')
try {
const stats = fs.fstatSync(fd)
const cacheKey = `${filePath}:${type}:${options.source ?? 'bundled'}:${options.agentMode ?? 'subagent'}:${options.skipBodyTransform ?? false}`
const cached = cache.get(cacheKey)
if (cached != null && cached.mtimeMs === stats.mtimeMs) {
return cached.converted
}
const content = fs.readFileSync(fd, 'utf8')
const converted = convertContent(content, type, options)
cache.set(cacheKey, { mtimeMs: stats.mtimeMs, converted })
return converted
} finally {
fs.closeSync(fd)
}
}
export function clearConverterCache(): void {
cache.clear()
}