-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathadapter-transforms.js
More file actions
671 lines (566 loc) · 27.5 KB
/
Copy pathadapter-transforms.js
File metadata and controls
671 lines (566 loc) · 27.5 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/**
* Adapter Transform Functions
*
* Shared transforms for converting Claude Code plugin content into
* OpenCode and Codex adapter formats. Used by:
* - bin/cli.js (npm installer)
* - scripts/dev-install.js (development installer)
* - scripts/gen-adapters.js (static adapter generation)
*
* @module adapter-transforms
* @author Avi Fenesh
* @license MIT
*/
const discovery = require('./discovery');
function transformBodyForOpenCode(content, repoRoot) {
content = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, '${PLUGIN_ROOT}');
content = content.replace(/\$CLAUDE_PLUGIN_ROOT/g, '$PLUGIN_ROOT');
// Replace .claude/ paths with .opencode/ but preserve platform documentation lists
// that enumerate all three platforms (Claude Code: .claude/, OpenCode: .opencode/, Codex: .codex/)
// Also preserve {AI_STATE_DIR} references which are platform-agnostic
content = content.replace(/\.claude\//g, (match, offset) => {
const context = content.substring(Math.max(0, offset - 60), offset + match.length + 10);
// Skip if inside a platform enumeration (e.g., "Claude Code: `.claude/`")
if (/Claude Code:/.test(context)) return match;
return '.opencode/';
});
content = content.replace(/\.claude'/g, (match, offset) => {
const context = content.substring(Math.max(0, offset - 60), offset + match.length + 10);
if (/Claude Code:/.test(context)) return match;
return ".opencode'";
});
content = content.replace(/\.claude"/g, (match, offset) => {
const context = content.substring(Math.max(0, offset - 60), offset + match.length + 10);
if (/Claude Code:/.test(context)) return match;
return '.opencode"';
});
content = content.replace(/\.claude`/g, (match, offset) => {
const context = content.substring(Math.max(0, offset - 60), offset + match.length + 10);
if (/Claude Code:/.test(context)) return match;
return '.opencode`';
});
const plugins = discovery.discoverPlugins(repoRoot);
if (plugins.length > 0) {
const pluginNames = plugins.join('|');
content = content.replace(new RegExp('`(' + pluginNames + '):([a-z-]+)`', 'g'), '`$2`');
content = content.replace(new RegExp('(' + pluginNames + '):([a-z-]+)', 'g'), '$2');
}
content = content.replace(
/```(\w*)\n([\s\S]*?)```/g,
(match, lang, code) => {
const langLower = (lang || '').toLowerCase();
if (langLower === 'bash' || langLower === 'shell' || langLower === 'sh') {
if (code.includes('node -e') && code.includes('require(')) {
return '*(Bash command with Node.js require - adapt for OpenCode)*';
}
return match;
}
if (!lang && (code.trim().startsWith('gh ') || code.trim().startsWith('glab ') ||
code.trim().startsWith('git ') || code.trim().startsWith('#!'))) {
return match;
}
if (code.includes('require(') || code.includes('Task(') ||
/^\s*const\s+[a-zA-Z_$[{]/m.test(code) || /^\s*let\s+[a-zA-Z_$[{]/m.test(code) ||
code.includes('function ') || code.includes('=>') ||
code.includes('async ') || code.includes('await ') ||
code.includes('completePhase')) {
let instructions = '';
const taskMatches = [...code.matchAll(/(?:await\s+)?Task\s*\(\s*\{[^}]*subagent_type:\s*["'](?:[^"':]+:)?([^"']+)["'][^}]*\}\s*\)/gs)];
for (const taskMatch of taskMatches) {
const agent = taskMatch[1];
instructions += `- Invoke \`@${agent}\` agent\n`;
}
const phaseMatches = code.match(/startPhase\s*\(\s*['"]([^'"]+)['"]\s*\)/g);
if (phaseMatches) {
for (const pm of phaseMatches) {
const phase = pm.match(/['"]([^'"]+)['"]/)[1];
instructions += `- Phase: ${phase}\n`;
}
}
if (code.includes('AskUserQuestion')) {
instructions += '- Use AskUserQuestion tool for user input\n';
}
if (code.includes('EnterPlanMode')) {
instructions += '- Use EnterPlanMode for user approval\n';
}
if (code.includes('completePhase')) {
instructions += '- Call `workflowState.completePhase(result)` to advance workflow state\n';
}
if (instructions) {
return instructions;
}
return '*(JavaScript reference - not executable in OpenCode)*';
}
return match;
}
);
content = content.replace(/\*\(Reference - adapt for OpenCode\)\*/g, '');
content = content.replace(/await\s+Task\s*\(\s*\{[\s\S]*?\}\s*\);?/g, (match) => {
const agentMatch = match.match(/subagent_type:\s*["'](?:[^"':]+:)?([^"']+)["']/);
if (agentMatch) {
return `Invoke \`@${agentMatch[1]}\` agent`;
}
return '*(Task call - use @agent-name syntax)*';
});
content = content.replace(/(?:const|let|var)\s+\{?[^}=\n]+\}?\s*=\s*require\s*\([^)]+\);?/g, '');
content = content.replace(/require\s*\(['"][^'"]+['"]\)/g, '');
if (content.includes('agent')) {
const note = `
> **OpenCode Note**: Invoke agents using \`@agent-name\` syntax.
> Available agents: task-discoverer, exploration-agent, planning-agent,
> implementation-agent, deslop-agent, delivery-validator, sync-docs-agent, consult-agent
> Example: \`@exploration-agent analyze the codebase\`
`;
content = content.replace(/^(---\n[\s\S]*?---\n)/, `$1${note}`);
}
if (content.includes('Master Workflow Orchestrator') && content.includes('No Shortcuts Policy')) {
const policySection = `
## Phase 1: Policy Selection (Built-in Options)
Ask the user these questions using AskUserQuestion:
**Question 1 - Source**: "Where should I look for tasks?"
- GitHub Issues - Use \`gh issue list\` to find issues
- GitHub Projects - Issues from a GitHub Project board
- GitLab Issues - Use \`glab issue list\` to find issues
- Local tasks.md - Read from PLAN.md, tasks.md, or TODO.md in the repo
- Custom - User specifies their own source
- Other - User describes source, you figure it out
If user selects GitHub Projects, ask two follow-up questions: project number (positive integer from the project URL, e.g. 1, 5, 42) and project owner (@me for your own projects, or the org/username). Pass as responses.project = { number, owner } to parseAndCachePolicy.
**Question 2 - Priority**: "What type of tasks to prioritize?"
- All - Consider all tasks, pick by score
- Bugs - Focus on bug fixes
- Security - Security issues first
- Features - New feature development
**Question 3 - Stop Point**: "How far should I take this task?"
- Merged - Until PR is merged to main
- PR Created - Stop after creating PR
- Implemented - Stop after local implementation
- Deployed - Deploy to staging
- Production - Full production deployment
After user answers, proceed to Phase 2 with the selected policy.
`;
if (content.includes('OpenCode Note')) {
content = content.replace(/(Example:.*analyze the codebase\`\n\n)/, `$1${policySection}`);
}
}
return content;
}
function transformCommandFrontmatterForOpenCode(content) {
return content.replace(
/^---\n([\s\S]*?)^---/m,
(match, frontmatter) => {
// Parse existing frontmatter
const lines = frontmatter.trim().split('\n');
const parsed = {};
for (const line of lines) {
const colonIdx = line.indexOf(':');
if (colonIdx > 0) {
const key = line.substring(0, colonIdx).trim();
const value = line.substring(colonIdx + 1).trim();
parsed[key] = value;
}
}
// Build OpenCode command frontmatter
let opencodeFrontmatter = '---\n';
if (parsed.description) opencodeFrontmatter += `description: ${parsed.description}\n`;
opencodeFrontmatter += 'agent: general\n';
// Don't include argument-hint or allowed-tools (not supported)
opencodeFrontmatter += '---';
return opencodeFrontmatter;
}
);
}
function transformAgentFrontmatterForOpenCode(content, options) {
const { stripModels = true } = options || {};
return content.replace(
/^---\n([\s\S]*?)^---/m,
(match, frontmatter) => {
// Parse existing frontmatter
const lines = frontmatter.trim().split('\n');
const parsed = {};
for (const line of lines) {
const colonIdx = line.indexOf(':');
if (colonIdx > 0) {
const key = line.substring(0, colonIdx).trim();
const value = line.substring(colonIdx + 1).trim();
parsed[key] = value;
}
}
// Build OpenCode frontmatter
let opencodeFrontmatter = '---\n';
if (parsed.name) opencodeFrontmatter += `name: ${parsed.name}\n`;
if (parsed.description) opencodeFrontmatter += `description: ${parsed.description}\n`;
opencodeFrontmatter += 'mode: subagent\n';
// Map model names - only include if NOT stripping
if (parsed.model && !stripModels) {
const modelMap = {
'sonnet': 'anthropic/claude-sonnet-4',
'opus': 'anthropic/claude-opus-4',
'haiku': 'anthropic/claude-haiku-3-5'
};
opencodeFrontmatter += `model: ${modelMap[parsed.model] || parsed.model}\n`;
}
// Convert tools to permissions
if (parsed.tools) {
opencodeFrontmatter += 'permission:\n';
const tools = parsed.tools.toLowerCase();
opencodeFrontmatter += ` read: ${tools.includes('read') ? 'allow' : 'deny'}\n`;
opencodeFrontmatter += ` edit: ${tools.includes('edit') || tools.includes('write') ? 'allow' : 'deny'}\n`;
opencodeFrontmatter += ` bash: ${tools.includes('bash') ? 'allow' : 'ask'}\n`;
opencodeFrontmatter += ` glob: ${tools.includes('glob') ? 'allow' : 'deny'}\n`;
opencodeFrontmatter += ` grep: ${tools.includes('grep') ? 'allow' : 'deny'}\n`;
}
opencodeFrontmatter += '---';
return opencodeFrontmatter;
}
);
}
function transformSkillBodyForOpenCode(content, repoRoot) {
return transformBodyForOpenCode(content, repoRoot);
}
function transformForCodex(content, options) {
const { skillName, description, pluginInstallPath } = options;
// Escape description for YAML: wrap in double quotes, escape backslashes and internal quotes
const escapedDescription = description.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
const yamlDescription = `"${escapedDescription}"`;
if (content.startsWith('---')) {
// Replace existing frontmatter with Codex-compatible format
content = content.replace(
/^---\n[\s\S]*?\n---\n/,
`---\nname: ${skillName}\ndescription: ${yamlDescription}\n---\n`
);
} else {
// Add new frontmatter
content = `---\nname: ${skillName}\ndescription: ${yamlDescription}\n---\n\n${content}`;
}
// Transform PLUGIN_ROOT to actual installed path (or placeholder) for Codex
content = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, pluginInstallPath);
content = content.replace(/\$CLAUDE_PLUGIN_ROOT/g, pluginInstallPath);
content = content.replace(/\$\{PLUGIN_ROOT\}/g, pluginInstallPath);
content = content.replace(/\$PLUGIN_ROOT/g, pluginInstallPath);
// Transform AskUserQuestion → request_user_input for Codex native tool
content = content.replace(/AskUserQuestion/g, 'request_user_input');
// Remove multiSelect lines (not supported in Codex)
content = content.replace(/^[ \t]*multiSelect:.*\n?/gm, '');
// Inject Codex note about required id field after request_user_input blocks
content = content.replace(
/^([ \t]*request_user_input:\s*)$/gm,
'$1\n> **Codex**: Each question MUST include a unique `id` field (e.g., `id: "q1"`).'
);
return content;
}
/**
* Transform content for Cursor (.mdc rule files).
*
* MDC format uses YAML frontmatter with `description`, `globs`, and
* `alwaysApply` fields followed by a markdown body.
*
* @param {string} content - Source markdown content (may have frontmatter)
* @param {Object} options
* @param {string} options.description - Rule description
* @param {string} options.pluginInstallPath - Absolute path to plugin install dir
* @param {string} [options.globs] - Optional glob pattern for file matching
* @param {boolean} [options.alwaysApply] - Whether rule always applies (default true)
* @returns {string} Transformed MDC content
*/
function transformRuleForCursor(content, options) {
const { description = '', pluginInstallPath, globs = '', alwaysApply = true } = options;
// Strip control characters and escape description for YAML
const cleanDescription = description.replace(/[\x00-\x1f\x7f]/g, ' ');
const escapedDescription = cleanDescription.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
const yamlDescription = `"${escapedDescription}"`;
// Build MDC frontmatter
let frontmatter = `---\ndescription: ${yamlDescription}\n`;
if (globs) {
frontmatter += `globs: ${JSON.stringify(globs)}\n`;
}
frontmatter += `alwaysApply: ${alwaysApply}\n---\n`;
// Strip existing frontmatter if present
if (content.startsWith('---')) {
content = content.replace(/^---\n[\s\S]*?\n---\n?/, '');
}
content = frontmatter + content;
// Replace PLUGIN_ROOT paths with actual install path
// Use function replacement to avoid $ pattern interpretation in replacement string
content = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$CLAUDE_PLUGIN_ROOT/g, () => pluginInstallPath);
content = content.replace(/\$\{PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$PLUGIN_ROOT/g, () => pluginInstallPath);
// Strip Claude-specific syntax: Task tool calls (handles one level of nested braces)
content = content.replace(/await\s+Task\s*\(\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}\s*\);?/g, (match) => {
const agentMatch = match.match(/subagent_type:\s*["'](?:[^"':]+:)?([^"']+)["']/);
if (agentMatch) {
return `Invoke the ${agentMatch[1]} agent`;
}
return '';
});
// Strip require() statements
content = content.replace(/(?:const|let|var)\s+\{?[^}=\n]+\}?\s*=\s*require\s*\([^)]+\);?/g, '');
content = content.replace(/require\s*\(['"][^'"]+['"]\)/g, '');
// Strip plugin namespacing (e.g. next-task:agent-name -> agent-name)
content = content.replace(/(?:next-task|deslop|ship|sync-docs|audit-project|enhance|perf|repo-map|drift-detect|consult|debate|learn|web-ctl):([a-z][a-z0-9-]*)/g, '$1');
return content;
}
/**
* Transform skill content for Cursor.
*
* Minimal transform - Cursor reads SKILL.md frontmatter natively so we
* preserve it. Only replaces PLUGIN_ROOT paths and strips namespace prefixes.
*
* @param {string} content - Source SKILL.md content
* @param {Object} options
* @param {string} options.pluginInstallPath - Absolute path to plugin install dir
* @returns {string} Transformed skill content
*/
function transformSkillForCursor(content, options) {
const { pluginInstallPath } = options;
// Replace PLUGIN_ROOT paths with actual install path
content = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$CLAUDE_PLUGIN_ROOT/g, () => pluginInstallPath);
content = content.replace(/\$\{PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$PLUGIN_ROOT/g, () => pluginInstallPath);
// Strip plugin namespacing (e.g. next-task:agent-name -> agent-name)
content = content.replace(/(?:next-task|deslop|ship|sync-docs|audit-project|enhance|perf|repo-map|drift-detect|consult|debate|learn|web-ctl):([a-z][a-z0-9-]*)/g, '$1');
return content;
}
/**
* Transform command content for Cursor.
*
* Light transform - strips frontmatter, replaces PLUGIN_ROOT paths,
* removes require() statements and Task() calls, strips namespace prefixes.
*
* @param {string} content - Source command markdown content
* @param {Object} options
* @param {string} options.pluginInstallPath - Absolute path to plugin install dir
* @returns {string} Transformed command content
*/
function transformCommandForCursor(content, options) {
const { pluginInstallPath } = options;
// Strip existing frontmatter if present
if (content.startsWith('---')) {
content = content.replace(/^---\n[\s\S]*?\n---\n?/, '');
}
// Replace PLUGIN_ROOT paths with actual install path
content = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$CLAUDE_PLUGIN_ROOT/g, () => pluginInstallPath);
content = content.replace(/\$\{PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$PLUGIN_ROOT/g, () => pluginInstallPath);
// Strip require() statements
content = content.replace(/(?:const|let|var)\s+\{?[^}=\n]+\}?\s*=\s*require\s*\([^)]+\);?/g, '');
content = content.replace(/require\s*\(['"][^'"]+['"]\)/g, '');
// Strip Claude-specific syntax: Task tool calls (handles one level of nested braces)
content = content.replace(/await\s+Task\s*\(\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}\s*\);?/g, (match) => {
const agentMatch = match.match(/subagent_type:\s*["'](?:[^"':]+:)?([^"']+)["']/);
if (agentMatch) {
return `Invoke the ${agentMatch[1]} agent`;
}
return '';
});
// Strip plugin namespacing (e.g. next-task:agent-name -> agent-name)
content = content.replace(/(?:next-task|deslop|ship|sync-docs|audit-project|enhance|perf|repo-map|drift-detect|consult|debate|learn|web-ctl):([a-z][a-z0-9-]*)/g, '$1');
return content;
}
/**
* Transform skill content for Kiro.
*
* Minimal transform - Kiro reads standard SKILL.md format natively so we
* preserve it. Only replaces PLUGIN_ROOT paths and strips namespace prefixes.
*
* @param {string} content - Source SKILL.md content
* @param {Object} options
* @param {string} options.pluginInstallPath - Absolute path to plugin install dir
* @returns {string} Transformed skill content
*/
function transformSkillForKiro(content, options) {
const { pluginInstallPath } = options;
content = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$CLAUDE_PLUGIN_ROOT/g, () => pluginInstallPath);
content = content.replace(/\$\{PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$PLUGIN_ROOT/g, () => pluginInstallPath);
content = content.replace(/(?:next-task|deslop|ship|sync-docs|audit-project|enhance|perf|repo-map|drift-detect|consult|debate|learn|web-ctl):([a-z][a-z0-9-]*)/g, '$1');
return content;
}
/**
* Transform command content for Kiro prompt files.
*
* Strips existing frontmatter, prepends inclusion: manual frontmatter,
* replaces PLUGIN_ROOT paths, removes require()/Task() calls, strips namespaces.
*/
function transformCommandForKiro(content, options) {
const { pluginInstallPath, name = '', description = '' } = options;
if (content.startsWith('---')) {
content = content.replace(/^---\n[\s\S]*?\n---\n?/, '');
}
const cleanDescription = description.replace(/[\x00-\x1f\x7f]/g, ' ');
const escapedDescription = cleanDescription.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
let frontmatter = '---\n';
frontmatter += 'inclusion: manual\n';
if (name) frontmatter += `name: "${name}"\n`;
if (description) frontmatter += `description: "${escapedDescription}"\n`;
frontmatter += '---\n';
content = frontmatter + content;
content = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$CLAUDE_PLUGIN_ROOT/g, () => pluginInstallPath);
content = content.replace(/\$\{PLUGIN_ROOT\}/g, () => pluginInstallPath);
content = content.replace(/\$PLUGIN_ROOT/g, () => pluginInstallPath);
content = content.replace(/(?:const|let|var)\s+\{?[^}=\n]+\}?\s*=\s*require\s*\([^)]+\);?/g, '');
content = content.replace(/require\s*\(['"][^'"]+['"]\)/g, '');
// Transform code blocks containing Promise.all + Task() (parallel reviewer spawns).
// The bare Task() regex below can't reach inside fenced code blocks.
// Fence boundaries must be at line start (^```) to avoid matching backtick
// template literals inside the code as false fence endings.
content = content.replace(/^```(?:javascript|js)?\n([\s\S]*?)^```$/gm, (fullBlock, codeContent) => {
if (!codeContent.includes('Promise.all') || !codeContent.includes('Task(')) return fullBlock;
// Use lazy [\s\S]*? for the template literal body: it stops at the first backtick and
// naturally matches any character including standalone $ (e.g. $100, $BUDGET).
const taskMatches = [...codeContent.matchAll(/Task\s*\(\s*\{[\s\S]*?subagent_type:\s*['"](?:[^"':]+:)?([^'"]+)['"][\s\S]*?prompt:\s*`([\s\S]*?)`/gs)];
if (taskMatches.length < 2) return fullBlock;
const delegations = taskMatches.map(m => {
const agent = m[1];
const promptFirstLine = m[2].split('\n').find(l => l.trim()) || '';
return `Delegate to the \`${agent}\` subagent:\n> ${promptFirstLine.trim()}`;
});
let result = delegations.join('\n\n');
const hasReviewKeyword = delegations.some(d =>
/review|quality|security|performance|test|coverage/i.test(d)
);
if (delegations.length >= 4 && hasReviewKeyword) {
result = `**Review phase (Kiro - max 4 agents, fallback to 2 sequential):**\n\nTry delegating to these subagents (experimental parallel spawning):\n\n${result}\n\nIf parallel spawning is unavailable, run 2 combined reviewers sequentially:\n1. Delegate to the \`reviewer-quality-security\` subagent (code quality + security)\n2. Then delegate to the \`reviewer-perf-test\` subagent (performance + test coverage)\n\nAggregate all findings from whichever execution path succeeded.`;
}
return result;
});
// Transform bare Task() calls outside code blocks
content = content.replace(/await\s+Task\s*\(\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}\s*\);?/g, (match) => {
const agentMatch = match.match(/subagent_type:\s*["'](?:[^"':]+:)?([^"']+)["']/);
const promptMatch = match.match(/prompt:\s*[`"']([\s\S]*?)[`"']/);
if (agentMatch) {
const agentName = agentMatch[1];
const prompt = promptMatch ? promptMatch[1].replace(/\\n/g, '\n').trim() : '';
if (prompt) {
return `Delegate to the \`${agentName}\` subagent:\n> ${prompt.split('\n')[0]}`;
}
return `Delegate to the \`${agentName}\` subagent.`;
}
return '';
});
// Transform AskUserQuestion to markdown prompt for Kiro chat
content = content.replace(/(?:await\s+)?AskUserQuestion\s*\(\s*\{[\s\S]*?\}\s*\);?/g, (match) => {
const questionMatch = match.match(/question:\s*["'`]([\s\S]*?)["'`]/);
const question = questionMatch ? questionMatch[1] : 'Please choose:';
const optionMatches = [...match.matchAll(/label:\s*["'`]([^"'`]+)["'`][\s\S]*?description:\s*["'`]([^"'`]+)["'`]/g)];
if (optionMatches.length > 0) {
const options = optionMatches.map((m, i) => `${i + 1}. **${m[1]}** - ${m[2]}`).join('\n');
return `**${question}**\n\n${options}\n\nReply with the number or name of your choice.`;
}
return `**${question}**\n\nReply in chat with your choice.`;
});
content = content.replace(/(?:next-task|deslop|ship|sync-docs|audit-project|enhance|perf|repo-map|drift-detect|consult|debate|learn|web-ctl):([a-z][a-z0-9-]*)/g, '$1');
// Batch parallel reviewer delegations for Kiro's agent limit.
// Detects 4+ consecutive "Delegate to" lines with review-related names
// and rewrites as try-4-then-fallback-to-2 pattern.
const reviewerBatchPattern = /((?:Delegate to the `[^`]*` subagent[^\n]*\n){4,})/g;
content = content.replace(reviewerBatchPattern, (block) => {
const delegations = block.match(/Delegate to the `([^`]+)` subagent/g) || [];
if (delegations.length < 4) return block;
const hasReviewKeyword = delegations.some(d =>
/review|quality|security|performance|test|coverage/i.test(d)
);
if (!hasReviewKeyword) return block;
return `**Review phase (Kiro - max 4 agents, fallback to 2 sequential):**
Try delegating to these subagents (experimental parallel spawning):
${block}
If parallel spawning is unavailable, run 2 combined reviewers sequentially:
1. Delegate to the \`reviewer-quality-security\` subagent (code quality + security)
2. Then delegate to the \`reviewer-perf-test\` subagent (performance + test coverage)
Aggregate all findings from whichever execution path succeeded.\n`;
});
return content;
}
/**
* Transform agent markdown+frontmatter to Kiro JSON format.
*
* Parses frontmatter for name/description/model/tools, uses body as prompt.
* Returns a JSON string matching Kiro's agent schema.
*/
function transformAgentForKiro(content, options) {
const { pluginInstallPath } = options || {};
const frontmatter = discovery.parseFrontmatter(content);
let body = content;
if (content.startsWith('---')) {
const endIdx = content.indexOf('\n---', 3);
if (endIdx !== -1) {
body = content.substring(endIdx + 4).replace(/^\n/, '');
}
}
if (pluginInstallPath) {
body = body.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginInstallPath);
body = body.replace(/\$CLAUDE_PLUGIN_ROOT/g, () => pluginInstallPath);
body = body.replace(/\$\{PLUGIN_ROOT\}/g, () => pluginInstallPath);
body = body.replace(/\$PLUGIN_ROOT/g, () => pluginInstallPath);
}
body = body.replace(/(?:next-task|deslop|ship|sync-docs|audit-project|enhance|perf|repo-map|drift-detect|consult|debate|learn|web-ctl):([a-z][a-z0-9-]*)/g, '$1');
const agent = {
name: frontmatter.name || '',
description: frontmatter.description || '',
prompt: body.trim()
};
if (frontmatter.tools) {
// parseFrontmatter returns arrays for YAML list syntax, string for inline
const toolItems = Array.isArray(frontmatter.tools)
? frontmatter.tools.map(t => t.toLowerCase())
: [frontmatter.tools.toLowerCase()];
const toolStr = toolItems.join(' ');
const tools = [];
if (toolStr.includes('read')) tools.push('read');
if (toolStr.includes('edit') || toolStr.includes('write')) tools.push('write');
if (toolStr.includes('bash') || toolStr.includes('shell')) tools.push('shell');
if (toolStr.includes('glob')) tools.push('read');
if (toolStr.includes('grep')) tools.push('read');
if (toolStr.includes('task') || toolStr.includes('agent')) tools.push('shell');
if (toolStr.includes('web') || toolStr.includes('fetch')) tools.push('shell');
if (toolStr.includes('notebook')) tools.push('write');
if (toolStr.includes('lsp')) tools.push('read');
const deduped = [...new Set(tools)];
agent.tools = deduped.length > 0 ? deduped : ['read'];
} else {
agent.tools = ['read'];
}
agent.resources = ['file://.kiro/prompts/**/*.md'];
return JSON.stringify(agent, null, 2);
}
/**
* Generate a combined reviewer agent JSON for Kiro's 4-agent limit.
* Merges multiple review responsibilities into a single agent.
*
* @param {Array<{name: string, focus: string}>} roles - Review passes to combine
* @param {string} name - Agent name
* @param {string} description - Agent description
* @returns {string} JSON string for .kiro/agents/*.json
*/
function generateCombinedReviewerAgent(roles, name, description) {
const sections = roles.map(r =>
`## ${r.name} Review\n\nFocus: ${r.focus}`
).join('\n\n---\n\n');
const agent = {
name,
description,
prompt: `You are a combined code reviewer covering multiple review passes in a single session.\n\n${sections}\n\nFor each file you review, check ALL of the above review dimensions. Return findings as a JSON array with objects containing: pass (which review), file, line, severity (critical/high/medium/low), description, suggestion.`,
tools: ['read'],
resources: ['file://.kiro/prompts/**/*.md'],
};
return JSON.stringify(agent, null, 2);
}
module.exports = {
transformBodyForOpenCode,
transformCommandFrontmatterForOpenCode,
transformAgentFrontmatterForOpenCode,
transformSkillBodyForOpenCode,
transformForCodex,
transformRuleForCursor,
transformSkillForCursor,
transformCommandForCursor,
transformForCursor: transformRuleForCursor,
transformSkillForKiro,
transformCommandForKiro,
transformAgentForKiro,
generateCombinedReviewerAgent
};