-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathinstall-rules.ts
More file actions
612 lines (519 loc) · 16.4 KB
/
install-rules.ts
File metadata and controls
612 lines (519 loc) · 16.4 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
import { confirm, intro, isCancel, log, multiselect, outro } from "@clack/prompts";
import { ResolvedConfig } from "@trigger.dev/core/v3/build";
import chalk from "chalk";
import { Command, Option as CommandOption } from "commander";
import { join } from "node:path";
import * as semver from "semver";
import { z } from "zod";
import { OutroCommandError, wrapCommandAction } from "../cli/common.js";
import { loadConfig } from "../config.js";
import {
GithubRulesManifestLoader,
loadRulesManifest,
LocalRulesManifestLoader,
ManifestVersion,
RulesManifest,
RulesManifestVersionOption,
} from "../rules/manifest.js";
import { cliLink } from "../utilities/cliOutput.js";
import {
readConfigHasSeenRulesInstallPrompt,
readConfigLastRulesInstallPromptVersion,
writeConfigHasSeenRulesInstallPrompt,
writeConfigLastRulesInstallPromptVersion,
} from "../utilities/configFiles.js";
import { pathExists, readFile, safeWriteFile } from "../utilities/fileSystem.js";
import { printStandloneInitialBanner } from "../utilities/initialBanner.js";
import { logger } from "../utilities/logger.js";
import { tryCatch } from "@trigger.dev/core/utils";
const targets = [
"claude-code",
"cursor",
"vscode",
"windsurf",
"gemini-cli",
"cline",
"agents.md",
"amp",
"kilo",
"ruler",
] as const;
type TargetLabels = {
[key in (typeof targets)[number]]: string;
};
const targetLabels: TargetLabels = {
"claude-code": "Claude Code",
cursor: "Cursor",
vscode: "VSCode",
windsurf: "Windsurf",
"gemini-cli": "Gemini CLI",
cline: "Cline",
"agents.md": "AGENTS.md (OpenAI Codex CLI, Jules, OpenCode)",
amp: "Sourcegraph AMP",
kilo: "Kilo Code",
ruler: "Ruler",
};
type SupportedTargets = (typeof targets)[number];
type ResolvedTargets = SupportedTargets | "unsupported";
const InstallRulesCommandOptions = z.object({
target: z.enum(targets).array().optional(),
manifestPath: z.string().optional(),
branch: z.string().optional(),
logLevel: z.enum(["debug", "info", "log", "warn", "error", "none"]).optional(),
forceWizard: z.boolean().optional(),
});
type InstallRulesCommandOptions = z.infer<typeof InstallRulesCommandOptions>;
export function configureInstallRulesCommand(program: Command) {
return program
.command("install-rules")
.description("Install the Trigger.dev Agent rules files")
.option(
"--target <targets...>",
"Choose the target (or targets) to install the Trigger.dev rules into. We currently support: " +
targets.join(", ")
)
.option(
"-l, --log-level <level>",
"The CLI log level to use (debug, info, log, warn, error, none). This does not effect the log level of your trigger.dev tasks.",
"log"
)
.addOption(
new CommandOption(
"--manifest-path <path>",
"The path to the rules manifest file. This is useful if you want to install the rules from a local file."
).hideHelp()
)
.addOption(
new CommandOption(
"--branch <branch>",
"The branch to install the rules from, the default is main"
).hideHelp()
)
.addOption(
new CommandOption(
"--force-wizard",
"Force the rules install wizard to run even if the rules have already been installed."
).hideHelp()
)
.action(async (options) => {
await printStandloneInitialBanner(true);
await installRulesCommand(options);
});
}
export async function installRulesCommand(options: unknown) {
return await wrapCommandAction(
"installRulesCommand",
InstallRulesCommandOptions,
options,
async (opts) => {
if (opts.logLevel) {
logger.loggerLevel = opts.logLevel;
}
return await _installRulesCommand(opts);
}
);
}
async function _installRulesCommand(options: InstallRulesCommandOptions) {
if (options.forceWizard) {
await initiateRulesInstallWizard(options);
return;
}
intro("Welcome to the Trigger.dev Agent rules install wizard ");
const manifestLoader = options.manifestPath
? new LocalRulesManifestLoader(options.manifestPath)
: new GithubRulesManifestLoader(options.branch ?? "main");
const manifest = await loadRulesManifest(manifestLoader);
writeConfigLastRulesInstallPromptVersion(manifest.currentVersion);
writeConfigHasSeenRulesInstallPrompt(true);
await installRules(manifest, options);
outro("You're all set! ");
}
type InstallRulesResults = Array<InstallRulesResult>;
type InstallRulesResult = {
configPath: string;
targetName: (typeof targets)[number];
};
export type InstallRulesWizardOptions = {
target?: Array<(typeof targets)[number]>;
manifestPath?: string;
branch?: string;
};
export async function initiateRulesInstallWizard(options: InstallRulesWizardOptions) {
const manifestLoader = options.manifestPath
? new LocalRulesManifestLoader(options.manifestPath)
: new GithubRulesManifestLoader(options.branch ?? "main");
const manifest = await loadRulesManifest(manifestLoader);
const hasSeenRulesInstallPrompt = readConfigHasSeenRulesInstallPrompt();
if (!hasSeenRulesInstallPrompt) {
writeConfigHasSeenRulesInstallPrompt(true);
writeConfigLastRulesInstallPromptVersion(manifest.currentVersion);
const installChoice = await confirm({
message: "Would you like to install the Trigger.dev code agent rules?",
initialValue: true,
});
const skipInstall = isCancel(installChoice) || !installChoice;
if (skipInstall) {
return;
}
await installRules(manifest, options);
return;
}
const lastRulesInstallPromptVersion = readConfigLastRulesInstallPromptVersion();
if (!lastRulesInstallPromptVersion) {
writeConfigHasSeenRulesInstallPrompt(true);
writeConfigLastRulesInstallPromptVersion(manifest.currentVersion);
const installChoice = await confirm({
message: `A new version of the trigger.dev agent rules is available (${manifest.currentVersion}). Do you want to install it?`,
initialValue: true,
});
const skipInstall = isCancel(installChoice) || !installChoice;
if (skipInstall) {
return;
}
await installRules(manifest, options);
return;
}
if (semver.gt(manifest.currentVersion, lastRulesInstallPromptVersion)) {
writeConfigHasSeenRulesInstallPrompt(true);
writeConfigLastRulesInstallPromptVersion(manifest.currentVersion);
const confirmed = await confirm({
message: `A new version of the trigger.dev agent rules is available (${lastRulesInstallPromptVersion} → ${chalk.greenBright(
manifest.currentVersion
)}). Do you want to install it?`,
initialValue: true,
});
if (isCancel(confirmed) || !confirmed) {
return;
}
await installRules(manifest, options);
}
return;
}
async function installRules(manifest: RulesManifest, opts: InstallRulesWizardOptions) {
const [_, config] = await tryCatch(
loadConfig({
cwd: process.cwd(),
})
);
const currentVersion = await manifest.getCurrentVersion();
const targetNames = await resolveTargets(opts);
if (targetNames.length === 1 && targetNames.includes("unsupported")) {
handleUnsupportedTargetOnly(opts);
return;
}
const results = [];
for (const targetName of targetNames) {
const result = await installRulesForTarget(
targetName,
currentVersion,
opts,
config ?? undefined
);
if (result) {
results.push(result);
}
}
if (results.length > 0) {
log.step("Installed the following rules files:");
for (const r of results) {
const installationsByLocation = r.installations.reduce(
(acc, i) => {
if (!acc[i.location]) {
acc[i.location] = [];
}
acc[i.location]!.push(i.option);
return acc;
},
{} as Record<string, RulesManifestVersionOption[]>
);
const locationOutput = Object.entries(installationsByLocation).map(
([location]) => `${chalk.greenBright(location)}`
);
for (const message of locationOutput) {
log.info(message);
}
}
log.info(
`${cliLink("Learn how to use our rules", "https://trigger.dev/docs/agents/rules/overview")}`
);
}
}
function handleUnsupportedTargetOnly(options: InstallRulesCommandOptions): InstallRulesResults {
log.info(
`${cliLink("Install the rules manually", "https://trigger.dev/docs/agents/rules/overview")}`
);
return [];
}
async function installRulesForTarget(
targetName: ResolvedTargets,
currentVersion: ManifestVersion,
options: InstallRulesCommandOptions,
config?: ResolvedConfig
) {
if (targetName === "unsupported") {
// This should not happen as unsupported targets are handled separately
// but if it does, provide helpful output
log.message(
`${chalk.yellow("⚠")} Skipping unsupported target - see manual configuration above`
);
return;
}
const result = await performInstallForTarget(targetName, currentVersion, options, config);
return result;
}
async function performInstallForTarget(
targetName: (typeof targets)[number],
currentVersion: ManifestVersion,
cmdOptions: InstallRulesCommandOptions,
config?: ResolvedConfig
) {
const options = await resolveOptionsForTarget(targetName, currentVersion, cmdOptions);
const installations = await performInstallOptionsForTarget(targetName, options, config);
return {
targetName,
installations,
};
}
async function performInstallOptionsForTarget(
targetName: (typeof targets)[number],
options: Array<RulesManifestVersionOption>,
config?: ResolvedConfig
) {
const results = [];
for (const option of options) {
const result = await performInstallOptionForTarget(targetName, option, config);
results.push(result);
}
return results;
}
async function performInstallOptionForTarget(
targetName: (typeof targets)[number],
option: RulesManifestVersionOption,
config?: ResolvedConfig
) {
switch (option.installStrategy) {
case "default": {
return performInstallDefaultOptionForTarget(targetName, option, config);
}
case "claude-code-subagent": {
return performInstallClaudeCodeSubagentOptionForTarget(option);
}
default: {
throw new Error(`Unknown install strategy: ${option.installStrategy}`);
}
}
}
async function performInstallDefaultOptionForTarget(
targetName: (typeof targets)[number],
option: RulesManifestVersionOption,
config?: ResolvedConfig
) {
// Get the path to the rules file
const rulesFilePath = resolveRulesFilePathForTargetOption(targetName, option);
const rulesFileContents = await resolveRulesFileContentsForTarget(targetName, option, config);
const mergeStrategy = await resolveRulesFileMergeStrategyForTarget(targetName);
// Try and read the existing rules file
const rulesFileAbsolutePath = join(process.cwd(), rulesFilePath);
await writeToFile(rulesFileAbsolutePath, rulesFileContents, mergeStrategy, option.name);
return { option, location: rulesFilePath };
}
async function writeToFile(
path: string,
contents: string,
mergeStrategy: "overwrite" | "replace" = "overwrite",
sectionName: string
) {
const exists = await pathExists(path);
if (exists) {
switch (mergeStrategy) {
case "overwrite": {
await safeWriteFile(path, contents);
break;
}
case "replace": {
const existingContents = await readFile(path);
const pattern = new RegExp(
`<!-- TRIGGER.DEV ${sectionName} START -->.*?<!-- TRIGGER.DEV ${sectionName} END -->`,
"gs"
);
// If the section name is not found, just append the new content
if (!pattern.test(existingContents)) {
await safeWriteFile(path, existingContents + "\n\n" + contents);
break;
}
const updatedContent = existingContents.replace(pattern, contents);
await safeWriteFile(path, updatedContent);
break;
}
default: {
throw new Error(`Unknown merge strategy: ${mergeStrategy}`);
}
}
} else {
await safeWriteFile(path, contents);
}
}
async function performInstallClaudeCodeSubagentOptionForTarget(option: RulesManifestVersionOption) {
const rulesFilePath = ".claude/agents/trigger-dev-task-writer.md";
const rulesFileContents = option.contents;
await writeToFile(rulesFilePath, rulesFileContents, "overwrite", option.name);
return { option, location: rulesFilePath };
}
function resolveRulesFilePathForTargetOption(
targetName: (typeof targets)[number],
option: RulesManifestVersionOption
): string {
if (option.installStrategy === "claude-code-subagent") {
return ".claude/agents/trigger-dev-task-writer.md";
}
switch (targetName) {
case "claude-code": {
return "CLAUDE.md";
}
case "cursor": {
return `.cursor/rules/trigger.${option.name}.mdc`;
}
case "vscode": {
return `.github/instructions/trigger-${option.name}.instructions.md`;
}
case "windsurf": {
return `.windsurf/rules/trigger-${option.name}.md`;
}
case "gemini-cli": {
return `GEMINI.md`;
}
case "cline": {
return `.clinerules/trigger-${option.name}.md`;
}
case "agents.md": {
return "AGENTS.md";
}
case "amp": {
return "AGENT.md";
}
case "kilo": {
return `.kilocode/rules/trigger-${option.name}.md`;
}
case "ruler": {
return `.ruler/trigger-${option.name}.md`;
}
default: {
throw new Error(`Unknown target: ${targetName}`);
}
}
}
async function resolveRulesFileMergeStrategyForTarget(targetName: (typeof targets)[number]) {
switch (targetName) {
case "amp":
case "agents.md":
case "gemini-cli":
case "claude-code": {
return "replace";
}
default: {
return "overwrite";
}
}
}
async function resolveRulesFileContentsForTarget(
targetName: (typeof targets)[number],
option: RulesManifestVersionOption,
config?: ResolvedConfig
) {
switch (targetName) {
case "cursor": {
return $output(
frontmatter({
description: option.label,
globs: option.applyTo ?? "**/trigger/**/*.ts",
alwaysApply: false,
}),
option.contents
);
}
case "vscode": {
return $output(
frontmatter({
applyTo: option.applyTo ?? "**/trigger/**/*.ts",
}),
option.contents
);
}
case "windsurf": {
return $output(
frontmatter({
trigger: "glob",
globs: option.applyTo ?? "**/trigger/**/*.ts",
}),
option.contents
);
}
default: {
return $output(
`<!-- TRIGGER.DEV ${option.name} START -->`,
option.contents,
`<!-- TRIGGER.DEV ${option.name} END -->`
);
}
}
}
function frontmatter(data: Record<string, string | boolean>) {
return $output("---", ...Object.entries(data).map(([key, value]) => `${key}: ${value}`), "---");
}
function $output(...strings: string[]) {
return strings.map((s) => s).join("\n");
}
async function resolveOptionsForTarget(
targetName: (typeof targets)[number],
currentVersion: ManifestVersion,
cmdOptions: InstallRulesCommandOptions
) {
const possibleOptions = currentVersion.options.filter(
(option) => !option.client || option.client === targetName
);
const selectedOptions = await multiselect({
message: `Choose the rules you want to install for ${targetLabels[targetName]}`,
options: possibleOptions.map((option) => ({
value: option,
label: option.title,
hint: `${option.label} [~${option.tokens} tokens]`,
})),
required: true,
});
if (isCancel(selectedOptions)) {
throw new OutroCommandError("No options selected");
}
return selectedOptions;
}
async function resolveTargets(options: InstallRulesCommandOptions): Promise<ResolvedTargets[]> {
if (options.target) {
return options.target;
}
const selectOptions: Array<{
value: string;
label: string;
hint?: string;
}> = targets.map((target) => ({
value: target,
label: targetLabels[target],
}));
selectOptions.push({
value: "unsupported",
label: "Unsupported target",
hint: "We don't support this target yet, but you can still install the rules manually.",
});
const $selectOptions = selectOptions as Array<{
value: ResolvedTargets;
label: string;
hint?: string;
}>;
const selectedTargets = await multiselect({
message: "Select one or more targets to install the rules into",
options: $selectOptions,
required: true,
});
if (isCancel(selectedTargets)) {
throw new OutroCommandError("No targets selected");
}
return selectedTargets;
}